1. 程式人生 > >判斷App整體處於前臺還是後臺

判斷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); } }