仅当应用程序不在前台时,我才需要向用户显示通知。这是我的公共(public)类MyFirebaseMessagingService扩展

FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if(applicationInForeground()) {
            Map<String, String> data = remoteMessage.getData();
            sendNotification(data.get("title"), data.get("detail"));
        }

    }

需要实现applicationInForeground()方法

最佳答案

您可以从android系统服务控制正在运行的应用程序进程。尝试这个:

private boolean applicationInForeground() {
    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> services = activityManager.getRunningAppProcesses();
    boolean isActivityFound = false;

    if (services.get(0).processName
            .equalsIgnoreCase(getPackageName()) && services.get(0).importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
        isActivityFound = true;
    }

    return isActivityFound;
}

祝你好运。

关于android - 如何从服务检查应用程序在前台?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41295924/

10-10 18:04