Skip to content Skip to sidebar Skip to footer

Can't Start Activity From Broadcastreceiver On Android 10

I updated my OS version to android 10 last night, and since then the startActivity function inside the broadcast receiver is doing nothing. This is how I try to start the activity

Solution 1:

Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.

Use a high-priority notification, with an associated full-screen Intent, instead. See the documentation. This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly:

val pi = PendingIntent.getActivity(
  appContext,
  0,
  Intent(appContext, MainActivity::class.java),
  PendingIntent.FLAG_UPDATE_CURRENT
)

val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
  .setSmallIcon(R.drawable.ic_notification)
  .setContentTitle("Um, hi!")
  .setAutoCancel(true)
  .setPriority(NotificationCompat.PRIORITY_HIGH)
  .setFullScreenIntent(pi, true)

val mgr = appContext.getSystemService(NotificationManager::class.java)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
  && mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
) {
  mgr.createNotificationChannel(
    NotificationChannel(
      CHANNEL_WHATEVER,
      "Whatever",
      NotificationManager.IMPORTANCE_HIGH
    )
  )
}

mgr.notify(NOTIF_ID, builder.build())

Solution 2:

You can use SYSTEM_ALERT_WINDOW to force launch activity window in android 10, refer to this settingsuperposition setting:

<uses-permissionandroid:name="android.permission.SYSTEM_ALERT_WINDOW" /><uses-permissionandroid:name="android.permission.RECEIVE_BOOT_COMPLETED" /><activityandroid:name=".MainActivity"android:label="@string/app_name"
        <intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity><receiverandroid:name=".OnBootReceiver"android:enabled="true"android:exported="true"android:permission="android.permission.RECEIVE_BOOT_COMPLETED" ><intent-filter><actionandroid:name="android.intent.action.BOOT_COMPLETED" /><categoryandroid:name="android.intent.category.DEFAULT" /></intent-filter></receiver>

in launched app check permissions:

privatevoidRequestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + this.getPackageName()));
            startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
        } else {
            //Permission Granted-System will work
        }
    }
}

you will can user intent as android older versions

publicclassOnBootReceiverextendsBroadcastReceiver {
    privatestaticfinalStringTAG= OnBootReceiver.class.getSimpleName();

    @OverridepublicvoidonReceive(Context context, Intent intent) {
        try {
            Intentactivity=newIntent(context, MainActivity.class);
            activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(activity);
        } catch (Exception e){
            Log.d(TAG,e.getMessage()+"");
        }
    }
}

Solution 3:

Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.

So you need to have a high-level notification and when the user clicks on the notification your activity will be opened notifications

publicclassUIExampleReceiverextendsBroadcastReceiver {

publicstaticfinalStringTAG_NOTIFICATION="NOTIFICATION_MESSAGE";
publicstaticfinalStringCHANNEL_ID="channel_1111";
publicstaticfinalintNOTIFICATION_ID=111111;
privatestaticfinalStringTAG="Receiver";

@OverridepublicvoidonReceive(Context context, Intent intent) {

    try {

            // If android 10 or higherif (Build.VERSION.SDK_INT > Build.VERSION_CODES.P)
            {

                 startActivityNotification(context,NOTIFICATION_ID,context.getResources().getString(R.string.open_app), context.getResources().getString(R.string.click_app));

            }
            else
            {
                // If lower than Android 10, we use the normal method ever.Intentactivity=newIntent(context, ExampleActivity.class);
                activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(activity);
            }

    } catch (Exception e)
    {
        Log.d(TAG,e.getMessage()+"");
    }
}


 // notification method to support opening activities on Android 10publicstaticvoidstartActivityNotification(Context context, int notificationID, 
String title, String message) {

    NotificationManagermNotificationManager=
            (NotificationManager) 
   context.getSystemService(Context.NOTIFICATION_SERVICE);
    //Create GPSNotification builder
    NotificationCompat.Builder mBuilder;

    //Initialise ContentIntentIntentContentIntent=newIntent(context, ExampleActivity.class);
    ContentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
    Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntentContentPendingIntent= PendingIntent.getActivity(context,
            0,
            ContentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = newNotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(message)
            .setColor(context.getResources().getColor(R.color.colorPrimaryDark))
            .setAutoCancel(true)
            .setContentIntent(ContentPendingIntent)
            .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannelmChannel=newNotificationChannel(CHANNEL_ID,
                "Activity Opening Notification",
                NotificationManager.IMPORTANCE_HIGH);
        mChannel.enableLights(true);
        mChannel.enableVibration(true);
        mChannel.setDescription("Activity opening notification");

        mBuilder.setChannelId(CHANNEL_ID);

   Objects.requireNonNull(mNotificationManager).createNotificationChannel(mChannel);
    }

 Objects.requireNonNull(mNotificationManager).notify(TAG_NOTIFICATION,notificationID, 
 mBuilder.build());
    }

}

Post a Comment for "Can't Start Activity From Broadcastreceiver On Android 10"