Android接入Firebase推送通知

参考:https://firebase.google.com/docs/cloud-messaging/android/client
参考:https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/

Firebase控制台配置

在Firebase控制台创建项目,并配置SHA1,然后下载google-service.json文件并添加到项目的app目录下即可

Gradle添加依赖

1
implementation 'com.google.firebase:firebase-messaging:17.3.4'

创建FirebaseMessagingService服务并注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MyFirebaseMessagingService extends FirebaseMessagingService {
/**
* Called if InstanceID token is updated. This may occur if the security of the previous token had been compromised.
* Note that this is called when the InstanceID token is initially generated so this is where you would retrieve the token.
*/
@Override
public void onNewToken(String token) {
NLog.i(Constants.TAG, "Refreshed token: " + token);

// If you want to send messages to this application instance or manage this apps subscriptions on the server side,
// send the Instance ID token to your app server.
// sendRegistrationToServer(token);
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

NLog.i(Constants.TAG, "From: " + remoteMessage.getFrom());

// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
NLog.i(Constants.TAG, "Message data payload: " + remoteMessage.getData());
}

// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
NLog.i(Constants.TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
}
1
2
3
4
5
<service android:name=".service.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

获取客户端Token

1
2
3
4
5
6
7
8
9
10
11
12
13
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
NLog.w(TAG, "GetInstanceId failed: ", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
NLog.d(TAG, "Firebase Token: " + token);
}
});

注册Topic

1
2
3
4
5
6
7
8
9
10
11
FirebaseMessaging.getInstance().subscribeToTopic("activity")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (!task.isSuccessful()) {
NLog.i(TAG, "Subscribe topic failure");
} else {
NLog.i(TAG, "Subscribe topic success");
}
}
});

控制台发送消息

在控制台左侧选择Cloud Messaging,然后点击写新消息,即可向指定设备或全部设备发送消息

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :