12

Here is the scenario:

AndroidManifest.xml defines a single Activity with android:launchMode="singleTask". (This means there should be a single activity in the stack throughout the entire application lifecycle, right ?)

During Activity.onCreate(), a broadcast receiver is programmatically created and listens for incomming SMS. The receiver remains active even after Activity.onPause() by design.

When the user is done with the application, he presses the device Home button which calls Activity.onPause() and the application disappears. The device shows then the Android home screen.

Upon receiving SMS, the broadcast receivers receives SMS and tries to show up the Activity via:

Intent it = new Intent(context, Akami.class);
it.setAction(Intent.ACTION_MAIN);
it.addCategory(Intent.CATEGORY_LAUNCHER);
it.setComponent(new ComponentName(context.getPackageName(), "MyActivity"));
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(it);

However, the activity is NOT showed up to the user.

  • a) Why ?
  • b) What are the possible ways to bring an Activty to foreground ?
David Andreoletti
  • 4,485
  • 4
  • 29
  • 51

2 Answers2

20

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.

David Andreoletti
  • 4,485
  • 4
  • 29
  • 51
  • Hi sir i have the same problem i want to open skype thorugh intent it opens for the first time. but when try to open it in seconds time .it did not give any error and nor it opens,how i can solve this problem – Mudassir Khan Sep 05 '18 at 13:32
  • @David this will not work in android 10 any other option. – Suhas Bachewar Feb 19 '21 at 05:31
1

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

Royston Pinto
  • 6,681
  • 2
  • 28
  • 46