Determine if an application is running in the background

How can I say that my application was placed in the background (i.e. none of my applications are visible anymore)? I need to define this so that I can allocate resources shared by several of my actions (graphics, sound clips and socket connection).

I was thinking about saving a global counter, which increased in the onStart () method and decreased in onStop (). If the counter reaches zero, all actions have been stopped, and my application is running in the background. However, I'm not sure if it will be 100% reliable. In addition, I cannot help but think that there should be a better way to do this.

+3
source share
5 answers

, :

:

public boolean inBackground;

@Override
public void onPause()
{
     inBackground=true;
     super.onPause();
}

@Override
public void onResume()
{
     inBackground=false;
     super.onResume();
}
+2

, . , , , , .

, Android - service .

0

, , . - "", , , . , sql - , , . .

0

, , .

  • , extends Activity ( SO).
  • , Activity.
  • @ onStop() ( ).
  • onStop() (, Droid-Fu), , .

: , ( ), , , .

public static boolean isApplicationInBackground(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;
}

, , !

: .

, , , ComponentInfo{com.motorola.blur.home/com.motorola.blur.home.HomeActivity} . "" ( , ).

, onDestroy() isFinished(), , ( , , ).

0

Source: https://habr.com/ru/post/1754393/


All Articles