startActivity not working when calling from BroadcastReceiver
An activity can be started from Broadcast Receiver even if it is not a launcher. That shouldn't be the problem.
Try passing a unique requestid,
notificationIntent = new Intent();
notificationIntent.setAction(AppConstants.ACTION_ACTIVITY);
notificationIntent.putExtra("key", value);
mBuilder.setContentIntent(PendingIntent.getBroadcast(context, value, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT));
See this question.
For someone, who will look for a similar question. Beginning from Android Q it's restricted to launch any activity, when app in background. To launch your activity, you need to displaying a notification with PRIORITY_HIGH
and set the full-screen intent. So, totally you should have something like this:
//Create your intent as usual
Intent intent = new Intent(context, Activity.class);
intent.putExtra("key", value);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Build a pending intent
PendingIntent pIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
//Notification builder
NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setPriority(PRIORITY_HIGH)
.setFullScreenIntent(pIntent, true /*isHighPriority*/);
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(10, notifyBuilder.build())
This will display notification and will launch your activity immediately. And in your activity onStart()
you can dismiss a notification like below:
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(10);
NOTE: Don't forget to init channel. Beginning from Android O it's a mandatory thing
in order to start activity from BroadcastReciever you should add flag of FLAG_ACTIVITY_NEW_TASK
Intent imap =new Intent(context,MainActivity.class);
imap.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(imap);
Try using flags as follows for the intent.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
And for Pending intent use PendingIntent.FLAG_UPDATE_CURRENT