Ways to bring an Android app in background to foreground

后端 未结 2 1394
遇见更好的自我
遇见更好的自我 2020-12-05 20:55

Here is the scenario:

AndroidManifest.xml defines a single Activity with android:launchMode=\"singleTask\". (This means there should be a single activit

相关标签:
2条回答
  • 2020-12-05 21:14

    In MyMainActivity definition (AndroidManifest.xml):

    <intent-filter>
     <action android:name="intent.my.action" />
     <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    

    Programmatically bringing application to foreground:

    Intent it = new Intent("intent.my.action");
    it.setComponent(new ComponentName(context.getPackageName(), MyMainActivity.class.getName()));
    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.getApplicationContext().startActivity(it);
    

    Note: context.startActivity(it) would NOT work when the context object is same as the activity one wants to bring up.

    0 讨论(0)
  • 2020-12-05 21:16

    Yes, what you are saying is correct, have a BroadcastReciever and fire an intent to your Activity to bring it to foreground. Word of caution however regarding the Activity life cycle.

    Android OS can take your activity from onPause() to onStop() and onDestroy() depending on system resources. So in such a case, your calling Activity will restart again, so take precautions there. Else, very easy to run into NullPointerExceptions

    0 讨论(0)
提交回复
热议问题