Android - launch app from broadcast receiver

前端 未结 4 452
-上瘾入骨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:49

    Since you need behaviour like

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

    2) If the app is in the background, bring it to the foreground with the state it was last in.

    3) If the app is in the foreground, do nothing.

    Consider:

    @Override
    public void onReceive(Context context, Intent intent) {
    
        Intent startIntent = context
                .getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
    
        startIntent.setFlags(
                        Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |
                        Intent.FLAG_ACTIVITY_NEW_TASK |
                        Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
        );
        context.startActivity(startIntent);
    }
    

提交回复
热议问题