简体   繁体   中英

Determining onCreate() VS onRestartingFromBackGround() in Android app

I'm having a small problem with the Android app I'm designing.

I need to run some code whenever either of these 2 events happen:

1.  The app is NOT running in the background, so the user launches it.
2.  The app IS already running in the background, so the user is really 
    just re-opening it.
(I only need to run the code once, not twice.)

No matter where I put the call to my code (onCreate, onStart, onRestart, onResume, etc) I always have undesired affects:

A. My code gets run twice when #2 happens.
B. My code runs even when the user is just moving from 
   MAIN to a SUB-ACTIVITY, then back to MAIN again.
C. My code doesn't run at all.

Isn't there come kind of distinction I can make to determine: onCreate() and onRestartingFromBackGround()?

I thought I could use onRestart(), but I was VERY surprised to see that onRestart() runs even just when I do #B. (Is #B really considered a "restart" of my app????)

From a pure java standpoint, you could use a loading thread for when the icon is first pressed. This loading thread can poll the phone to see if the main activity thread is currently running or not, then from your loading thread, move to the correct piece of code. For ANDROID, I THINK, that you will poll the process name, or process ID...anyone ever poll the OS for processes??

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