How to check whether a activity is foreground and bring it to background when it is foreground?












0















I hope to define whether a activity is foreground in Android, and bring it to background when it is foreground. How can I do it?



You know the <uses-permission android:name="android.permission.GET_TASKS"/> is Deprecated!



Sample Code



private boolean isTopActivity(String activityName){
ActivityManager manager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
String cmpNameTemp = null;
if(runningTaskInfos != null){
cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
}
if(cmpNameTemp == null){
return false;
}
return cmpNameTemp.equals(activityName);
}









share|improve this question





























    0















    I hope to define whether a activity is foreground in Android, and bring it to background when it is foreground. How can I do it?



    You know the <uses-permission android:name="android.permission.GET_TASKS"/> is Deprecated!



    Sample Code



    private boolean isTopActivity(String activityName){
    ActivityManager manager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
    String cmpNameTemp = null;
    if(runningTaskInfos != null){
    cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
    }
    if(cmpNameTemp == null){
    return false;
    }
    return cmpNameTemp.equals(activityName);
    }









    share|improve this question



























      0












      0








      0








      I hope to define whether a activity is foreground in Android, and bring it to background when it is foreground. How can I do it?



      You know the <uses-permission android:name="android.permission.GET_TASKS"/> is Deprecated!



      Sample Code



      private boolean isTopActivity(String activityName){
      ActivityManager manager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
      List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
      String cmpNameTemp = null;
      if(runningTaskInfos != null){
      cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
      }
      if(cmpNameTemp == null){
      return false;
      }
      return cmpNameTemp.equals(activityName);
      }









      share|improve this question
















      I hope to define whether a activity is foreground in Android, and bring it to background when it is foreground. How can I do it?



      You know the <uses-permission android:name="android.permission.GET_TASKS"/> is Deprecated!



      Sample Code



      private boolean isTopActivity(String activityName){
      ActivityManager manager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
      List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
      String cmpNameTemp = null;
      if(runningTaskInfos != null){
      cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
      }
      if(cmpNameTemp == null){
      return false;
      }
      return cmpNameTemp.equals(activityName);
      }






      android android-studio






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 27 '18 at 2:32







      HelloCW

















      asked Nov 27 '18 at 1:55









      HelloCWHelloCW

      27542898




      27542898
























          2 Answers
          2






          active

          oldest

          votes


















          0














          this is supported natively by the Activity lifecycle which is onResume, which will be called after the activity comes in the foreground.



          public void onResume() {
          // do here what you need
          }





          share|improve this answer
























          • Thanks! but I need to do it outside the Activity.

            – HelloCW
            Nov 27 '18 at 2:32






          • 1





            that is easy using the EventBus or the Observable

            – Khalid Taha
            Nov 27 '18 at 2:32











          • @KhalidTaha, could you please provide some examples using EventBus or Observable?

            – shizhen
            Nov 27 '18 at 2:37













          • Sure, this is a tutorial of EventBus: code.tutsplus.com/articles/…

            – Khalid Taha
            Nov 27 '18 at 2:39











          • Thanks! How to get the foreground activity ? could you show me some sample code?

            – HelloCW
            Nov 27 '18 at 3:01



















          0














          Put below code in a file in your application



              public class Foreground implements Application.ActivityLifecycleCallbacks {

          public static final long CHECK_DELAY = 500;
          public static final String TAG = Foreground.class.getName();

          public interface Listener {

          public void onBecameForeground();

          public void onBecameBackground();

          }

          private static Foreground instance;

          private boolean foreground = false, paused = true;
          private Handler handler = new Handler();
          private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
          private Runnable check;

          /**
          * Its not strictly necessary to use this method - _usually_ invoking
          * get with a Context gives us a path to retrieve the Application and
          * initialise, but sometimes (e.g. in test harness) the ApplicationContext
          * is != the Application, and the docs make no guarantees.
          *
          * @param application
          * @return an initialised Foreground instance
          */
          public static Foreground init(Application application) {
          if (instance == null) {
          instance = new Foreground();
          application.registerActivityLifecycleCallbacks(instance);
          }
          return instance;
          }

          public static Foreground get(Application application) {
          if (instance == null) {
          init(application);
          }
          return instance;
          }

          public static Foreground get(Context ctx) {
          if (instance == null) {
          Context appCtx = ctx.getApplicationContext();
          if (appCtx instanceof Application) {
          init((Application) appCtx);
          }
          throw new IllegalStateException(
          "Foreground is not initialised and " +
          "cannot obtain the Application object");
          }
          return instance;
          }

          public static Foreground get() {
          if (instance == null) {
          throw new IllegalStateException(
          "Foreground is not initialised - invoke " +
          "at least once with parameterised init/get");
          }
          return instance;
          }

          public boolean isForeground() {
          return foreground;
          }

          public boolean isBackground() {
          return !foreground;
          }

          public void addListener(Listener listener) {
          listeners.add(listener);
          }

          public void removeListener(Listener listener) {
          listeners.remove(listener);
          }

          @Override
          public void onActivityResumed(Activity activity) {
          paused = false;
          boolean wasBackground = !foreground;
          foreground = true;

          if (check != null)
          handler.removeCallbacks(check);

          if (wasBackground) {
          Log.i(TAG, "went foreground");
          for (Listener l : listeners) {
          try {
          l.onBecameForeground();
          } catch (Exception exc) {
          Log.e(TAG, "Listener threw exception!", exc);
          }
          }
          } else {
          Log.i(TAG, "still foreground");
          }
          }

          @Override
          public void onActivityPaused(Activity activity) {
          paused = true;

          if (check != null)
          handler.removeCallbacks(check);

          handler.postDelayed(check = new Runnable() {
          @Override
          public void run() {
          if (foreground && paused) {
          foreground = false;
          Log.i(TAG, "went background");
          for (Listener l : listeners) {
          try {
          l.onBecameBackground();
          Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
          if (intent != null) {
          // We found the activity now start the activity
          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
          } else {
          // Bring user to the market or let them choose an app?
          intent = new Intent(Intent.ACTION_VIEW);
          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
          startActivity(intent);
          }
          } catch (Exception exc) {
          Log.e(TAG, "Listener threw exception!", exc);
          }
          }
          } else {
          Log.i(TAG, "still foreground");
          }
          }
          }, CHECK_DELAY);
          }

          @Override
          public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
          }

          @Override
          public void onActivityStarted(Activity activity) {
          }

          @Override
          public void onActivityStopped(Activity activity) {
          }

          @Override
          public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
          }

          @Override
          public void onActivityDestroyed(Activity activity) {
          }


          Now in onCreate method of Application.class put the code:



           @Override
          public void onCreate() {
          super.onCreate();
          Foreground.init(this);
          }


          You can now use Foreground.isBackground() to get application is in background or not.



          You can even perform specific task in one of the overridden lifecycle methods (onActivityPaused, onActivityStopped etc)






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53491673%2fhow-to-check-whether-a-activity-is-foreground-and-bring-it-to-background-when-it%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            this is supported natively by the Activity lifecycle which is onResume, which will be called after the activity comes in the foreground.



            public void onResume() {
            // do here what you need
            }





            share|improve this answer
























            • Thanks! but I need to do it outside the Activity.

              – HelloCW
              Nov 27 '18 at 2:32






            • 1





              that is easy using the EventBus or the Observable

              – Khalid Taha
              Nov 27 '18 at 2:32











            • @KhalidTaha, could you please provide some examples using EventBus or Observable?

              – shizhen
              Nov 27 '18 at 2:37













            • Sure, this is a tutorial of EventBus: code.tutsplus.com/articles/…

              – Khalid Taha
              Nov 27 '18 at 2:39











            • Thanks! How to get the foreground activity ? could you show me some sample code?

              – HelloCW
              Nov 27 '18 at 3:01
















            0














            this is supported natively by the Activity lifecycle which is onResume, which will be called after the activity comes in the foreground.



            public void onResume() {
            // do here what you need
            }





            share|improve this answer
























            • Thanks! but I need to do it outside the Activity.

              – HelloCW
              Nov 27 '18 at 2:32






            • 1





              that is easy using the EventBus or the Observable

              – Khalid Taha
              Nov 27 '18 at 2:32











            • @KhalidTaha, could you please provide some examples using EventBus or Observable?

              – shizhen
              Nov 27 '18 at 2:37













            • Sure, this is a tutorial of EventBus: code.tutsplus.com/articles/…

              – Khalid Taha
              Nov 27 '18 at 2:39











            • Thanks! How to get the foreground activity ? could you show me some sample code?

              – HelloCW
              Nov 27 '18 at 3:01














            0












            0








            0







            this is supported natively by the Activity lifecycle which is onResume, which will be called after the activity comes in the foreground.



            public void onResume() {
            // do here what you need
            }





            share|improve this answer













            this is supported natively by the Activity lifecycle which is onResume, which will be called after the activity comes in the foreground.



            public void onResume() {
            // do here what you need
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 27 '18 at 2:03









            Khalid TahaKhalid Taha

            1,89411531




            1,89411531













            • Thanks! but I need to do it outside the Activity.

              – HelloCW
              Nov 27 '18 at 2:32






            • 1





              that is easy using the EventBus or the Observable

              – Khalid Taha
              Nov 27 '18 at 2:32











            • @KhalidTaha, could you please provide some examples using EventBus or Observable?

              – shizhen
              Nov 27 '18 at 2:37













            • Sure, this is a tutorial of EventBus: code.tutsplus.com/articles/…

              – Khalid Taha
              Nov 27 '18 at 2:39











            • Thanks! How to get the foreground activity ? could you show me some sample code?

              – HelloCW
              Nov 27 '18 at 3:01



















            • Thanks! but I need to do it outside the Activity.

              – HelloCW
              Nov 27 '18 at 2:32






            • 1





              that is easy using the EventBus or the Observable

              – Khalid Taha
              Nov 27 '18 at 2:32











            • @KhalidTaha, could you please provide some examples using EventBus or Observable?

              – shizhen
              Nov 27 '18 at 2:37













            • Sure, this is a tutorial of EventBus: code.tutsplus.com/articles/…

              – Khalid Taha
              Nov 27 '18 at 2:39











            • Thanks! How to get the foreground activity ? could you show me some sample code?

              – HelloCW
              Nov 27 '18 at 3:01

















            Thanks! but I need to do it outside the Activity.

            – HelloCW
            Nov 27 '18 at 2:32





            Thanks! but I need to do it outside the Activity.

            – HelloCW
            Nov 27 '18 at 2:32




            1




            1





            that is easy using the EventBus or the Observable

            – Khalid Taha
            Nov 27 '18 at 2:32





            that is easy using the EventBus or the Observable

            – Khalid Taha
            Nov 27 '18 at 2:32













            @KhalidTaha, could you please provide some examples using EventBus or Observable?

            – shizhen
            Nov 27 '18 at 2:37







            @KhalidTaha, could you please provide some examples using EventBus or Observable?

            – shizhen
            Nov 27 '18 at 2:37















            Sure, this is a tutorial of EventBus: code.tutsplus.com/articles/…

            – Khalid Taha
            Nov 27 '18 at 2:39





            Sure, this is a tutorial of EventBus: code.tutsplus.com/articles/…

            – Khalid Taha
            Nov 27 '18 at 2:39













            Thanks! How to get the foreground activity ? could you show me some sample code?

            – HelloCW
            Nov 27 '18 at 3:01





            Thanks! How to get the foreground activity ? could you show me some sample code?

            – HelloCW
            Nov 27 '18 at 3:01













            0














            Put below code in a file in your application



                public class Foreground implements Application.ActivityLifecycleCallbacks {

            public static final long CHECK_DELAY = 500;
            public static final String TAG = Foreground.class.getName();

            public interface Listener {

            public void onBecameForeground();

            public void onBecameBackground();

            }

            private static Foreground instance;

            private boolean foreground = false, paused = true;
            private Handler handler = new Handler();
            private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
            private Runnable check;

            /**
            * Its not strictly necessary to use this method - _usually_ invoking
            * get with a Context gives us a path to retrieve the Application and
            * initialise, but sometimes (e.g. in test harness) the ApplicationContext
            * is != the Application, and the docs make no guarantees.
            *
            * @param application
            * @return an initialised Foreground instance
            */
            public static Foreground init(Application application) {
            if (instance == null) {
            instance = new Foreground();
            application.registerActivityLifecycleCallbacks(instance);
            }
            return instance;
            }

            public static Foreground get(Application application) {
            if (instance == null) {
            init(application);
            }
            return instance;
            }

            public static Foreground get(Context ctx) {
            if (instance == null) {
            Context appCtx = ctx.getApplicationContext();
            if (appCtx instanceof Application) {
            init((Application) appCtx);
            }
            throw new IllegalStateException(
            "Foreground is not initialised and " +
            "cannot obtain the Application object");
            }
            return instance;
            }

            public static Foreground get() {
            if (instance == null) {
            throw new IllegalStateException(
            "Foreground is not initialised - invoke " +
            "at least once with parameterised init/get");
            }
            return instance;
            }

            public boolean isForeground() {
            return foreground;
            }

            public boolean isBackground() {
            return !foreground;
            }

            public void addListener(Listener listener) {
            listeners.add(listener);
            }

            public void removeListener(Listener listener) {
            listeners.remove(listener);
            }

            @Override
            public void onActivityResumed(Activity activity) {
            paused = false;
            boolean wasBackground = !foreground;
            foreground = true;

            if (check != null)
            handler.removeCallbacks(check);

            if (wasBackground) {
            Log.i(TAG, "went foreground");
            for (Listener l : listeners) {
            try {
            l.onBecameForeground();
            } catch (Exception exc) {
            Log.e(TAG, "Listener threw exception!", exc);
            }
            }
            } else {
            Log.i(TAG, "still foreground");
            }
            }

            @Override
            public void onActivityPaused(Activity activity) {
            paused = true;

            if (check != null)
            handler.removeCallbacks(check);

            handler.postDelayed(check = new Runnable() {
            @Override
            public void run() {
            if (foreground && paused) {
            foreground = false;
            Log.i(TAG, "went background");
            for (Listener l : listeners) {
            try {
            l.onBecameBackground();
            Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
            if (intent != null) {
            // We found the activity now start the activity
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            } else {
            // Bring user to the market or let them choose an app?
            intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
            startActivity(intent);
            }
            } catch (Exception exc) {
            Log.e(TAG, "Listener threw exception!", exc);
            }
            }
            } else {
            Log.i(TAG, "still foreground");
            }
            }
            }, CHECK_DELAY);
            }

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }


            Now in onCreate method of Application.class put the code:



             @Override
            public void onCreate() {
            super.onCreate();
            Foreground.init(this);
            }


            You can now use Foreground.isBackground() to get application is in background or not.



            You can even perform specific task in one of the overridden lifecycle methods (onActivityPaused, onActivityStopped etc)






            share|improve this answer




























              0














              Put below code in a file in your application



                  public class Foreground implements Application.ActivityLifecycleCallbacks {

              public static final long CHECK_DELAY = 500;
              public static final String TAG = Foreground.class.getName();

              public interface Listener {

              public void onBecameForeground();

              public void onBecameBackground();

              }

              private static Foreground instance;

              private boolean foreground = false, paused = true;
              private Handler handler = new Handler();
              private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
              private Runnable check;

              /**
              * Its not strictly necessary to use this method - _usually_ invoking
              * get with a Context gives us a path to retrieve the Application and
              * initialise, but sometimes (e.g. in test harness) the ApplicationContext
              * is != the Application, and the docs make no guarantees.
              *
              * @param application
              * @return an initialised Foreground instance
              */
              public static Foreground init(Application application) {
              if (instance == null) {
              instance = new Foreground();
              application.registerActivityLifecycleCallbacks(instance);
              }
              return instance;
              }

              public static Foreground get(Application application) {
              if (instance == null) {
              init(application);
              }
              return instance;
              }

              public static Foreground get(Context ctx) {
              if (instance == null) {
              Context appCtx = ctx.getApplicationContext();
              if (appCtx instanceof Application) {
              init((Application) appCtx);
              }
              throw new IllegalStateException(
              "Foreground is not initialised and " +
              "cannot obtain the Application object");
              }
              return instance;
              }

              public static Foreground get() {
              if (instance == null) {
              throw new IllegalStateException(
              "Foreground is not initialised - invoke " +
              "at least once with parameterised init/get");
              }
              return instance;
              }

              public boolean isForeground() {
              return foreground;
              }

              public boolean isBackground() {
              return !foreground;
              }

              public void addListener(Listener listener) {
              listeners.add(listener);
              }

              public void removeListener(Listener listener) {
              listeners.remove(listener);
              }

              @Override
              public void onActivityResumed(Activity activity) {
              paused = false;
              boolean wasBackground = !foreground;
              foreground = true;

              if (check != null)
              handler.removeCallbacks(check);

              if (wasBackground) {
              Log.i(TAG, "went foreground");
              for (Listener l : listeners) {
              try {
              l.onBecameForeground();
              } catch (Exception exc) {
              Log.e(TAG, "Listener threw exception!", exc);
              }
              }
              } else {
              Log.i(TAG, "still foreground");
              }
              }

              @Override
              public void onActivityPaused(Activity activity) {
              paused = true;

              if (check != null)
              handler.removeCallbacks(check);

              handler.postDelayed(check = new Runnable() {
              @Override
              public void run() {
              if (foreground && paused) {
              foreground = false;
              Log.i(TAG, "went background");
              for (Listener l : listeners) {
              try {
              l.onBecameBackground();
              Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
              if (intent != null) {
              // We found the activity now start the activity
              intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              startActivity(intent);
              } else {
              // Bring user to the market or let them choose an app?
              intent = new Intent(Intent.ACTION_VIEW);
              intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
              startActivity(intent);
              }
              } catch (Exception exc) {
              Log.e(TAG, "Listener threw exception!", exc);
              }
              }
              } else {
              Log.i(TAG, "still foreground");
              }
              }
              }, CHECK_DELAY);
              }

              @Override
              public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
              }

              @Override
              public void onActivityStarted(Activity activity) {
              }

              @Override
              public void onActivityStopped(Activity activity) {
              }

              @Override
              public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
              }

              @Override
              public void onActivityDestroyed(Activity activity) {
              }


              Now in onCreate method of Application.class put the code:



               @Override
              public void onCreate() {
              super.onCreate();
              Foreground.init(this);
              }


              You can now use Foreground.isBackground() to get application is in background or not.



              You can even perform specific task in one of the overridden lifecycle methods (onActivityPaused, onActivityStopped etc)






              share|improve this answer


























                0












                0








                0







                Put below code in a file in your application



                    public class Foreground implements Application.ActivityLifecycleCallbacks {

                public static final long CHECK_DELAY = 500;
                public static final String TAG = Foreground.class.getName();

                public interface Listener {

                public void onBecameForeground();

                public void onBecameBackground();

                }

                private static Foreground instance;

                private boolean foreground = false, paused = true;
                private Handler handler = new Handler();
                private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
                private Runnable check;

                /**
                * Its not strictly necessary to use this method - _usually_ invoking
                * get with a Context gives us a path to retrieve the Application and
                * initialise, but sometimes (e.g. in test harness) the ApplicationContext
                * is != the Application, and the docs make no guarantees.
                *
                * @param application
                * @return an initialised Foreground instance
                */
                public static Foreground init(Application application) {
                if (instance == null) {
                instance = new Foreground();
                application.registerActivityLifecycleCallbacks(instance);
                }
                return instance;
                }

                public static Foreground get(Application application) {
                if (instance == null) {
                init(application);
                }
                return instance;
                }

                public static Foreground get(Context ctx) {
                if (instance == null) {
                Context appCtx = ctx.getApplicationContext();
                if (appCtx instanceof Application) {
                init((Application) appCtx);
                }
                throw new IllegalStateException(
                "Foreground is not initialised and " +
                "cannot obtain the Application object");
                }
                return instance;
                }

                public static Foreground get() {
                if (instance == null) {
                throw new IllegalStateException(
                "Foreground is not initialised - invoke " +
                "at least once with parameterised init/get");
                }
                return instance;
                }

                public boolean isForeground() {
                return foreground;
                }

                public boolean isBackground() {
                return !foreground;
                }

                public void addListener(Listener listener) {
                listeners.add(listener);
                }

                public void removeListener(Listener listener) {
                listeners.remove(listener);
                }

                @Override
                public void onActivityResumed(Activity activity) {
                paused = false;
                boolean wasBackground = !foreground;
                foreground = true;

                if (check != null)
                handler.removeCallbacks(check);

                if (wasBackground) {
                Log.i(TAG, "went foreground");
                for (Listener l : listeners) {
                try {
                l.onBecameForeground();
                } catch (Exception exc) {
                Log.e(TAG, "Listener threw exception!", exc);
                }
                }
                } else {
                Log.i(TAG, "still foreground");
                }
                }

                @Override
                public void onActivityPaused(Activity activity) {
                paused = true;

                if (check != null)
                handler.removeCallbacks(check);

                handler.postDelayed(check = new Runnable() {
                @Override
                public void run() {
                if (foreground && paused) {
                foreground = false;
                Log.i(TAG, "went background");
                for (Listener l : listeners) {
                try {
                l.onBecameBackground();
                Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
                if (intent != null) {
                // We found the activity now start the activity
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                } else {
                // Bring user to the market or let them choose an app?
                intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
                startActivity(intent);
                }
                } catch (Exception exc) {
                Log.e(TAG, "Listener threw exception!", exc);
                }
                }
                } else {
                Log.i(TAG, "still foreground");
                }
                }
                }, CHECK_DELAY);
                }

                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                }

                @Override
                public void onActivityStarted(Activity activity) {
                }

                @Override
                public void onActivityStopped(Activity activity) {
                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                }


                Now in onCreate method of Application.class put the code:



                 @Override
                public void onCreate() {
                super.onCreate();
                Foreground.init(this);
                }


                You can now use Foreground.isBackground() to get application is in background or not.



                You can even perform specific task in one of the overridden lifecycle methods (onActivityPaused, onActivityStopped etc)






                share|improve this answer













                Put below code in a file in your application



                    public class Foreground implements Application.ActivityLifecycleCallbacks {

                public static final long CHECK_DELAY = 500;
                public static final String TAG = Foreground.class.getName();

                public interface Listener {

                public void onBecameForeground();

                public void onBecameBackground();

                }

                private static Foreground instance;

                private boolean foreground = false, paused = true;
                private Handler handler = new Handler();
                private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
                private Runnable check;

                /**
                * Its not strictly necessary to use this method - _usually_ invoking
                * get with a Context gives us a path to retrieve the Application and
                * initialise, but sometimes (e.g. in test harness) the ApplicationContext
                * is != the Application, and the docs make no guarantees.
                *
                * @param application
                * @return an initialised Foreground instance
                */
                public static Foreground init(Application application) {
                if (instance == null) {
                instance = new Foreground();
                application.registerActivityLifecycleCallbacks(instance);
                }
                return instance;
                }

                public static Foreground get(Application application) {
                if (instance == null) {
                init(application);
                }
                return instance;
                }

                public static Foreground get(Context ctx) {
                if (instance == null) {
                Context appCtx = ctx.getApplicationContext();
                if (appCtx instanceof Application) {
                init((Application) appCtx);
                }
                throw new IllegalStateException(
                "Foreground is not initialised and " +
                "cannot obtain the Application object");
                }
                return instance;
                }

                public static Foreground get() {
                if (instance == null) {
                throw new IllegalStateException(
                "Foreground is not initialised - invoke " +
                "at least once with parameterised init/get");
                }
                return instance;
                }

                public boolean isForeground() {
                return foreground;
                }

                public boolean isBackground() {
                return !foreground;
                }

                public void addListener(Listener listener) {
                listeners.add(listener);
                }

                public void removeListener(Listener listener) {
                listeners.remove(listener);
                }

                @Override
                public void onActivityResumed(Activity activity) {
                paused = false;
                boolean wasBackground = !foreground;
                foreground = true;

                if (check != null)
                handler.removeCallbacks(check);

                if (wasBackground) {
                Log.i(TAG, "went foreground");
                for (Listener l : listeners) {
                try {
                l.onBecameForeground();
                } catch (Exception exc) {
                Log.e(TAG, "Listener threw exception!", exc);
                }
                }
                } else {
                Log.i(TAG, "still foreground");
                }
                }

                @Override
                public void onActivityPaused(Activity activity) {
                paused = true;

                if (check != null)
                handler.removeCallbacks(check);

                handler.postDelayed(check = new Runnable() {
                @Override
                public void run() {
                if (foreground && paused) {
                foreground = false;
                Log.i(TAG, "went background");
                for (Listener l : listeners) {
                try {
                l.onBecameBackground();
                Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
                if (intent != null) {
                // We found the activity now start the activity
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                } else {
                // Bring user to the market or let them choose an app?
                intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
                startActivity(intent);
                }
                } catch (Exception exc) {
                Log.e(TAG, "Listener threw exception!", exc);
                }
                }
                } else {
                Log.i(TAG, "still foreground");
                }
                }
                }, CHECK_DELAY);
                }

                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                }

                @Override
                public void onActivityStarted(Activity activity) {
                }

                @Override
                public void onActivityStopped(Activity activity) {
                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                }


                Now in onCreate method of Application.class put the code:



                 @Override
                public void onCreate() {
                super.onCreate();
                Foreground.init(this);
                }


                You can now use Foreground.isBackground() to get application is in background or not.



                You can even perform specific task in one of the overridden lifecycle methods (onActivityPaused, onActivityStopped etc)







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 27 '18 at 4:31









                Vikash BijarniyaVikash Bijarniya

                1368




                1368






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53491673%2fhow-to-check-whether-a-activity-is-foreground-and-bring-it-to-background-when-it%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks