监听APP是否切换到了后台
来源:互联网 发布:淘宝商城口红 编辑:程序博客网 时间:2024/06/01 16:20
以前看有这么一段程序来判断应用是否被切换到了后台….
/** * 程序是否在前台运行 * * @return */ public boolean isAppOnForeground() { // Returns a list of application processes that are running on the // device ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); String packageName = getApplicationContext().getPackageName(); List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) return false; for (RunningAppProcessInfo appProcess : appProcesses) { // The name of the process that this object is associated with. if (appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } return false; }
今天在阅读Google官方的Training的时候,注意到这个一段文字
…..
To be notified when the user exits your UI, implement the onTrimMemory() callback in your Activity classes. You should use this method to listen for the TRIM_MEMORY_UI_HIDDEN level, which indicates your UI is now hidden from view and you should free resources that only your UI uses.
Notice that your app receives the onTrimMemory() callback with TRIM_MEMORY_UI_HIDDEN only when all the UI components of your app process become hidden from the user. …..
文中说到当用户退出你的UI,onTrimMemory() 就会被调用.同时会发送TRIM_MEMORY_UI_HIDDEN level这么一个东西叫我们监听.下面的notice是:只有用户隐藏你的应用UI组件才会有这个情况.
测试了一下,当你在任意一个Activity中这么写:
@Override public void onTrimMemory(int level) { super.onTrimMemory(level); if(level == TRIM_MEMORY_UI_HIDDEN){ Log.e("siyehua", "background..."); } }
不管是按Home键,还是有来电,还是你点击了状态栏的通知进入了其他的应用,都会调用这个方法,能正常的监听到应用被切换到了后台.完美监听应用是否切换到了后台(^o^)/~
Notice:只需要重写一个Activity的该方法即可.切换到其它Activity并不会触发该方法
- 监听APP是否切换到了后台
- 监听APP进入后台或切换到前台方案对比
- Android 监听app前台、后台状态切换的实现方案
- android见后台切换监听
- Android 监听前台后台切换
- 关于监听切换应用,app从后台返回进入锁屏界面
- Android WebView监听是否滚到到了头部
- RecyclerView滑动监听,判断是否滑动到了最后一个item
- android 监听后台到前台的切换
- home键监听(Android应用切换到后台监听)
- APP切入后台的事件监听
- App统一监听网络状态切换
- Android App前后台切换的监听
- App前后台切换的监听
- 监听用C/C++代码监听App是否被卸载
- Android 应用监听后台切换前台的方法
- jquery判断某个元素是否到了浏览器顶部 滚定监听
- RecyclerView——滑动监听,判断是否滑动到了最后一个item
- POJ 1014: Dividing
- Android L 64位兼容32 应用程序的认识
- 【python】os文件操作模块
- java编程面试题
- poj_3436
- 监听APP是否切换到了后台
- User Defined Runtime Attributes
- Python模拟switch
- birt初学中遇到为问题
- linux 配置如何识别U盘
- 实现数的反转
- 记录一下seekbar遇到的问题
- KM算法 详解+模板
- Ubuntu 14.04 64bit上使用IPython玩转Docker