简体   繁体   中英

How not to start Activity if App in background

In my app I have two activities, A and B. A downloads some data and starts activity B when the data is downloaded - this is done through a BroadcastReceiver whose onReceive() method starts B through an intent.

My problem is that, when I my app goes to background while the data is still downloading (eg I start my app, then quickly click the "home" button, or switch app with the square "switch" button), my app comes back to foreground once the data is downloaded... annoying.

So far I've tried adding flags and setting actions on the intent to avoid that, including intent.setAction(Intent.ACTION_SCREEN_ON) , which might be close to the answer: it works nicely on a device running API 16 but not on mine which is running API 22.

Typically, one uses a service to carry out operations in the background. Services don't have a UI (for obvious reasons). By definition, an Activity is a foreground task - the behavior you're seeing is exactly what is supposed to happen.

I'd strongly suggest NOT trying to turn an activity into a service. You'd be working against the whole application life cycle when you could use a feature in Android designed for the very purpose you seek.

Here's a quick resource, I suggest you read more on services:

https://developer.android.com/training/best-background.html

The BroadcastReceiver for an Activity receives and processes Intent objects even when your app is in the background, but doesn't force your app to the foreground. If you want to notify the user about an event that happened in the background while your app was not visible, use a Notification . Never start an Activity in response to an incoming broadcast Intent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM