验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Android FCM接入的方法是什么

阅读:653 来源:乙速云 作者:代码code

Android FCM接入的方法是什么

      发送通知

      消息推送在现在的App中已经十分常见,我们经常会收到不同App的各种消息。消息推送的实现,国内与海外发行的App需要考虑不同的方案。国内发行的App,常见的有可以聚合各手机厂商推送功能的极光、个推等,海外发行的App肯定是直接使用Firebase Cloud Message(FCM)。

      下面介绍下如何接入FCM与发送通知。

      FCM的SDK不包含创建和发送通知的功能,这部分需要我们自己实现。

      在 Android 13+ 上请求运行时通知权限

      Android 13 引入了用于显示通知的新运行时权限。这会影响在 Android 13 或更高版本上运行的所有使用 FCM 通知的应用。需要动态申请POST_NOTIFICATIONS权限后才能推送通知,代码如下:

      class ExampleActivity : AppCompatActivity() {
          private val requestPermissionCode = this.hashCode()
          override fun onCreate(savedInstanceState: Bundle?) {
              super.onCreate(savedInstanceState)
                  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && 
                      ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                      // 申请通知权限
                      ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), requestPermissionCode)
                  }
          }
          override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
              super.onRequestPermissionsResult(requestCode, permissions, grantResults)
                  if (requestCode == requestPermissionCode) {
                      // 处理回调结果
                  }
          }
      }

      创建通知渠道

      从 Android 8.0(API 级别 26)开始,必须为所有通知分配渠道,否则通知将不会显示。通过将通知归类到不同的渠道中,用户可以停用您应用的特定通知渠道(而非停用您的所有通知),还可以控制每个渠道的视觉和听觉选项。

      创建通知渠道代码如下:

      class ExampleActivity : AppCompatActivity() {
          override fun onCreate(savedInstanceState: Bundle?) {
              super.onCreate(savedInstanceState)
              val notificationManager = NotificationManagerCompat.from(this)
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                  val applicationInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                      packageManager.getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(0))
                  } else {
                      packageManager.getApplicationInfo(packageName, 0)
                  }
                  val appLabel = getText(applicationInfo.labelRes)
                  val exampleNotificationChannel = NotificationChannel("example_notification_channel", "$appLabel Notification Channel", NotificationManager.IMPORTANCE_DEFAULT).apply {
                      description = "The description of this notification channel"
                  }
                  notificationManager.createNotificationChannel(minigameChannel)
              }
          }
      }

      创建并发送通知

      创建与发送通知,代码如下:

      class ExampleActivity : AppCompatActivity() {
          private var notificationId = 0
          override fun onCreate(savedInstanceState: Bundle?) {
              super.onCreate()
              val notificationManager = NotificationManagerCompat.from(this)
              ...
              if (notificationManager.areNotificationsEnabled()) {
                  val notification = NotificationCompat.Builder(this, "example_notification_channel")
                      //设置小图标
                      .setSmallIcon(R.drawable.notification)
                      // 设置通知标题
                      .setContentTitle("title")
                      // 设置通知内容
                      .setContentText("content")
                      // 设置是否自动取消
                      .setAutoCancel(true)
                      // 设置通知声音
                      .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                      // 设置点击的事件
                      .setContentIntent(PendingIntent.getActivity(this, requestCode, packageManager.getLaunchIntentForPackage(packageName)?.apply { putExtra("routes", "From notification") }, PendingIntent.FLAG_IMMUTABLE))
                      .build()
                  // notificationId可以记录下来
                  // 可以通过notificationId对通知进行相应的操作
                  notificationManager.notify(notificationId, notification)
              }
          }
      }

      *注意,smallIcon必须设置,否则会导致崩溃。

      FCM

      Firebase Cloud Message (FCM) 是一种跨平台消息传递解决方案,可让您免费可靠地发送消息。

      官方接入文档

      集成FCM

      在项目下的build.gradle中添加如下代码:

      buildscript {
          repositories {
              google()
              mavenCentral()
          }
          dependencies {
              ...
              classpath("com.google.gms:google-services:4.3.14")
          }
      }

      在app module下的build.gradle中添加代码,如下:

      dependencies {
          // 使用Firebase Andorid bom(官方推荐)
          implementation platform('com.google.firebase:firebase-bom:31.1.0') 
          implementation 'com.google.firebase:firebase-messaging' 
          // 不使用bom
          implementation 'com.google.firebase:firebase-messaging:23.1.1'
      }

      在Firebase后台获取项目的google-services.json文件,放到app目录下

      Android FCM接入的方法是什么

      要接收FCM的消息推送,需要自定义一个Service继承FirebaseMessagingService,如下:

      class ExampleFCMService : FirebaseMessagingService() {
          override fun onNewToken(token: String) {
              super.onNewToken(token)
              // FCM生成的令牌,可以用于标识用户的身份
          }
          override fun onMessageReceived(message: RemoteMessage) {
              super.onMessageReceived(message)
              // 接收到推送消息时回调此方法
          }

      在AndroidManifest中注册Service,如下:

      
      
          
              
                  
                      
                  
              
          
      

      通知图标的样式

      当App处于不活跃状态时,如果收到通知,FCM会使用默认的图标与颜色来展示通知,如果需要更改的话,可以在AndroidManifest中通过meta-data进行配置,代码如下:

      
      
          
              
              
              
              
          
      

      避免自动初始化

      如果有特殊的需求,不希望FCM自动初始化,可以通过在AndroidManifest中配置meta-data来实现,代码如下:

      
      
          
              
              
              
          
      

      需要重新启动FCM自动初始化时,更改FirebaseMessagingisAutoInitEnabled的属性,代码如下:

      FirebaseMessaging.getInstance().isAutoInitEnabled = true
      // 如果同时禁止了Google Analytics,需要配置如下代码
      FirebaseAnalytics.getInstance(context).setAnalyticsCollectionEnabled(true)

      调用此代码后,下次App启动时FCM会自动初始化。

      测试消息推送

      在Firebase后台中,选择Messageing,并点击制作首个宣传活动,如图:

      Android FCM接入的方法是什么

      选择Firebase 通知消息,如图:

      Android FCM接入的方法是什么

      输入标题和内容后,点击发送测试消息,如图:

      Android FCM接入的方法是什么

      输入在FirebaseMessagingService的onNewToken方法中获取到的token,并点击测试,如图:

      Android FCM接入的方法是什么

    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>