Firebase Cloud Messaging 配置

Firebase Notification配置

前言:

以前項(xiàng)目中用過GCM,現(xiàn)在Google收購了FireBase之后現(xiàn)在需要用到推送,看了下文檔發(fā)現(xiàn)GCM并入了FCM,相關(guān)API和用法基本一致,趁此機(jī)會(huì)整理一下基本配置方法。

基本配置

官方Doc
官方Sample
運(yùn)行要求:android2.3以上及google play service 9.6.1版本以上的設(shè)備
1. 在firebase中創(chuàng)建項(xiàng)目后創(chuàng)建android子項(xiàng)目填寫相關(guān)信息 包括:package id
2. 復(fù)制生成的文件放到module目錄下
3. 在project目錄的build.gradle下添加依賴
 dependencies {
 classpath 'com.google.gms:google-services:3.0.0' 
 }
4. 在module目錄的build.gradle下添加依賴
 dependencies {
    compile 'com.google.firebase:firebase-messaging:9.6.1'
    compile 'com.google.android.gms:play-services:9.6.1'
}
//底部添加plugin   
apply plugin: 'com.google.gms.google-services'
5. 在BaseAvtivity中檢查GoogleService是否可用:
@Override
protected void onResume() {
    super.onResume();
    isGooglePlayServicesAvailable();
    handleFcmDataExtras();
}

public void isGooglePlayServicesAvailable() {
    int state = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
    if (state != SUCCESS)
        GoogleApiAvailability.getInstance().getErrorDialog(this, state, 0).show();
}
6. 繼承FirebaseInstanceIdservice注冊(cè)token
@Override
public void onTokenRefresh() {
    // 獲取 InstanceID
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String refreshedToken) {
    // 在此方法中將InstanceID發(fā)送給app的服務(wù)器,用于定向發(fā)送推送消息。
}
7.繼承FirebaseMessagingService以及在Luncher Activity進(jìn)行接收消息/數(shù)據(jù)的配置。
  • FireBaseMessagingService中
   private final String TAG = "MyFirebaseMsgService";

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        //用于處理主題消息
        //并不是所有的消息都在這里處理,如果APP處在后臺(tái)接收帶數(shù)據(jù)的通知,那么數(shù)據(jù)會(huì)放在啟動(dòng)activity的Intent中
        if ((remoteMessage.getFrom().startsWith("/topics/"))) {
            String topic = remoteMessage.getFrom().replace("/topics/", "");
            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "From: " + topic);
        }
        // 檢查是否包含數(shù)據(jù)
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // 檢查是否包含通知
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
        //如果有其它相關(guān)自定義操作,在這里完成
    }

    /**
     *  創(chuàng)建Notification發(fā)送給
     */
    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_media_play)
                .setContentTitle("FCM Message")
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
  • 在Launcher Activity中
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 當(dāng)Notification的類型是message+data時(shí),data在此處理
        if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                Object value = getIntent().getExtras().get(key);
                Log.d(TAG, "Key: " + key + " Value: " + value);
            }
        }}

推送方式

  1. 根據(jù)app id推送
  2. 根據(jù)設(shè)備的fcm Id推送
  3. 根據(jù)用戶訂閱的topic推送

消息類型

  1. 通知
  2. 數(shù)據(jù)
  3. 通知+數(shù)據(jù)

app接收消息時(shí)的行為

根據(jù)app在前臺(tái)/后臺(tái)、消息類型的不同分別作出不同的行為。

應(yīng)用狀態(tài) 通知 數(shù)據(jù) 兩者
前臺(tái) onMessageReceived onMessageReceived onMessageReceived
后臺(tái) 系統(tǒng)托盤 onMessageReceived 通知:系統(tǒng)托盤;數(shù)據(jù):Intent的extra中
  • 實(shí)測(cè)即使app處于后臺(tái)未kill的狀態(tài),通知也會(huì)交由系統(tǒng)處理。

icon / color 相關(guān)設(shè)定

在5.0以后app的small_icon只允許帶有aplha圖層,不支持rgb圖層。
APP處于前臺(tái)時(shí):可以在onMessageReceived()全權(quán)處理消息如自定義notification : large_icon , small_icon , color .
APP處于后臺(tái)時(shí):由系統(tǒng)通知處理這部分顯示,只可以在Manifest定義 : icon、color

      <meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
          android:resource="@drawable/ic_stat_ic_notification" />
      <meta-data
android:name="com.google.firebase.messaging.default_notification_color"
          android:resource="@color/colorAccent" />
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,040評(píng)論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,563評(píng)論 19 139
  • FCM,即Firebase Cloud Messaging Firebase,F(xiàn)irebase是一家實(shí)時(shí)后端數(shù)據(jù)庫...
    阿敏其人閱讀 38,973評(píng)論 4 16
  • “你不知道自己會(huì)記住些什么,記憶是很任性的?!?這是大三的時(shí)候從隔壁舍友那里收到的話,沒有刻意去記它,但也這樣默默...
    海北sunshine閱讀 444評(píng)論 0 0
  • 七歲,我喜歡拼拼音 八歲,我喜歡騎自行車 九歲,我喜歡畫雞蛋 十歲,我決定每年要喜歡一個(gè)事物 十一歲,我喜歡給家貓...
    倩何人換取閱讀 190評(píng)論 1 1

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