无法创建推送通知



我在Android Studio中遇到推送通知问题。我从firebase网络控制台向我的设备发送通知。我收到通知是因为我在logcat中看到了正文,但我无法创建推送通知。

这是我的代码:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
String TAG = "";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification().getBody() != null) {
Log.e("FIREBASE", "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage);
}
}
private void sendNotification(RemoteMessage remoteMessage) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "channel_id_0")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, mBuilder.build());
}

}

我的用户权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />

我的服务声明:

<service
android:name=".MyFirebaseMessagingService">
<!--android:enabled="true"
android:exported="true"-->
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>

通知文本正常

使用带有>=Oreo的设备?使用下面的代码。使用pendingIntent,您可以通过触摸通知来打开您的活动(如果您不需要,请删除(:

private void sendNotification(String messageBody, String messageTitle) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "channel_id_0";
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

相关内容

  • 没有找到相关文章

最新更新