当前位置:   article > 正文

Android Firebase (FCM)推送接入

Android Firebase (FCM)推送接入

官方文档:

向后台应用发送测试消息  |  Firebase Cloud Messaging

1、根级(项目级)Gradlegradle的dependencies中添加:

  1. dependencies {
  2. ...
  3. // Add the dependency for the Google services Gradle plugin
  4. classpath 'com.google.gms:google-services:4.3.10'
  5. }

2、模块(应用级)Gradle 中添加 Google 服务插件:

  1. plugins {
  2. id 'com.android.application'
  3. // Add the Google services Gradle plugin
  4. id 'com.google.gms.google-services'
  5. ...
  6. }
  7. 或者
  8. apply {
  9. plugin 'com.android.application'
  10. // Add the Google services Gradle plugin
  11. plugin "com.google.gms.google-services"
  12. }

添加 Firebase Cloud Messaging Android 库的依赖项:(按官方的应该也是可以的)

  1. implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
  2. implementation("com.google.firebase:firebase-analytics-ktx")
  3. // implementation("com.google.firebase:firebase-auth-ktx")
  4. implementation("com.google.firebase:firebase-firestore-ktx")
  5. implementation("com.google.firebase:firebase-messaging")
  6. // Firebase Cloud Messaging (Kotlin)
  7. implementation("com.google.firebase:firebase-messaging-ktx")

3、消息接收

AndroidManifest.xml中添加,接受类

  1. <service
  2. android:name=".BillionFirebaseMessagingService"
  3. android:exported="true">
  4. <intent-filter>
  5. <action android:name="com.google.firebase.MESSAGING_EVENT" />
  6. </intent-filter>
  7. </service>
  1. import android.app.Notification;
  2. import android.app.NotificationChannel;
  3. import android.app.NotificationManager;
  4. import android.app.PendingIntent;
  5. import android.content.Intent;
  6. import android.content.pm.PackageManager;
  7. import android.os.Build;
  8. import android.util.Log;
  9. import androidx.annotation.NonNull;
  10. import androidx.core.app.NotificationCompat;
  11. import androidx.core.app.NotificationManagerCompat;
  12. import androidx.core.content.ContextCompat;
  13. import com.game.base.sdk.BaseSDK;
  14. import com.game.base.sdk.Events;
  15. import com.google.firebase.messaging.FirebaseMessagingService;
  16. import com.google.firebase.messaging.RemoteMessage;
  17. import com.google.gson.Gson;
  18. import org.json.JSONArray;
  19. import org.json.JSONException;
  20. import org.json.JSONObject;
  21. import java.util.Locale;
  22. import java.util.Map;
  23. import java.util.jar.JarException;
  24. import java.lang.Boolean;
  25. import game.billion.block.blast.bbb.MainActivity;
  26. import game.billion.block.blast.bbb.R;
  27. import kotlin.Pair;
  28. public class BillionFirebaseMessagingService extends FirebaseMessagingService {
  29. private String channelID = "game.puzzle.block.billion.pro.notification";
  30. private String channelName = "messageName";
  31. int notifyID = 101010;
  32. //监控令牌的生成
  33. @Override
  34. public void onNewToken(@NonNull String token) {
  35. super.onNewToken(token);
  36. Log.d("BillionFirebaseMessagingService", "onNewToken:"+token);
  37. }
  38. //监控推送的消息
  39. @Override
  40. public void onMessageReceived(@NonNull RemoteMessage mge) {
  41. super.onMessageReceived(mge);
  42. Log.d("BillionFirebaseMessagingService", "From:"+mge.getFrom());
  43. Log.d("BillionFirebaseMessagingService", "data:"+mge.getData());
  44. Map<String,String> dt = mge.getData();
  45. String ti =dt.get("title"); //标题(多语言),JSON字符串
  46. try {
  47. if (ti != null && !ti.isEmpty())
  48. {
  49. JSONObject json =new JSONObject(ti);
  50. String language = Locale.getDefault().getLanguage();
  51. if (language=="pt")
  52. {
  53. //获取巴西语
  54. String resTitle = json.getString("pt");
  55. if (resTitle != null && !resTitle.isEmpty())
  56. {
  57. //显示通知
  58. addNotification(resTitle);
  59. }
  60. }else {
  61. String resTitle = json.getString("en");
  62. if (resTitle != null && !resTitle.isEmpty())
  63. {
  64. //显示通知
  65. addNotification(resTitle);
  66. }
  67. }
  68. }
  69. } catch (JSONException e) {
  70. }
  71. String mgeId = mge.getMessageId();
  72. String intent =dt.get("intent");
  73. String strId =dt.get("sid");
  74. Pair<String, String>[] params = new Pair[3];
  75. params[0] = new Pair<>("message_id", mgeId);
  76. params[1] = new Pair<>("type", intent);
  77. params[2] = new Pair<>("sid", strId);
  78. Events.push("100410", params);
  79. }
  80. //添加提示
  81. private void addNotification(String resTitle )
  82. {
  83. if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
  84. NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
  85. NotificationChannel nc=newNotificationChannel(channelID, channelName);
  86. if (nc!=null)
  87. {
  88. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  89. managerCompat.createNotificationChannel(nc);
  90. }
  91. }
  92. Intent nfIntent = new Intent(this, MainActivity.class);
  93. PendingIntent pendingIntent ;
  94. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
  95. pendingIntent=PendingIntent.getActivity(this, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE);
  96. } else {
  97. pendingIntent=PendingIntent.getActivity(this, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
  98. }
  99. NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelID);
  100. builder.setContentIntent(pendingIntent); // 设置PendingIntent
  101. builder.setSmallIcon(R.drawable.notification); // 设置状态栏内的小图标
  102. builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
  103. builder.setStyle(new NotificationCompat.BigTextStyle());
  104. builder.setContentTitle(getString(R.string.app_name));
  105. builder.setContentText(resTitle);
  106. builder.setWhen(System.currentTimeMillis());
  107. builder.setAutoCancel(true);
  108. managerCompat.notify(notifyID, builder.build());
  109. }
  110. }
  111. private NotificationChannel newNotificationChannel(String cId, String cName)
  112. {
  113. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  114. NotificationChannel channel =new NotificationChannel(cId, channelName, NotificationManager.IMPORTANCE_HIGH);
  115. channel.setSound(null, null);
  116. channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
  117. return channel;
  118. }
  119. return null;
  120. }
  121. }

4、测试(google-services.json 记得放应用级中)

a、获取tokn

  1. //在firebase中检查google版本是否有问题
  2. GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this).addOnCompleteListener(new OnCompleteListener<Void>() {
  3. @Override
  4. public void onComplete(@NonNull Task<Void> task) {
  5. if (task.isSuccessful()) {
  6. Log.d("Firebase", "onComplete: Play services OKAY");
  7. //firebase 推送 (FCM)获取token(FCM令牌)
  8. FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
  9. @Override
  10. public void onComplete(@NonNull Task<String> task) {
  11. if (!task.isSuccessful())
  12. {
  13. Log.w("Firebase", "Fetching FCM registration token failed", task.getException());
  14. return;
  15. }
  16. // Get new FCM registration token
  17. String ss= task.getResult();
  18. Log.d("Firebase", "onComplete:token getResult "+ss);
  19. }
  20. });
  21. } else {
  22. // Show the user some UI explaining that the needed version
  23. // of Play services Could not be installed and the app can't run.
  24. }
  25. }
  26. });

b、用tokn就能对固定手机发送消息

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/40400
推荐阅读
相关标签
  

闽ICP备14008679号