Android应用监听切换到后台/前台、熄屏的正确姿势

首先确保你的应用最低支持的API版本为14(Android 4.0 ICS)以上。

应用切换至后台

调用Application.onTrimMemory(int level),这个方法包含了一个等级叫TRIM_MEMORY_UI_HIDDEN,用于记录应用即将进入后台运行。

sample:

1
2
3
4
5
6
7
8
9
10
public class MyApplication extends Application { 
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
isBackground = true;
notifyBackground();
}
}
}

应用切换至前台

利用Application.registerActivityLifeStyleCallbacks(),如名字描述一样,可以覆写每一个生命周期函数。在这个例子中,在不侵入式改动每个Activity的代码的前提下,在Activity.onResume()中执行了代码。

sample:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MyApplication extends Application {
// ...
@Override
public void onCreate() {
super.onCreate();

registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
// ...
@Override
public void onActivityResumed(Activity activity) {
if (isBackground) {
isBackground = false;
notifyForeground();
}
}
// ...
});
}
// ...
}

手机熄屏

Application.onTrimMemory(int level)在手机熄屏时不回调怎么办?用Intent.ACTION_SCREEN_OFF注册BroadcastReceiver

sample:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyApplication extends Application {
// ...
@Override
public void onCreate() {
super.onCreate();
// ...
IntentFilter screenOffFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (isBackground) {
isBackground = false;
notifyForeground();
}
}
}, screenOffFilter);
}
}

参考博客:

[译]玩转Android Application的生命周期(不,不许覆盖那个Home键)

No, You Can Not Override the Home Button… But You Don’t Have To!