近日公司APP需要新增海外版的App推送,需要接入FCM推送,在此做做个记录.
首先得有一个谷歌开发者账号,将项目与Firebase关联,下载json文件,并放到项目指定位置,关联参考链接
1.首先在项目级 build.gradle
文件中的 buildscript
和 allprojects
部分添加 Google 的 Maven 代码库。
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// ...
// Add the following line:
classpath 'com.google.gms:google-services:4.2.0' // Google Services plugin
}
}
allprojects {
// ...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
// ...
}
}
2.在您的模块(应用级)Gradle 文件(通常是 app/build.gradle
)中,在文件末尾添加一行内容。
apply plugin: 'com.android.application'
android {
// ...
}
// Add the following line to the bottom of the file:
apply plugin: 'com.google.gms.google-services' // Google Play services Gradle plugin
3.将 Firebase SDK 添加到您的应用.
在您的模块(应用级)Gradle 文件(通常是 app/build.gradle
)中,添加核心 Firebase SDK 的依赖项:
dependencies {
// ...
implementation 'com.google.firebase:firebase-core:17.0.0'
// Getting a "Could not find" error? Make sure that you've added
// Google's Maven repository to your root-level build.gradle file
}
2.设置 Firebase 和 FCM SDK
将 Android 版云消息传递库的依赖项添加到您的模块(应用级)Gradle 文件(通常为 app/build.gradle
)
implementation 'com.google.firebase:firebase-messaging:20.0.0'
新建一个FcmMessagService继承 FirebaseMessagingService
/**
* create by
* on 2020/4/27
* explain${Fcm接收通知}
*/
public class FcmMessagService extends FirebaseMessagingService {
public static String TAG = "tag_-----FcmMessagService:";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.e(TAG, "From Id為: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
// scheduleJob();
} else {
// Handle message within 10 seconds
// handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
// if (remoteMessage.getNotification() != null && remoteMessage.getNotification().getBody() != null) {
// sendNotification(getApplicationContext(), remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
// } else {
// sendNotification(getApplicationContext(), remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
// }
}
@Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
@Override
public void onMessageSent(String s) {
super.onMessageSent(s);
}
@Override
public void onSendError(String s, Exception e) {
super.onSendError(s, e);
}
private void sendNotification(Context iContext, String messageTitle, String messageBody) {
NotificationManager notificationManager = (NotificationManager) iContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, MessageActivity.class); // 接收到通知后,点击通知,启动 MessageActivity
// PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500, 500, 500, 500, 500};
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "-1")
.setTicker(messageTitle)
.setSmallIcon(R.mipmap.able_icon)
.setContentTitle("push 通知 标题")
.setAutoCancel(true)
.setContentText(messageBody)
.setWhen(System.currentTimeMillis())
.setVibrate(pattern)
.setLights(Color.BLUE, 1, 1);
builder.setDefaults(NotificationCompat.DEFAULT_SOUND | NotificationCompat.DEFAULT_VIBRATE);
// builder.setContentIntent(pendingIntent);
// builder.setFullScreenIntent(pendingIntent, true);//将一个Notification变成悬挂式Notification
if (notificationManager != null) {
notificationManager.notify(0, builder.build());
}
}
}
在AndroidManifest.xml添加服务:
<service
android:name=".FcmMessagService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@mipmap/xxx_icon" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
在需要的地方获取令牌,设备要有Google Play服务才行,
//檢查是否安裝了GooglePlay,安裝了則設置token,未安裝則不設置,默認為空
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.e("TAG", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
InstanceIdResult result = task.getResult();
if (result != null) {
String token = result.getToken();
//保存FCM token
ABLESharedPreferencesUtils.setFcmToken(xxx.this, token);
}
}
});
然后在平台上推送测试推送,正常接收即可,
App在前台推送:
App在后台推送: