Search code examples
androidandroid-activitybroadcastreceiverandroid-broadcast

Android: start an Activity from a BroadcastReceiver


I want to start an activity from a BroadcastReceiver. The issue is that, when I try to launch it, i get an exception which tells me to add the "FLAG_ACTIVITY_NEW_TASK" flag, because my Receiver is registered into a Service and not into an Activity. So, I modified my code into the BroadcastReceiver class:

public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
    Intent start=new Intent(context,MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(start);
}

But my Activity does not start. Does anyone can explain me why I get this behaviour?


Solution

  • I guess it's just a typo.

    You have to call start.addFlags(), not intent.addFlags().