application 有用的监听

来源:互联网 发布:java可以清理cookie吗 编辑:程序博客网 时间:2024/06/05 07:11
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;    }}
0 0
原创粉丝点击