到 Firebase 控制台,選擇 Android 應用程式圖示
輸入Android專案名稱(請與gradle中的namespace一致)
下載json並加入Android專案中
在Android Studio中找到Tools/Firebase
找到Cloud Messaging
依序點擊,並照著提示會幫你自動添加Gradle
用於處理 Firebase 遠端訊息的接收和處理。
public class FCMService extends FirebaseMessagingService {
public FCMService() {}
@Override
public void onNewToken(@NonNull String token) {
super.onNewToken(token);
Log.d("itDemo", "此設備Token: "+token);
}
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = getSystemService(NotificationManager.class);
NotificationChannel channel = new NotificationChannel(
"it_ID", "it_demo", notificationManager.IMPORTANCE_DEFAULT);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
RemoteMessage.Notification notification = remoteMessage.getNotification();
NotificationCompat.Builder builder
= new NotificationCompat.Builder(FCMService.this,"it_demo")
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE);
NotificationManagerCompat notificationManagerCompat
= NotificationManagerCompat.from(FCMService.this);
notificationManagerCompat.notify(1,builder.build());
}
}
FCMService 類別繼承了 FirebaseMessagingService 並覆寫了 onNewToken 與 onMessageReceived 方法。