Checking if an Android application is running in the background

前端 未结 30 2901
无人共我
无人共我 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 07:15

    Idolon's answer is error prone and much more complicated althought repeatead here check android application is in foreground or not? and here Determining the current foreground application from a background task or service

    There is a much more simpler approach:

    On a BaseActivity that all Activities extend:

    protected static boolean isVisible = false;
    
     @Override
     public void onResume()
     {
         super.onResume();
         setVisible(true);
     }
    
    
     @Override
     public void onPause()
     {
         super.onPause();
         setVisible(false);
     }
    

    Whenever you need to check if any of your application activities is in foreground just check isVisible();

    To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle

提交回复
热议问题