Niko Gamulin Niko Gamulin - 2 months ago 12
Android Question

how to start activity when the main activity is running in background?

I created an application which enables the user to set whether he wants to receive notification while the application runs in background mode. If the notifications are enabled an activity should be started (the dialog should appear on the screen).

I tried to enabled it the following way:

@Override
public void onProductsResponse(List<Product> products) {
this.products = products;
moboolo.setProducts(products);
if(moboolo.getAutomaticNotificationsMode() != 0 && products.size() > 0){
if(isRunningInBackground)
{
Intent intent = new Intent(this, ProductListActivity.class);
intent.setAction(Intent.ACTION_MAIN);
startActivity(intent);
}
}
drawProducts(products);

}


this is the method from main activity. When onPause() is executed isRunningInBackground is set true.
When I tried to debug it when the main application was running in the background the line

startActivity(intent) had no effect (the activity didn't appear).

Does anyone know how to midify the logic in order to start an activity from the main activity when the main activity is running in the background (after onPause() is called)?

Thank you.

Answer

You can't force an Activity to appear from an application running the background. The documentation says:

If the application is running in the background and needs the user's attention, the application should create a notificaiton that allows the user to respond at his or her convenience.

If your Activity is paused the user may be doing something else in a different application and probably doesn't want your Activity suddenly appearing on top of what they are currently doing.

You should be using a Status Bar Notification. This allows your application to put an icon in the Status Bar. The user can then slide down the Status Bar drawer and click on your notification to open your application and show the relevant Activity. This is the way the vast majority of Android apps notify the user when running in the background.

Comments