android:how to check if application is running in background

后端 未结 4 1308
Happy的楠姐
Happy的楠姐 2020-12-01 18:53

I am newbie to android. I have client server based application. Server keeps on sending the update notifications to client after every single minute and at client side my ap

相关标签:
4条回答
  • 2020-12-01 19:34

    Update, see this first:

    Checking if an Android application is running in the background


    To check if your application is sent to background, you can call this code on onPause() on every activity in your application:

     /**
       * Checks if the application is being sent in the background (i.e behind
       * another application's Activity).
       * 
       * @param context the context
       * @return <code>true</code> if another application will be above this one.
       */
      public static boolean isApplicationSentToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
          ComponentName topActivity = tasks.get(0).topActivity;
          if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
          }
        }
    
        return false;
      }
    

    For this to work you should include this in your AndroidManifest.xml

    <uses-permission android:name="android.permission.GET_TASKS" />
    
    0 讨论(0)
  • 2020-12-01 19:40

    http://developer.android.com/guide/topics/fundamentals.html#lcycles is a description of the Life Cycle of an android application.

    The method onPause() gets called when the activity goes into the background. So you can deactivate the update notifications in this method.

    0 讨论(0)
  • 2020-12-01 19:42

    You can use getRunningAppProcesses() in ActivityManager .

    0 讨论(0)
  • 2020-12-01 19:56

    Only for API level 14 and above

    You can use ComponentCallbacks2 to an activity, service, etc.

    Example:

    public class MainActivity extends AppCompatActivity implements ComponentCallbacks2 {
       @Override
       public void onConfigurationChanged(final Configuration newConfig) {
    
       }
    
       @Override
       public void onLowMemory() {
    
       }
    
       @Override
       public void onTrimMemory(final int level) {
         if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            // app is in background
         }
       }
    }
    
    0 讨论(0)
提交回复
热议问题