您的位置:首页 > 移动开发 > Android开发

监听Android应用前后台运行状态

2016-10-29 17:02 274 查看

监听Android应用前后台运行状态

核心内容

这篇文章主要是参考外文,编写的监听应用前后台状态的操作,但是我家领导有时候来看我写的博客,总说她看不懂,所以,我决定专门写一段他能看懂的,额如果想直接应用到项目中的,请直接绕过此段,直接copy下面的代码到自己的项目中使用即可,具体的文字说明也已经在给出的参考链接中说的很详细了,我就不重复造轮子了,还有特别说明我家领导,聪明伶俐,可爱活泼,胆识过人,英姿飒爽,善解人意有爱心,总之就是人很nice~优点太多,我家领导很低调不让我到处嚷嚷,我就不一一总结了啦啦啦啦啦啦啦啦~

实战代码

public class MyApplication extends Application {

// Starts as true in order to be notified on first launch
private boolean isBackground = true;

@Override
public void onCreate() {
super.onCreate();

listenForForeground();
listenForScreenTurningOff();
}

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

private void listenForScreenTurningOff() {
IntentFilter screenStateFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
isBackground = true;
notifyBackground();
}
}, screenStateFilter);
}

@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
isBackground = true;
notifyBackground();
}

}

private void notifyForeground() {
// This is where you can notify listeners, handle session tracking, etc
}

private void notifyBackground() {
// This is where you can notify listeners, handle session tracking, etc
}

public boolean isBackground() {
return isBackground;
}
}

总结

参考连接中文版:http://blog.csdn.net/qq284565035/article/details/51811590英文版:http://www.developerphil.com/no-you-can-not-override-the-home-button-but-you-dont-have-to/

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息