【问题标题】:How to check whether a app is in background or foreground android. Using following code but unable check如何检查应用程序是在后台还是前台android。使用以下代码但无法检查
【发布时间】:2019-04-05 07:53:17
【问题描述】:

我正在尝试使用以下代码为“推送通知”查找前台或后台,但它同时执行后台和前台。有什么解决办法吗??

public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }
    return isInBackground;
}

【问题讨论】:

标签: android push-notification background-foreground


【解决方案1】:

所以如果我理解你的问题,你想检查你当前的线程是否是主线程/一些后台线程,你可以这样检查:

if(Looper.myLooper() == Looper.getMainLooper()){
  //you are on your main Thread (also called UI Thread)
}

【讨论】:

    【解决方案2】:

    让你的 Application 类实现 LifecycleObserver 接口,你可以定义如下所示的方法来获取应用程序前台和应用程序后台事件的回调

    class MyApplication implements LifecycleObsercer {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onAppBackgrounded() {
            Timber.d("App in background");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onAppForegrounded() {
            Timber.d("App is in foreground");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多