如何检测和计数,当活动进入从背景到前景 [英] How to detect and count when activity goes from background to foreground

查看:98
本文介绍了如何检测和计数,当活动进入从背景到前景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测和计数,当活动去从背景到前台(活动时可见,加大计)。我试图用标志的onPause() onResume()是这样的:

I want to detect and count when Activity goes from background to foreground (when activity is visible, increase count).I tried to use flag in onPause() and onResume() like this:

void onPause(){
    flag = true;
}

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

}

它的工作原理,当用户preSS 家居键,将重新启动应用程序,但是当我转移活动然后回到过去,它仍然增加了计数,因为它调用的onPause()。如何prevent是什么?或者,反正是有这个数?

It works when user press home key and relaunches the app, but when I transfer Activity then goes back, it still increases the count, because it calls onPause(). How to prevent that? Or is there anyway to count this?

推荐答案

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

Use this method to check wheter app is brought to background:

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权限:

It requires the GET_TASKS permission:

<uses-permission android:name="android.permission.GET_TASKS" />

这篇关于如何检测和计数,当活动进入从背景到前景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆