我正在尝试使用以下代码为“推送通知”找到前台或后台,但是它同时执行后台和前台。有什么解决办法吗?
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;
}
答案 0 :(得分:0)
因此,如果我理解您的问题,您想检查当前线程是否为主线程/某些后台线程,您可以像这样检查它:
if(Looper.myLooper() == Looper.getMainLooper()){
//you are on your main Thread (also called UI Thread)
}
答案 1 :(得分:0)
让您的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");
}
}