Ways to bring an Android app in background to foreground
Asked Answered
S

2

13

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 ?
Sisely answered 11/10, 2012 at 11:13 Comment(2)
It is not clear what the problem is. Is the activity not coming to the foreground? Is there a crash?Bard
@tencent: I edited my post. Yes, the activity is NOT coming to the foreground. No crash.Sisely
S
21

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.

Sisely answered 15/10, 2012 at 9:21 Comment(2)
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 problemClegg
@David this will not work in android 10 any other option.Dehypnotize
D
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

Dissenter answered 11/10, 2012 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.