Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 应用程序打开或后台(是否显示通知)_Android - Fatal编程技术网

Android 应用程序打开或后台(是否显示通知)

Android 应用程序打开或后台(是否显示通知),android,Android,我的应用程序从服务器接收GCM消息。我已经准备好了通知 我的问题是,如果应用程序是打开的,那么我不想显示通知,只想显示应用程序中的消息。但是如果应用程序关闭,那么我需要显示通知(如聊天应用程序) 我该如何做这个决定 谢谢您可以检查应用程序是否在后台,然后尝试此操作 public static boolean isAppIsInBackground(Context context) { boolean isInBackground = true; ActivityManager

我的应用程序从服务器接收GCM消息。我已经准备好了通知

我的问题是,如果应用程序是打开的,那么我不想显示通知,只想显示应用程序中的消息。但是如果应用程序关闭,那么我需要显示通知(如聊天应用程序)

我该如何做这个决定


谢谢

您可以检查应用程序是否在后台,然后尝试此操作

 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;
}
public静态布尔值isAppIsInBackground(上下文){
布尔值isInBackground=true;
ActivityManager am=(ActivityManager)context.getSystemService(context.ACTIVITY_服务);
if(Build.VERSION.SDK\u INT>Build.VERSION\u code.KITKAT\u WATCH){
List runningprocesss=am.getrunningappprocesss();
对于(ActivityManager.RunningAppProcessInfo processInfo:RunningProcesss){
if(processInfo.importance==ActivityManager.RunningAppProcessInfo.importance\u前台){
for(字符串activeProcess:processInfo.pkgList){
if(activeProcess.equals(context.getPackageName())){
isInBackground=假;
}
}
}
}
}否则{
List taskInfo=am.getRunningTasks(1);
ComponentName componentInfo=taskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals(context.getPackageName())){
isInBackground=假;
}
}
返回背景;
}

您可以将活动生命周期事件的侦听器添加到应用程序对象中

看这里


除了手动之外,没有办法确定它-在某处创建一些标志,并跟踪应用程序的活动生命周期,以检查前台是否有任何活动。