'how to detect when android app in background and foreground to handle some code

I need to know when user send my android app to background and then bring it back to foreground

when user send app to background I should perform server call and when back to foreground I have to clear some data

I have implemented it in the following way

public class MyApplication implements Application.ActivityLifecycleCallbacks {

@Override
    public void onActivityStopped(final Activity activity) {

// my logic goes here
}
}

but this way make a lot of ANRs in background, and when I put my logic inside AsyncTask it does not work and also it close app in background

can any one advice me how to meet my requirement in another way without generating ANR's



Solution 1:[1]

The easiest way to do it is (IMHO):

public class YourApplication extends Application implements LifecycleObserver {

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onAppBackgrounded() {
        Log.d("YourApplication", "YourApplication is in background");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onAppForegrounded() {
        Log.d("YourApplication", "YourApplication is in foreground");
    }
}

Do not forget to add in build.gradle:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.1"
}

Solution 2:[2]

Use :

@Override
    public void onStop()
    {
        super.onStop();
        // Do your stuff here when you are stopping your activity
    }

@Override
    public void onResume()
    {
        super.onResume();
        // Do your stuff here when comes back to activity
    }

This can also work when you lock your device onStop is called and when you reopen onResume is called.

Solution 3:[3]

In your Application class, you can add this code:

ProcessLifecycleOwner.get().getLifecycle().addObserver(new DefaultLifecycleObserver() {
        @Override
        public void onStop(@NonNull LifecycleOwner owner) { /* code here */ }});

More about it, here https://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner

Solution 4:[4]

private boolean isAppInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

and add below permission in manifest

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vladyslav Ulianytskyi
Solution 2 Muhammad Saad Rafique
Solution 3 guerdaa
Solution 4 Manoj Bhadane