0

我想检测并计算Activity从背景到前景的时间(当活动可见时,增加计数)。我尝试使用标志onPause()onResume()如下所示:

void onPause(){
    flag = true;
}

void onResume(){
if(flag){
 //save to shared reference.  
   saveCount(getCount(count) + 1);
 flag = false;
}

}

它在用户按下home键并重新启动应用程序时起作用,但是当我转移Activity然后返回时,它仍然会增加计数,因为它调用 onPause()。如何防止这种情况?或者无论如何都要计算这个?

4

1 回答 1

3

使用此方法检查应用程序是否被带到后台:

private boolean isApplicationBroughtToBackground(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;
}

它需要 GET_TASKS 权限:

<uses-permission android:name="android.permission.GET_TASKS" />
于 2012-07-23T08:07:50.167 回答