cannot start activity background in android 10 [ android Q ]

With Android Q, it is impossible to start an activity from the background automatically if your app does not include those exceptions listed in the link below.

https://developer.android.com/guide/components/activities/background-starts

Possible Solutions:

1- You can choose just show a service notification, and start pending intent with a click

2- You can use full-screen intents to show your intent immediately as shown in the other answer and suggested by Google.

For full-screen intent solution, as described in the official document

The system UI may choose to display a heads-up notification, instead
of launching this intent, while the user is using the device.

3- To start the activity automatically in the background, The most possible solution in my view is adding “SYSTEM_ALERT_WINDOW” to the manifest file. And ask for user permission once when the app opened the first time. (The user can give this permission manually – (Settings-Apps-Your App-Advanced- Draw over other apps))

Example code to request permission :

In Manifest:

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

Somewhere in app:

 public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE= 2323;

//if the user already granted the permission or the API is below Android 10 no need to ask for permission

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
 !Settings.canDrawOverlays(getContext()))
                    {RequestPermission()}

 private void RequestPermission() {
            // Check if Android M or higher
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // Show alert dialog to the user saying a separate permission is needed
                // Launch the settings activity if the user prefers
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getActivity().getPackageName()));
                startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
            }
        }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(getContext())) {
                    PermissionDenied();
                }
                else
                {
                 // Permission Granted-System will work
            }

        }
    }
 }

Leave a Comment