/**
* 程序是否在前台运行
*
*/
public boolean isAppOnForeground() {
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
String packageName = getApplicationContext().getPackageName();
/**
* 获取Android设备中所有正在运行的App
*/
List
.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
这是我在网上找到的例子,主要的实现原理就是,使用ActivityManager,首先拿到自己App的包名,再拿到Android设备中所有正在运行的App包名,然后对所有的App进行遍历,通过判断正在运行的App中包名有没有和自己的App相等,从而判断自己的App是否退到后台.
@Override
protected void onPause() {
super.onPause();
if(!isAppOnForeground()){
Toast.makeText(getApplicationContext(), TAG+"onPause:",
Toast.LENGTH_SHORT).show();
}else {
sendBroadcast(new Intent(NotificationIntentReceiver.ACTION_ENABLE_MESSAGES)
.setClass(this, NotificationIntentReceiver.class));
Toast.makeText(getApplicationContext(), TAG+"后台运行1",
Toast.LENGTH_SHORT).show();
}
}
然后在onPause()方法中,进行判断,上面代码中实现的是,App退出后台就发送广播,然后在广播中执行Notification,然后在回到Activity时,在onResume()中清除应该清除Notification.