Android - launch app from broadcast receiver

前端 未结 4 442
-上瘾入骨i
-上瘾入骨i 2021-01-12 00:08

I want the broadcast receiver to launch my app this way:

  1. If the app is not in the foreground or background, launch it as if it is launched from launcher.

4条回答
  •  有刺的猬
    2021-01-12 00:51

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent launch_intent = new  Intent(context, MainActivity.class);
        launch_intent.setComponent(new ComponentName("com.example.helloworld","com.example.helloworld.MainActivity");
        launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |INTENT.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        launch_intent.putExtra("some_data", "value");
        launch_intent.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(launch_intent);
    }
    

    It's this simple but unless you know the proper way when you try to get the extra data from your intent you will usually get a java null pointer exception.

    Use the onNewIntent() method to receive the extra data. If you want to know how comment below.

    Edit: Try the following. But what I don't understand is the first code which I gave you should work on its own. It has always worked for me. Have you made sure that you have copied the first code I gave you and pasted it without making any changes?

    Edit2: If that doesn't work try setting the flag to clearTaskOnLaunch instead of INTENT.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED

提交回复
热议问题