监听应用的前后台切换

2020-10-19  本文已影响0人  狂奔的_土豆
public class LifecycleCallback implements Application.ActivityLifecycleCallbacks {
    private static final String TAG = "LifecycleCallback";
    private int count; 
    private boolean isForeground; 

    public boolean isForeground() {
        return isForeground; 
    }
     
     /**
     * 运行在主线程,如果需要添加一些相对耗时的操作,最好是在子线程操作
     */
    @Override 
    public void onActivityStarted(Activity activity) { 
        count ++; 
         isForeground = false; 
    }
    @Override 
    public void onActivityStopped(Activity activity) { 
        count --; 
        if(count == 0) {
            isForeground = true; 
        }else{
            isForeground = false; 
        }
    }
public class MyApplication extends Application {
    @Override 
    public void onCreate() {
        super.onCreate(); 
        //注册回调
        LifecycleCallback callbacks = new LifecycleCallback();
        registerActivityLifecycleCallbacks(callbacks); 
    }
}
上一篇下一篇

猜你喜欢

热点阅读