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

监听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;
}
}

总结


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值