且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Firebase在Android中推送通知获取令牌

更新时间:2023-02-27 08:01:30

尝试这种方式.1.创建服务

Try this way. 1. Create a Service

public class YourService extends FirebaseMessagingService {

public static int NOTIFICATION_ID = 1;

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this, "2")
            .setSmallIcon(R.drawable.your_icon)
            .setContentTitle(remoteMessage.getNotification().getTitle())
            .setContentText(remoteMessage.getNotification().getBody())
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (NOTIFICATION_ID > 1073741824) {
        NOTIFICATION_ID = 0;
    }
    Objects.requireNonNull(notificationManager).notify(NOTIFICATION_ID++, mNotifyBuilder.build());
}

}

现在将其添加到清单

<service
   android:name=".YourService"
   android:exported="false">
   <intent-filter>
       <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>