Cordova Android 中的 Firebase 推送通知
將 Firebase 新增到你的 Android 專案中
將 Firebase 新增到你的應用
要將 Firebase 新增到你的應用,你需要一個適用於你應用的 Firebase 專案和 Firebase 配置檔案。
- 如果你還沒有 Firebase 專案,請在 Firebase 控制檯中建立 Firebase 專案。如果你已有與移動應用程式關聯的現有 Google 專案,請單擊“匯入 Google 專案”。否則,單擊建立新專案。
- 點選新增 Firebase 到你的 Android 應用。如果你要匯入現有的 Google 專案,這可能會自動發生,你只需下載配置檔案即可。
- 出現提示時,輸入應用程式的包名稱。輸入你的應用正在使用的包名稱非常重要; 只有在將
應用程式新增到 Firebase 專案時才能設定此項。 - 最後,你將下載 google-services.json 檔案。你可以隨時再次下載此檔案。如果你還沒有這樣做,請將其複製到專案的模組資料夾中,通常是 app /。
Cordova Firebase 推送通知外掛
https://www.npmjs.com/package/cordova-plugin-fcm
要獲取訪問令牌:
FCMPlugin.getToken(
function(token){
alert(token);
},
function(err){
console.log('error retrieving token: ' + err);
}
);
回撥接收推送通知:
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
alert( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
alert( JSON.stringify(data) );
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);
將 get 訪問令牌和回撥放在 receiveEvent 函式中的 index.js 檔案中接收推送通知
通過 REST API 傳送推送通知
//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSyAMMh0mdVIRXPcBejyatAtdZgmklepwoNs //key is server-key
{
"notification":{
"title":"Notification title", //Any value
"body":"Notification body", //Any value
"sound":"default", //If you want notification sound
"click_action":"FCM_PLUGIN_ACTIVITY", //Must be present for Android
"icon":"fcm_push_icon" //White icon Android resource
},
"data":{
"param1":"value1", /Any data to be retrieved in the notification callback
"param2":"value2"
},
"to":"eRImo7algBM:APA91bHSxSOdmgsOi9su_XytEtCbei0Zi0ODgm76VHvbqeb-WPoZcLyNVpnaLWPLw7U1u93hO0ZhtBxn_hVGxPAwxXXfc-yNy6_kkfzUdTpcI2QPB0vzJBmOFzX3RRZ15wmFkCUFtyhc", //Topic or single device
"priority":"high", //If not set, notification won't be delivered on completely closed iOS app
"restricted_package_name":"com.zensar.fcm" //Optional. Set for application filtering
}
使用 Postman rest 客戶端配置上述 REST API。
工作原理向單個裝置或主題傳送推送通知。
1.a 應用程式在前臺:使用者在其裝置通知欄中收到通知訊息。使用者點選通知並開啟應用程式。使用者在 JavaScript 回撥中接收通知資料。
1.b 應用程式在後臺:使用者在其裝置通知欄中收到通知訊息。使用者點選通知並開啟應用程式。使用者在 JavaScript 回撥中接收通知資料。