3 回答
TA贡献1846条经验 获得超7个赞
ActivityLifecycleCallbacks
getRunningTasks()
Activity
onResumed()
/onPaused()
java:
public class MyLifecycleHandler implements ActivityLifecycleCallbacks { // I use four separate variables here. You can, of course, just use two and // increment/decrement them instead of using four and incrementing them all. private int resumed; private int paused; private int started; private int stopped; @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityDestroyed(Activity activity) { } @Override public void onActivityResumed(Activity activity) { ++resumed; } @Override public void onActivityPaused(Activity activity) { ++paused; android.util.Log.w("test", "application is in foreground: " + (resumed > paused)); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityStarted(Activity activity) { ++started; } @Override public void onActivityStopped(Activity activity) { ++stopped; android.util.Log.w("test", "application is visible: " + (started > stopped)); } // If you want a static function you can use to check if your application is // foreground/background, you can use the following: /* // Replace the four variables above with these four private static int resumed; private static int paused; private static int started; private static int stopped; // And these two public static functions public static boolean isApplicationVisible() { return started > stopped; } public static boolean isApplicationInForeground() { return resumed > paused; } */}
java:
// Don't forget to add it to your manifest by doing// <application android:name="your.package.MyApplication" ...public class MyApplication extends Application { @Override public void onCreate() { // Simply add the handler, and that's it! No need to add any code // to every activity. Everything is contained in MyLifecycleHandler // with just a few lines of code. Now *that's* nice. registerActivityLifecycleCallbacks(new MyLifecycleHandler()); }}
onStop()
onStop()
请注意,在内存不足的情况下,这个方法可能永远不会被调用,因为系统没有足够的内存来使您的活动的进程在其onPace()方法被调用之后继续运行。
MyLifecycleHandler
0
.
这是否适用于配置更改?
configChanges=orientation|screensize
(|
onCreate -> onStart -> onResume -> (now rotate) -> onPause -> onStop -> onDestroy -> onCreate -> onStart -> onResume
configChanges
configChanges
一份说明:
Activity
onPause()
super.onPause()
Activity
onStop()
super.onStop()
.
- 3 回答
- 0 关注
- 984 浏览
添加回答
举报