2018年12月14日 星期五

Android Fcm 基本用法

Set up 跳過


結論
Firebase console 裡面只能推播帶有通知的資料,不能純粹推播資料,必須自己寫post request to fcm。



當app在背景時
收到推播時,「推播只有fcm預設的通知樣式」,且在onMessageReceived取不到資料,無法根據推播資料客製通知UI。當按下通知時,才能經由onCreate 或 onNewIntent 去抓 intent資料,實在有點雞肋。


當app在前景時
資料會進入onMessageReceived但是不會有通知跳出來,除非自己寫一個,你可以根據推播資料客製通知UI。


如果只想把推播通知推到某台手機,可以使用以下取得token在set到fcm上:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, new OnSuccessListener<InstanceIdResult>() {

@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
     String newToken = instanceIdResult.getToken();                LogUtil.logString("newToken", newToken);
     }
});


onMessageReceived資料細節:

//remoteMessage detail
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
LogUtil.logString("FCM message from = " + remoteMessage.getFrom()); //398173965753
LogUtil.logString("getMessageId = " + remoteMessage.getMessageId()); //0:1544769433215868%f3db448ff3db448f
LogUtil.logString("getCollapseKey = " + remoteMessage.getCollapseKey()); //com.xxx.xxx.xxx
LogUtil.logString("getMessageType = " + remoteMessage.getMessageType()); //null
LogUtil.logString("getTtl = " + remoteMessage.getTtl()); //2419200
LogUtil.logString("getTo = " + remoteMessage.getTo()); //null
LogUtil.logString("getPriority = " + remoteMessage.getPriority()); //1
LogUtil.logString("getOriginalPriority = " + remoteMessage.getOriginalPriority()); //1
//usage
LogUtil.logString("getTitle = " + remoteMessage.getNotification().getTitle()); //title
LogUtil.logString("getBody = " + remoteMessage.getNotification().getBody()); //content
LogUtil.logString("getData = " + remoteMessage.getData().toString()); //{aaa=bbb,ccc=ddd}


點擊通知會打開app,取得getIntent裡的extra資料細節:


在自訂資料的部分,每個key value都可以在這邊抓到,還算方便。

if (getIntent().getExtras() != null) {

     for (String key : getIntent().getExtras().keySet()) {
          String value = getIntent().getExtras().getString(key);
          LogUtil.logString("Key: " + key + " Value: " + value);
     }
}

//Key: google.delivered_priority Value: high
//Key: google.sent_time Value: null
//Key: google.ttl Value: null
//Key: google.original_priority Value: high
//Key: aaa Value: bbb
//Key: from Value: 398173965753
//Key: title Value: title
//Key: google.message_id Value: 0:1544774861711777%f3db448ff3db448f
//Key: content Value: content
//Key: collapse_key Value: com.xxx.xxx.xxx



沒有留言:

張貼留言