一文詳解Android?FCM接入
發(fā)送通知
消息推送在現(xiàn)在的App中已經(jīng)十分常見,我們經(jīng)常會收到不同App的各種消息。消息推送的實現(xiàn),國內(nèi)與海外發(fā)行的App需要考慮不同的方案。國內(nèi)發(fā)行的App,常見的有可以聚合各手機(jī)廠商推送功能的極光、個推等,海外發(fā)行的App肯定是直接使用Firebase Cloud Message(FCM)。
下面介紹下如何接入FCM與發(fā)送通知。
FCM的SDK不包含創(chuàng)建和發(fā)送通知的功能,這部分需要我們自己實現(xiàn)。
在 Android 13+ 上請求運(yùn)行時通知權(quán)限
Android 13 引入了用于顯示通知的新運(yùn)行時權(quán)限。這會影響在 Android 13 或更高版本上運(yùn)行的所有使用 FCM 通知的應(yīng)用。需要動態(tài)申請POST_NOTIFICATIONS權(quán)限后才能推送通知,代碼如下:
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) {
// 申請通知權(quán)限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), requestPermissionCode)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == requestPermissionCode) {
// 處理回調(diào)結(jié)果
}
}
}
創(chuàng)建通知渠道
從 Android 8.0(API 級別 26)開始,必須為所有通知分配渠道,否則通知將不會顯示。通過將通知歸類到不同的渠道中,用戶可以停用您應(yīng)用的特定通知渠道(而非停用您的所有通知),還可以控制每個渠道的視覺和聽覺選項。
創(chuàng)建通知渠道代碼如下:
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)
}
}
}
創(chuàng)建并發(fā)送通知
創(chuàng)建與發(fā)送通知,代碼如下:
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")
//設(shè)置小圖標(biāo)
.setSmallIcon(R.drawable.notification)
// 設(shè)置通知標(biāo)題
.setContentTitle("title")
// 設(shè)置通知內(nèi)容
.setContentText("content")
// 設(shè)置是否自動取消
.setAutoCancel(true)
// 設(shè)置通知聲音
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
// 設(shè)置點擊的事件
.setContentIntent(PendingIntent.getActivity(this, requestCode, packageManager.getLaunchIntentForPackage(packageName)?.apply { putExtra("routes", "From notification") }, PendingIntent.FLAG_IMMUTABLE))
.build()
// notificationId可以記錄下來
// 可以通過notificationId對通知進(jìn)行相應(yīng)的操作
notificationManager.notify(notificationId, notification)
}
}
}
*注意,smallIcon必須設(shè)置,否則會導(dǎo)致崩潰。
FCM
Firebase Cloud Message (FCM) 是一種跨平臺消息傳遞解決方案,可讓您免費可靠地發(fā)送消息。
集成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目錄下

要接收FCM的消息推送,需要自定義一個Service繼承FirebaseMessagingService,如下:
class ExampleFCMService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
// FCM生成的令牌,可以用于標(biāo)識用戶的身份
}
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
// 接收到推送消息時回調(diào)此方法
}
在AndroidManifest中注冊Service,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<service
android:name="com.minigame.fcmnotificationsdk.MinigameFCMService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
通知圖標(biāo)的樣式
當(dāng)App處于不活躍狀態(tài)時,如果收到通知,F(xiàn)CM會使用默認(rèn)的圖標(biāo)與顏色來展示通知,如果需要更改的話,可以在AndroidManifest中通過meta-data進(jìn)行配置,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!--修改默認(rèn)圖標(biāo)-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/notification" />
<!--修改默認(rèn)顏色-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/color_blue_0083ff" />
</application>
</manifest>
修改前:

修改后:

避免自動初始化
如果有特殊的需求,不希望FCM自動初始化,可以通過在AndroidManifest中配置meta-data來實現(xiàn),代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<meta-data
android:name="firebase_messaging_auto_init_enabled"
android:value="false" />
<!--如果同時引入了谷歌分析,需要配置此參數(shù)-->
<meta-data
android:name="firebase_analytics_collection_enabled"
android:value="false" />
</application>
</manifest>
需要重新啟動FCM自動初始化時,更改FirebaseMessaging的isAutoInitEnabled的屬性,代碼如下:
FirebaseMessaging.getInstance().isAutoInitEnabled = true // 如果同時禁止了Google Analytics,需要配置如下代碼 FirebaseAnalytics.getInstance(context).setAnalyticsCollectionEnabled(true)
調(diào)用此代碼后,下次App啟動時FCM會自動初始化。
測試消息推送
在Firebase后臺中,選擇Messageing,并點擊制作首個宣傳活動,如圖:

選擇Firebase 通知消息,如圖:

輸入標(biāo)題和內(nèi)容后,點擊發(fā)送測試消息,如圖:

輸入在FirebaseMessagingService的onNewToken方法中獲取到的token,并點擊測試,如圖:

示例
已整合到demo中。
效果如圖:

以上就是一文詳解Android FCM接入的詳細(xì)內(nèi)容,更多關(guān)于Android FCM接入的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android Flutter自適應(yīng)瀑布流案例詳解
這篇文章主要介紹了Android Flutter自適應(yīng)瀑布流案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
Android TextView 去掉自適應(yīng)默認(rèn)的fontpadding的實現(xiàn)方法
這篇文章主要介紹了Android TextView 去掉自適應(yīng)默認(rèn)的fontpadding的實現(xiàn)方法的相關(guān)資料,希望通過本文大家能夠掌握這部分內(nèi)容,需要的朋友可以參考下2017-09-09
使用android studio開發(fā)工具編譯GBK轉(zhuǎn)換三方庫iconv的方法
這篇文章主要介紹了使用android studio開發(fā)工具編譯GBK轉(zhuǎn)換三方庫iconv的教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
Android Activity與Service通信(不同進(jìn)程之間)詳解
這篇文章主要介紹了Android Activity與Service通信(不同進(jìn)程之間)的相關(guān)資料,這里提供了三種方法,需要的朋友可以參考下2016-10-10
android中使用Html渲染的方式實現(xiàn)必填項前面的*號示例
本篇文章主要介紹了android中使用Html渲染的方式實現(xiàn)必填項前面的*號示例,具有一定的參考價值,有興趣的可以了解一下2017-09-09
Matrix的set,pre,post調(diào)用順序詳解
下面小編就為大家?guī)硪黄狹atrix的set,pre,post調(diào)用順序詳解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04

