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

∥☆過路亽.° 提交于 2019-12-05 20:36:27

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

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