0

NotificationService system_server W Blocking custom toast from package com.example.androidtest due to package not in the foreground at time the toast was posted Blockquote

When I try to show a custom Toast right after request for permission On Android >= 11, I got the above warning and the custom Toast won't show

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
    }
}

I thought the app still in foreground but the Toast won't showing

Linh
  • 57,942
  • 23
  • 262
  • 279

1 Answers1

0

The above warning which I got is from NotificationManagerService#checkCanEnqueueToast

enter image description here

And, here is the **isPackageInForegroundForToast** function

enter image description here

There are many cases which will block the custom Toast showing, and in my above case, it because I show Toast behind a translucent Activity (which is Request Permission activity)

The solution for this can be

  • Not using custom Toast, use standard text toast
  • Show custom Toast later, when app in foreground
Linh
  • 57,942
  • 23
  • 262
  • 279