Checking if an Android application is running in the background

前端 未结 30 2800
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  再見小時候
    2020-11-21 06:52

    You can use ComponentCallbacks2 to detect if the app is in background. BTW this callback is only available in API Level 14 (Ice Cream Sandwich) and above.

    You will get a call to the method:

    public abstract void onTrimMemory (int level)

    if the level is ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN then the app is in background.

    You can implement this interface to an activity, service, etc.

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

提交回复
热议问题