简体   繁体   English

前台通知 android 未显示(奥利奥)

[英]Notification android on foreground not displayed (Oreo)

I'm trying to display an notification with firebase when the app is in the foreground .当应用程序在前台时,我正在尝试使用 firebase 显示通知。 The onMessageReceived method is called when I push the notification from the server, but the notification is not displayed .当我从服务器推送通知时调用 onMessageReceived 方法,但未显示通知。

Here my code :这是我的代码:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
        Timber.d("FCM-From: " + remoteMessage.getFrom());

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    if (remoteMessage.getNotification() != null) {
                        Timber.d("FCM-Message Notification Body: " + remoteMessage.getNotification().getBody());

                        NotificationCompat.Builder builder = new  NotificationCompat.Builder(
                                getApplicationContext(), "CHANNEL_NOTIF")
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("test")
                                .setContentText("test content");
                        NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
                        if (manager != null) {
                            Timber.d("FCM-Notif");
                            manager.notify(1, builder.build());
                        }
                    }
                }
            });
    }
}

In my logcat I can see :在我的 logcat 中,我可以看到:

FCM-Message Notification Body: 202018105166 FCM-消息通知正文:202018105166

FCM-From: 1049809400953 FCM-发件人:1049809400953

FCM-Notif FCM-通知

I followed https://developer.android.com/training/notify-user/build-notification.html#builder我跟着https://developer.android.com/training/notify-user/build-notification.html#builder

I'am running on Oreo我在奥利奥上跑步

SOLUTION解决方案

Found the answer here : Android foreground service notification not showing在这里找到答案: Android 前台服务通知未显示

It was an Oreo issue, thank to @Yashaswi NP这是奥利奥的问题,感谢@Yashaswi NP

This happened because of Android Oreo and higher API levels.这是因为 Android Oreo 和更高的 API 级别。 So You must create the notification channel before posting any notifications on Android 8.0 and higher, you should execute this code as soon as your app starts.因此,您必须在 Android 8.0 及更高版本上发布任何通知之前创建通知渠道,您应该在应用程序启动后立即执行此代码。 It's safe to call this repeatedly because creating an existing notification channel performs no operation.重复调用它是安全的,因为创建现有的通知通道不执行任何操作。

And use following code to solve this problem:并使用以下代码解决此问题:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
    private NotificationUtils notificationUtils;
    private String title,message,click_action;
    private  String CHANNEL_ID = "MyApp";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {

            try {
                JSONObject data = new JSONObject(remoteMessage.getData());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
             title = remoteMessage.getNotification().getTitle(); //get title
             message = remoteMessage.getNotification().getBody(); //get message
             click_action = remoteMessage.getNotification().getClickAction(); //get click_action

            Log.d(TAG, "Notification Title: " + title);
            Log.d(TAG, "Notification Body: " + message);
            Log.d(TAG, "Notification click_action: " + click_action);

            sendNotification(title, message,click_action);
        }
    }

    private void sendNotification(String title,String messageBody, String click_action) {
        Intent intent = new Intent(this, TargetActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.logo_heart)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)// Set the intent that will fire when the user taps the notification
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        // notificationId is a unique int for each notification that you must define
        notificationManager.notify(1, mBuilder.build());

        createNotificationChannel();
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.app_name);
            String description = getString(R.string.description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

}

Found the answer here : Android foreground service notification not showing在这里找到答案: Android 前台服务通知未显示

Need to handle channel with Oreo需要用奥利奥处理渠道

   mNotifyManager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel(mNotifyManager);
    mBuilder = new NotificationCompat.Builder(mActivity, "YOUR_TEXT_HERE").setSmallIcon(android.R.drawable.stat_sys_download).setColor
            (ContextCompat.getColor(mActivity, R.color.colorNotification)).setContentTitle(YOUR_TITLE_HERE).setContentText(YOUR_DESCRIPTION_HERE);
    mNotifyManager.notify(mFile.getId().hashCode(), mBuilder.build());

@TargetApi(26)
private void createChannel(NotificationManager notificationManager) {
    String name = "FileDownload";
    String description = "Notifications for download status";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;

    NotificationChannel mChannel = new NotificationChannel(name, name, importance);
    mChannel.setDescription(description);
    mChannel.enableLights(true);
    mChannel.setLightColor(Color.BLUE);
    notificationManager.createNotificationChannel(mChannel);
}

Thank to @Yashaswi NP感谢@Yashaswi NP

The below mentioned line of code snippet will help you fix it:下面提到的代码片段行将帮助您修复它:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new 
NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
mChannel.setDescription(notification);
mChannel.enableLights(true);
mChannel.setLightColor(ContextCompat.getColor
(getApplicationContext(),R.color.colorPrimary));
notificationManager.createNotificationChannel(mChannel);

}

I have used this code snippet in my project and it really resolved the issue.我在我的项目中使用了这个代码片段,它确实解决了这个问题。

I have added the following permission in the manifest file.我在清单文件中添加了以下权限。

My issue solved.我的问题解决了。

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 应用程序被杀死后,Android Oreo-前台服务| android显示一个通知 - Android oreo - Foreground service once app is killed | android shows a notification 如何在 Oreo 8.0 下为 Android 创建带有通知的前台服务? - How to create a foreground service with notification for Android below Oreo 8.0? 覆盖默认的Oreo前台通知 - Override default Oreo Foreground Notification 奥利奥 - 前景服务不显示前景通知 - Oreo - Foreground service does not show foreground notification 前台服务在android oreo中不起作用 - Foreground service not working in android oreo Android通知未显示在Oreo上 - Android notification not showing on Oreo 在Android Oreo 8.0应用程序中,当通知到来时,背景会从后台变为前台 - In Android Oreo 8.0 App is coming foreground from background when notification come 当应用程序在 Android 上处于前台时不显示 Amazon Pinpoint 推送通知 - Amazon Pinpoint Push Notification not displayed when the app is in foreground on Android Delphi Android Oreo:如何在前台启动服务? - Delphi Android Oreo: How to start service in foreground? 检查Foreground服务是否在Android OREO中运行 - Check if Foreground service is running in Android OREO
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM