判断App整体处于前台还是后台
- - CSDN博客推荐文章转载请注明转自:[noyet12的博客](http://blog.csdn.net/u012975705)
博客原址:http://blog.csdn.net/u012975705/article/details/50109883. 上篇博客说道,在项目中使用Notification,想要的效果是在app退出前台工作时拉取后台数据,发现新动态则在通知栏提示用户.
转载请注明转自:[noyet12的博客](http://blog.csdn.net/u012975705)
博客原址:http://blog.csdn.net/u012975705/article/details/50109883
上篇博客说道,在项目中使用Notification,想要的效果是在app退出前台工作时拉取后台数据,发现新动态则在通知栏提示用户。要达到这个效果,就必须判断当前app是否处于前台工作,下面给出判断方法。
public boolean isAppOnForeground() {
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(
Context.ACTIVITY_SERVICE);
String packageName =getApplicationContext().getPackageName();
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
使用方式:
@Override
protected void onStop() {
super.onStop();
if (MainApplication.getInstance().getIsLogin()
&& !MainApplication.getInstance().isAppOnForeground()) {
mTask = new TimerTask() {
@Override
public void run() {
getNews();
}
};
mTimer = new Timer();
mTimer.schedule(mTask, 3 * 1000, 3 * 60 * 1000);
}
}