Reputation: 10193
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;
}
}
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?
Upvotes: 0
Views: 1971
Reputation: 59148
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;
}
It requires the GET_TASKS permission:
<uses-permission android:name="android.permission.GET_TASKS" />
Upvotes: 3