利用Application监听App处于前台和后台

之前有个需求,App从前台切换到后台,不需要做什么操作;从后台切换到前台,需要先验证屏锁密码。于是乎,搜索了一下,“利用Application监听App处于前台和后台”,找到了一个国外的big god的解决方案。不要问我是怎么找到的,做开发必备的技能,擅长检索,也是一种能力。致谢steveliles

...

废话不说了,直接上代码。

<pre>

public class ForegroundCallbacks implements Application.ActivityLifecycleCallbacks {

public static final long CHECK_DELAY = 500;
public static final String TAG = ForegroundCallbacks.class.getName();

public interface Listener {

    public void onBecameForeground();

    public void onBecameBackground();

}

private static ForegroundCallbacks instance;

private boolean foreground = false, paused = true;
private Handler handler = new Handler();
private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
private Runnable check;


public static ForegroundCallbacks init(Application application){
    if (instance == null) {
        instance = new ForegroundCallbacks();
        application.registerActivityLifecycleCallbacks(instance);
    }
    return instance;
}

public static ForegroundCallbacks get(Application application){
    if (instance == null) {
        init(application);
    }
    return instance;
}

public static ForegroundCallbacks get(Context ctx){
    if (instance == null) {
        Context appCtx = ctx.getApplicationContext();
        if (appCtx instanceof Application) {
            init((Application)appCtx);
        }
        throw new IllegalStateException(
            "Foreground is not initialised and " +
            "cannot obtain the Application object");
    }
    return instance;
}

public static ForegroundCallbacks get(){
    if (instance == null) {
        throw new IllegalStateException(
            "Foreground is not initialised - invoke " +
            "at least once with parameterised init/get");
    }
    return instance;
}

public boolean isForeground(){
    return foreground;
}

public boolean isBackground(){
    return !foreground;
}

public void addListener(Listener listener){
    listeners.add(listener);
}

public void removeListener(Listener listener){
    listeners.remove(listener);
}

@Override
public void onActivityResumed(Activity activity) {
    paused = false;
    boolean wasBackground = !foreground;
    foreground = true;

    if (check != null)
        handler.removeCallbacks(check);

    if (wasBackground){
        LogUtil.e("went foreground");
        for (Listener l : listeners) {
            try {
                l.onBecameForeground();
            } catch (Exception exc) {
                LogUtil.e("Listener threw exception!", exc);
            }
        }
    } else {
        LogUtil.e("still foreground");
    }
}

@Override
public void onActivityPaused(Activity activity) {
    paused = true;

    if (check != null)
        handler.removeCallbacks(check);

    handler.postDelayed(check = new Runnable(){
        @Override
        public void run() {
            if (foreground && paused) {
                foreground = false;
                LogUtil.e("went background");
                for (Listener l : listeners) {
                    try {
                        l.onBecameBackground();
                    } catch (Exception exc) {
                        LogUtil.e("Listener threw exception!", exc);
                    }
                }
            } else {
                LogUtil.e("still foreground");
            }
        }
    }, CHECK_DELAY);
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

@Override
public void onActivityStarted(Activity activity) {}

@Override
public void onActivityStopped(Activity activity) {}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

@Override
public void onActivityDestroyed(Activity activity) {}

}

</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 178,901评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,534评论 19 139
  • Android中的前台就是指用户可见,后台就是指用户不可见。对于Activity来说,可以通过生命周期,监听回到前...
    蓝灰_q阅读 4,003评论 0 2
  • 自从古老的iOS4以来,当用户点击home建的时候,你可以使你的APP们在内存中处于suspended(挂起)状态...
    木易林1阅读 3,344评论 1 4
  • 你离开了很久。 现在我的头像是窦唯,半夜爱看娄烨的文艺片,循环最多的歌曲是你离开了南京从此没有人和我说话。他们是你...
    陈乡阅读 188评论 0 2

友情链接更多精彩内容