在 Android 中阻止包中的自定义 toast

问题描述 投票:0回答:1

NotificationService system_server W 由于发布 toast 时包不在前台,因此阻止 com.example.androidtest 包中的自定义 toast 块引用

当我尝试在请求许可后立即显示自定义 Toast 时 在 Android >= 11 上,我收到上述警告,并且自定义 Toast 不会显示

private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->

}

override fun onCreate(savedInstanceState: Bundle?) {
    ...

    buttonCamera.setOnClickListener {
        requestPermissionLauncher.launch(android.Manifest.permission.CAMERA)
        makeCommonToast("ABc").show()
    }
}

private fun makeCustomToast(message: CharSequence): Toast {
    return Toast.makeText(context, "", Toast.LENGTH_LONG).apply {
        val rootView = LayoutInflater.from(context).inflate(R.layout.my_custom_toast, null)
        view = rootView
        val textView = rootView.findViewById<TextView>(R.id.text_message)
        textView.text = message
    }
}

我以为应用程序仍在前台,但 Toast 不会显示

android android-toast custom-toast
1个回答
0
投票

我收到的上述警告来自

NotificationManagerService#checkCanEnqueueToast

而且,这是

**isPackageInForegroundForToast**
函数

有很多情况会阻止自定义Toast的显示,在我上面的例子中,这是因为我在半透明的Activity(即请求权限活动)后面显示了Toast

这个问题的解决方案可以是

  • 不使用自定义Toast,使用标准文本toast
  • 稍后当应用程序位于前台时显示自定义 Toast
© www.soinside.com 2019 - 2024. All rights reserved.