如何检查Android应用程序是在后台还是在前台运行? [英] How to check if an Android application is running in the background or in foreground?

查看:57
本文介绍了如何检查Android应用程序是在后台还是在前台运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在我的项目中有以下代码:

for exemple i have this code in my project :

   public class Utilities extends Application
{
    private static int stateCounter;

    public void onCreate()
    {
        super.onCreate();
        stateCounter = 0;
    }

    /**
     * @return true if application is on background
     * */
    public static boolean isApplicationOnBackground()
    {
        return stateCounter == 0;
    }

    //to be called on each Activity onStart()
    public static void activityStarted()
    {
        stateCounter++;
    }

    //to be called on each Activity onStop()
    public static void activityStopped()
    {
        stateCounter--;
    } 
}

但是在ios中,检测状态很简单:

but in ios is simple to detect the state :

let state: UIApplicationState = UIApplication.sharedApplication().applicationState // or use  let state =  UIApplication.sharedApplication().applicationState

if state == .Background {

// background
}
else if state == .Active {

// foreground
}

我正在搜索android是否还有其他解决方案来执行此测试?

I m searching if android have another solution to do this test ?

推荐答案

在应用程序类中编写此方法,然后在任何需要的地方使用.

write this method in application class and use wherever you want.

  public boolean isApplicationBroughtToBackground() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(getPackageName())) {
            return true;
        }
    }
    return false;
}

创建一个新的类baseActivity

create a new class baseActivity

public class BaseActivity extends AppCompatActivity {

static Boolean IsResumecalled = false;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
protected void onResume() {
    super.onResume();
    if (!IsResumecalled) {
        //call api here
    IsResumecalled= true;
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (Myapplication.getInstance().isApplicationBroughtToBackground()) {
      //call api here
       IsResumecalled= false;
    }
}

}

并使用BaseActivity扩展每个活动类

and extends with BaseActivity for every activity class

这篇关于如何检查Android应用程序是在后台还是在前台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆