溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android?FCM接入的方法是什么

發(fā)布時間:2023-03-20 14:56:27 來源:億速云 閱讀:120 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了Android FCM接入的方法是什么的相關知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Android FCM接入的方法是什么文章都會有所收獲,下面我們一起來看看吧。

    發(fā)送通知

    消息推送在現(xiàn)在的App中已經(jīng)十分常見,我們經(jīng)常會收到不同App的各種消息。消息推送的實現(xiàn),國內(nèi)與海外發(fā)行的App需要考慮不同的方案。國內(nèi)發(fā)行的App,常見的有可以聚合各手機廠商推送功能的極光、個推等,海外發(fā)行的App肯定是直接使用Firebase Cloud Message(FCM)。

    下面介紹下如何接入FCM與發(fā)送通知。

    FCM的SDK不包含創(chuàng)建和發(fā)送通知的功能,這部分需要我們自己實現(xiàn)。

    在 Android 13+ 上請求運行時通知權限

    Android 13 引入了用于顯示通知的新運行時權限。這會影響在 Android 13 或更高版本上運行的所有使用 FCM 通知的應用。需要動態(tài)申請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<out String>, grantResults: IntArray) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
                if (requestCode == requestPermissionCode) {
                    // 處理回調結果
                }
        }
    }

    創(chuàng)建通知渠道

    從 Android 8.0(API 級別 26)開始,必須為所有通知分配渠道,否則通知將不會顯示。通過將通知歸類到不同的渠道中,用戶可以停用您應用的特定通知渠道(而非停用您的所有通知),還可以控制每個渠道的視覺和聽覺選項。

    創(chuàng)建通知渠道代碼如下:

    class ExampleActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            val notificationManager = NotificationManagerCompat.from(this)
            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
                val applicationInfo = if (Build.VERSION.SDK_INT &gt;= 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")
                    //設置小圖標
                    .setSmallIcon(R.drawable.notification)
                    // 設置通知標題
                    .setContentTitle("title")
                    // 設置通知內(nèi)容
                    .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) 是一種跨平臺消息傳遞解決方案,可讓您免費可靠地發(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目錄下

    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,如下:

    <?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>

    通知圖標的樣式

    當App處于不活躍狀態(tài)時,如果收到通知,F(xiàn)CM會使用默認的圖標與顏色來展示通知,如果需要更改的話,可以在AndroidManifest中通過meta-data進行配置,代碼如下:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
        <application>
            <!--修改默認圖標-->
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_icon"
                android:resource="@drawable/notification" />
            <!--修改默認顏色-->
            <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自動初始化時,更改FirebaseMessagingisAutoInitEnabled的屬性,代碼如下:

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

    調用此代碼后,下次App啟動時FCM會自動初始化。

    測試消息推送

    在Firebase后臺中,選擇Messageing,并點擊制作首個宣傳活動,如圖:

    Android?FCM接入的方法是什么

    選擇Firebase 通知消息,如圖:

    Android?FCM接入的方法是什么

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

    Android?FCM接入的方法是什么

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

    Android?FCM接入的方法是什么

    關于“Android FCM接入的方法是什么”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“Android FCM接入的方法是什么”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

    AI