android項目介入google推送

1.項目的gradle中配置

buildscript {
    dependencies {
        // 增加google services插件配置,用于集成FCM
        classpath 'com.google.gms:google-services:4.4.2'
    }
}
plugins {
    id 'com.google.gms.google-services' version '4.4.2' apply false
}

2.module的gradle中配置

plugins {
    id 'com.google.gms.google-services'
}
//FCM
    implementation platform('com.google.firebase:firebase-bom:33.3.0')
    implementation 'com.google.firebase:firebase-analytics'
    //implementation 'com.google.firebase:firebase-messaging'

    // 確保包含 Firebase Installations 和 FCM 依賴
    implementation 'com.google.firebase:firebase-installations:17.1.0'
    implementation 'com.google.firebase:firebase-messaging:23.3.1'
    // Google Play 服務(wù)基礎(chǔ)庫
    implementation 'com.google.android.gms:play-services-base:18.2.0'

3.AndroidMainfest.xml中

<!--    FCM    -->
        <service
            android:name=".service.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="firebase_messaging_auto_init_enabled"
            android:value="false" />
        <meta-data
            android:name="firebase_analytics_collection_enabled"
            android:value="false" />
        <!--    FCM    -->
        <meta-data
            android:name="com.google.android.gms.wallet.api.enabled"
            android:value="true" />

4.MyFirebaseMessagingService

import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.sportal.util.PushHelper

class MyFirebaseMessagingService: FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        super.onNewToken(token)
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        val extraJson = message.data["extraInfo"] ?: ""
//        val map: HashMap<String, String> = Gson().fromJson(extraJson, object: TypeToken<HashMap<String, String>>(){}.type)
        showNotification(message.notification?.title ?: "", message.notification?.body ?: "", message.messageId.hashCode(), mapOf("extraInfo" to extraJson))
    }
    fun showNotification(title: String, content: String, messageId: Int, extras: Map<String, String>) {
        //當(dāng)處于客服聊天頁面時,客服消息不展示推送通知
//        if (extras["msgType"] == "CUSTOMER_CHAT" && BaseApp.getCurrentActivity() is CustomServiceComposeActivity2) {
//            return
//        }
        if (extras["msgType"] == "CUSTOMER_CHAT" && Global.isIsCustomSession()) {
            return
        }
        val builder = NotificationCompat.Builder(BogoApplication.getInstance(), Constant.NEW_MESSAGE_NTF_CHANNEL_ID).apply {
            setAutoCancel(true)
            setSmallIcon(R.drawable.ic_launcher)
            setWhen(System.currentTimeMillis())
            setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
        }

        val intent = Intent(BogoApplication.getInstance(), SplashActivity::class.java)
        intent.action = IntentAction.ACTION_FROM_NOTIFICATION
        extras.forEach { (t, u) -> intent.putExtra(t, u) }

        val pendingIntent = PendingIntent.getActivity(BogoApplication.getInstance(), messageId, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
        builder.setContentIntent(pendingIntent)

        builder.setLargeIcon(BogoApplication.getInstance().resources.getDrawable(R.drawable.ic_launcher).toBitmap())
        builder.setContentTitle(title)
        builder.setContentText(content)

        ContextCompat.getSystemService(BogoApplication.getInstance(), NotificationManager::class.java)!!.notify(messageId, builder.build())
    }
}

5.去谷歌推送開發(fā)者中心按要求輸出google-services.json

https://firebase.google.com/docs/cloud-messaging/get-started?authuser=0&platform=android

6.在需要的地方生成googletoken,一般登錄的時候需要用到這個字段,服務(wù)端會用于去推送消息。

var googleToken: String? = null//同一臺手機時,一般不會變化
private fun initGooglePush(activity: BaseActivity) {
        FirebaseAnalytics.getInstance(activity).setAnalyticsCollectionEnabled(true)
        FirebaseMessaging.getInstance().isNotificationDelegationEnabled = true
        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if (it.isSuccessful) {
                googleToken = it.result
                FirebaseMessaging.getInstance().subscribeToTopic("SAVOAPP_DEFAULT_TOPIC")
                    .addOnCompleteListener { Log.d("PushHelper", "subscribeToTopic") }
            } else {
                Log.e("PushHelper", "error")
            }
        }
    }

至此就完成了android的集成,要測試是否成功時,先要看服務(wù)端是否推送成功,在服務(wù)端推送成功的前提下,才能夠測試android端是否集成成功。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容