How to identify app when it goes in background in Kitkat (4.4)?

这一生的挚爱 提交于 2019-12-07 15:41:30

问题


I am trying to detect app when it goes in background. Everything works perfect but in New Android Version 4.4(Kitkat) its not working. I am unable to find out what's the issue with Kitkat. It always returns false.

public static boolean inBackground(final 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;
}

回答1:


Override Activity.onPause() or Activity.onStop(), depending on which level of background you want.




回答2:


I'm having the same problem. The solution is to call this method on onStop().

To simplify, I extend the Activities where I need to detect when app goes to background to class below.

public abstract class MyActivity extends Activity {

    @Override
    public void onStop() {

        super.onStop();

        if (isApplicationSentToBackground(this)){

            // handle app going into background here
        }
    }

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


来源:https://stackoverflow.com/questions/20500432/how-to-identify-app-when-it-goes-in-background-in-kitkat-4-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!