Search code examples
androidbroadcastreceiver

Can't start the activity from the BroadcastReceiver in Android 9 or later


I am unable to start the activity from the Broadcastreceiver in Android 9 or later. I know this might be duplicate question but I didn't get the solution, so asking.

Here is my code:

Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

Please help me.


Solution

  • When I try running your code on an emulator with Android 10, I get the following Logcat entries:

    2019-12-30 19:26:11.579 2048-2096/system_process I/ActivityManager: Start proc 5504:com.example.broadcastreceivertest/u0a133 for broadcast {com.example.broadcastreceivertest/com.example.broadcastreceivertest.MyReceiver}

    2019-12-30 19:26:11.695 5504-5504/com.example.broadcastreceivertest E/TEST: onReceive()

    2019-12-30 19:26:11.730 2048-5522/system_process I/ActivityTaskManager: START u0 {flg=0x10000000 cmp=com.example.broadcastreceivertest/.MainActivity} from uid 10133

    2019-12-30 19:26:11.738 2048-5522/system_process W/ActivityTaskManager: Background activity start [callingPackage: com.example.broadcastreceivertest; callingUid: 10133; isCallingUidForeground: false; isCallingUidPersistentSystemProcess: false; realCallingUid: 10133; isRealCallingUidForeground: false; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; isBgStartWhitelisted: false; intent: Intent { flg=0x10000000 cmp=com.example.broadcastreceivertest/.MainActivity }; callerApp: ProcessRecord{5ddbd7 5504:com.example.broadcastreceivertest/u0a133}]

    2019-12-30 19:32:12.313 2048-2095/system_process I/ActivityManager: Killing 5504:com.example.broadcastreceivertest/u0a133 (adj 985): empty #17

    The interesting part is

    W/ActivityTaskManager: Background activity start

    Devices running Android 10 (API level 29) and higher have Restrictions on starting activities from the background. This means you can no longer start an Activity from a BroadcastReceiver. It is recommended to use a notification instead, so that users can start the Activity by tapping on the notification.

    There are some exceptions to this behavior (see the linked page).

    An easy way out may be to add

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

    to your Manifest file. (Note: when installing the app via Android Studio, you have to manually grant the permission once the app is installed)

    That being said, it may be wiser to switch over to showing a notification - depending on your use case and your distribution channels.

    Since it's possible to show even a full screen notification for the "problem API levels" 29 and higher, consider showing the Activity/ showing a notification in onReceive(), depending on the device's android version.