Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to bring an Android app in background to foreground

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 ?
like image 453
David Andreoletti Avatar asked Oct 11 '12 11:10

David Andreoletti


People also ask

How do I move an app from the background to the foreground?

Use moveTaskToBack() to move your app to the background. After Home button is pressed, it takes 5 seconds to bring the app back to foreground.

What happens when app goes in background android?

An app is running in the background when both the following conditions are satisfied: None of the app's activities are currently visible to the user. The app isn't running any foreground services that started while an activity from the app was visible to the user.


1 Answers

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.

like image 94
David Andreoletti Avatar answered Oct 12 '22 08:10

David Andreoletti