[英]How to check whether a app is in background or foreground android. Using following code but unable check
I am trying find foreground or background for "push notification" using the following code but it executing both background and foreground.我正在尝试使用以下代码为“推送通知”查找前景或背景,但它同时执行背景和前景。 Any solution for this??有什么解决办法吗??
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;
}
So if I understand your question you want to check if your current thread is the main thread /some background thread, you can check it like this :所以如果我理解你的问题,你想检查你当前的线程是否是主线程/某个后台线程,你可以这样检查:
if(Looper.myLooper() == Looper.getMainLooper()){
//you are on your main Thread (also called UI Thread)
}
Make your Application class implement LifecycleObserver interface and you can define methods like shown below to get callbacks for app foreground and app background events使您的应用程序类实现 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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.