FirebaseMessagingService无法正常工作

时间:2018-08-06 04:46:12

标签: android push-notification

我已经实现了FirebaseMessagingService的服务。今天,我注意到手机被阻止时有异常行为。我很幸运地收到消息,Android通过通知向我显示,但是onMessageReceived中的代码不起作用。

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    final Context context = this;

    if(remoteMessage == null){
        return;
    }

    if(remoteMessage.getNotification() != null){
        try {
            final  Message msg = createMessage(remoteMessage.getNotification());
            Handler handler= new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if(!isAppIsInBackgrund(context)){
                        Intent intent = new Intent("APP_MESSAGE_BROADCAST");
                        intent.putExtra("SENDER", msg.getCorrespondent().getId().toString());
                        intent.putExtra("MESSAGE_ID", msg.getId());
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                    }
                    else {
                        showNotification(msg.getCorrespondent().getName(), msg.getBody());
                    }
                }
            });

        } catch (Exception e) {
            showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }
}

// isAppIsInBackgrund-我在哪里检查打开应用程序的方法。

public boolean isAppIsInBackgrund(Context context){
    boolean isInBackground = true;
    ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH){
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = activityManager.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 = activityManager.getRunningTasks(1);
        ComponentName componentName = taskInfo.get(0).topActivity;
        if(componentName.getPackageName().equals(context.getPackageName())){
            isInBackground = false;
        }
    }
    return isInBackground; }

0 个答案:

没有答案