1

I am trying find foreground or background for "push notification" using the following code but it executing both background and foreground. Any solution for this??

public static boolean isAppIsInBackground(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;
}
UnityTaru
  • 81
  • 2
  • 11
  • I've used this tutorial : https://medium.com/@iamsadesh/android-how-to-detect-when-app-goes-background-foreground-fd5a4d331f8a – Nikos Hidalgo Apr 05 '19 at 08:04
  • May be it will be better to use ProcessLifecycleOwner? It is provided by Android and works fine. I can share simple example. – Eugene Babich Apr 05 '19 at 08:37
  • Possible duplicate of [Checking if an Android application is running in the background](https://stackoverflow.com/questions/3667022/checking-if-an-android-application-is-running-in-the-background) – MurugananthamS Apr 05 '19 at 08:54

2 Answers2

0

So if I understand your question you want to check if your current thread is the main thread /some background thread, you can check it like this :

if(Looper.myLooper() == Looper.getMainLooper()){
  //you are on your main Thread (also called UI Thread)
}
Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
0

Make your Application class implement LifecycleObserver interface and you can define methods like shown below to get callbacks for app foreground and app background events

class MyApplication implements LifecycleObsercer {

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppBackgrounded() {
        Timber.d("App in background");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        Timber.d("App is in foreground");
    }
}