我是在做测试我的apk监听短信功能是,发现了这样一个问题:当移动端还处在我的apk状态时,来了一条短信,我并未退出我的apk,就去查看了短信,这时看完短信按了退出键,正常是只返回到我的apk离开时的界面,可我的apk这时也执行了返回键的功能。
因此为了避免此情况的发生,我加了这个函数,用来判断我的apk当前处于前台还是后台。
/**
*Determine the current application is in the foreground or background
*
* @param context
* @return
*/
private boolean isApplicationBroughtToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
当我的apk处于后台时,isApplicationBroughtToBackground返回true。
这个是需要权限的 在AndroidManifest.xml中添加
<uses-permission android:name="android.permission.GET_TASKS" />