Android app中經過Broadcast Receiver接受Alarm的定時消息,以便發送Notification;這裏發送Notification前要求app自身不在運行狀態;檢測app自身是否在前臺的一個宗旨是:判斷app全部的Activity是否有在前臺的;在網上找了好長一段時間,發現一個我的以爲比較好的斷定方法:java
<!-- lang: java --> public boolean isAppForground(Context mContext) { ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(mContext.getPackageName())) { return false; } } return true; }
注:getRunningTasks方法,Android Document中說API level 21開始該方法將deprecated, 暫時沒去測試,不知道會有多大影響app