简体   繁体   中英

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

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"
}

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.

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

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM