Firebase Cloud Messaging的通知未显示在设备上

时间:2019-05-22 11:45:22

标签: android firebase firebase-cloud-messaging

每当我使用Firebase控制台发送通知时。该通知未显示在设备上,但是活动更改为另一个活动或在应用程序上发生了某些操作。

从控制台发送通知时,我将主题以及当前应用程序ID和通知ID添加为“ MyNotifications”。

我已经按照在线说明进行操作,并创建了一个名为MyFirebaseMessagingService的类:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
    }

    public void showNotification(String title, String message) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MyNotifications")
                .setContentTitle(title)
                .setContentText(message);

        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        manager.notify(999, builder.build());
    }
}

我的MainActivityOnCreate中的这段代码组成:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            NotificationChannel channel =
                    new NotificationChannel("MyNotifications", "MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }

        FirebaseMessaging.getInstance().subscribeToTopic("general")
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        String msg = "Successful!";
                        if (!task.isSuccessful()) {
                            msg = "Failed";
                        }
                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });

我也在我的AndroidManifest中添加了它:

<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

1 个答案:

答案 0 :(得分:0)

因此,自API级别21(棒棒糖)以来,必须在通知中放置一个小图标。这就是应用程序崩溃并返回首页的原因。因此,这里对代码所做的唯一更改是:

                .setSmallIcon(R.drawable.fui_ic_twitter_bird_white_24dp);

有关此主题的更多信息,请查看此question