locked
Detect running activity RRS feed

  • Question

  • User365175 posted

    Is there a way to determine if a certain activity is running?

    Thanks in advance :)

    Thursday, August 23, 2018 8:39 AM

Answers

  • User371688 posted

    @Enohara These are several methods for you to select according to your choice. Solution 1 : ActivityManager is useful for Checking whether a activity is running or not.

    protected Boolean isActivityRunning(Class activityClass){
        ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
        for (ActivityManager.RunningTaskInfo task : tasks) {
            if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
                return true;
          }
        return false;
    }
    

    Also, to do this you need to add the permission to your manifest.

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

    Note: this method is only intended for debugging and presenting task management user interfaces.

    Solution 2: You can try to use an static variable in your activity and store it somewhere for access from your service or broadcast receiver .

      static int isRunning= 0;
     static boolean isActive() {
        return (activeInstance > 0)
     }
    
     public void onStart() {
         isRunning ++; 
      } 
      public void onStop() {
         isRunning --; 
      }
    

    Note: This breaks when the activity is killed without calling onStop()

    Solution 3: public class example extends Activity {

    @Override
    protected void onStart() {
        super.onStart();
    
        // Store our shared preference
        SharedPreferences sp = getSharedPreferences("INFO", MODE_PRIVATE);
        Editor ed = sp.edit();
        ed.putBoolean("active", true);
        ed.commit();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
    
        // Store our shared preference
        SharedPreferences sp = getSharedPreferences("INFO", MODE_PRIVATE);
        Editor ed = sp.edit();
        ed.putBoolean("active", false);
        ed.commit();
    
    }
    

    } Note: The correct functions are not always called so the state does not always represent the actual state. If an app crashes for example, it will not call the onStop() function. You can remedy this however with creating a default exception handler which can set the shared preferences to the correct values.. Conclusion We prefer to use the shared preferences version. Exception handling To remedy some of the issues mentioned in the previous sections you can create a default exception handler in which you can do some last coding. final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                // fix our issues for static variables
                isActive = false;   
    
                // fix our issues for sharedpreferences
                SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
                Editor ed = sp.edit();
                ed.putBoolean("active", false);
                ed.commit();
    
                // Handle everthing else
                defaultHandler.uncaughtException(thread, throwable);
            }
        });
    

    More details: http://androidblog.reindustries.com/check-if-an-android-activity-is-currently-running/

    PS : In fact, none of the other answers work 100% either.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, August 24, 2018 5:56 AM

All replies

  • User371688 posted

    @Enohara These are several methods for you to select according to your choice. Solution 1 : ActivityManager is useful for Checking whether a activity is running or not.

    protected Boolean isActivityRunning(Class activityClass){
        ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
        for (ActivityManager.RunningTaskInfo task : tasks) {
            if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
                return true;
          }
        return false;
    }
    

    Also, to do this you need to add the permission to your manifest.

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

    Note: this method is only intended for debugging and presenting task management user interfaces.

    Solution 2: You can try to use an static variable in your activity and store it somewhere for access from your service or broadcast receiver .

      static int isRunning= 0;
     static boolean isActive() {
        return (activeInstance > 0)
     }
    
     public void onStart() {
         isRunning ++; 
      } 
      public void onStop() {
         isRunning --; 
      }
    

    Note: This breaks when the activity is killed without calling onStop()

    Solution 3: public class example extends Activity {

    @Override
    protected void onStart() {
        super.onStart();
    
        // Store our shared preference
        SharedPreferences sp = getSharedPreferences("INFO", MODE_PRIVATE);
        Editor ed = sp.edit();
        ed.putBoolean("active", true);
        ed.commit();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
    
        // Store our shared preference
        SharedPreferences sp = getSharedPreferences("INFO", MODE_PRIVATE);
        Editor ed = sp.edit();
        ed.putBoolean("active", false);
        ed.commit();
    
    }
    

    } Note: The correct functions are not always called so the state does not always represent the actual state. If an app crashes for example, it will not call the onStop() function. You can remedy this however with creating a default exception handler which can set the shared preferences to the correct values.. Conclusion We prefer to use the shared preferences version. Exception handling To remedy some of the issues mentioned in the previous sections you can create a default exception handler in which you can do some last coding. final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                // fix our issues for static variables
                isActive = false;   
    
                // fix our issues for sharedpreferences
                SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
                Editor ed = sp.edit();
                ed.putBoolean("active", false);
                ed.commit();
    
                // Handle everthing else
                defaultHandler.uncaughtException(thread, throwable);
            }
        });
    

    More details: http://androidblog.reindustries.com/check-if-an-android-activity-is-currently-running/

    PS : In fact, none of the other answers work 100% either.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, August 24, 2018 5:56 AM
  • User365175 posted

    @jezh The solution 3 is brilliant, haven't tried the other solution, Thanks you so much, this is very helpful :)

    Friday, August 24, 2018 9:25 AM