[英]Migrate from GCM to FCM
最近我從 GCM 遷移到 FCM,過去幾天我正在努力使它工作。
Android 應用程序正在從 google firebase 控制台接收通知,但它們不會從 php 服務器接收通知。
這是我的 PHP 服務器端代碼:
<?php
define("GOOGLE_API_KEY", Setting::get('browser_key') ? Setting::get('browser_key') : "");
class GCM {
function __construct() {
}
public function send_notification($registatoin_ids, $message) {
Log::info("GOOGLE_API_KEY".GOOGLE_API_KEY);
include_once 'const.php';
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
Log::info('***** PUSH MESSAGE ******'.print_r(json_encode($fields),true));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
Log::info(print_r($result,true));
if ($result === FALSE) {
//die('Curl failed: ' . curl_error($ch));
Log::error('Curl failed: ' . curl_error($ch));
}
else{
//echo $result;
Log::error($result);
}
// Close connection
/*curl_close($ch);
echo $result/*."\n\n".json_encode($fields); */
}
}
?>
這是我的 const.php
<?php
define('TEAM','team');
define('MESSAGE' , 'message');
?>
這是我的 firebase 消息傳遞代碼:
public class MessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Message";
public MessagingService() {
super();
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getBody());
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification());
}
private void sendNotification(String body) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent= PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle("Codegama");
notificationBuilder.setContentText(body);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
這是我在 logcat android studio 中不斷出現的錯誤:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference
at hr.trazim.client.services.MessagingService.onMessageReceived(MessagingService.java:32)
at com.google.firebase.messaging.FirebaseMessagingService.zzd(Unknown Source:60)
at com.google.firebase.iid.zzg.run(Unknown Source:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source:6)
at java.lang.Thread.run(Thread.java:919)
2020-01-07 12:08:11.092 1732-29214/? E/ResolverController: 沒有有效的 NAT64 前綴 (101, /0)
我在這樣的stackoverflow主題上閱讀了很多,但找不到合適的修復/解決方案。 我希望此修復程序能幫助像我這樣的其他開發人員找到合適的答案,而不會像我一樣浪費太多時間。
PS如果您需要我的令牌,我還沒有遷移它,但它在這里工作的是代碼:
public class InstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.e("FCMToken", refreshedToken);
saveDeviceToken(refreshedToken);
}
private void saveDeviceToken(String token) {
UserDataSource.getDataInstance().putDeviceToken(token);
}
}
提前致謝。
你得到錯誤的數據。 它應該是這樣的。 或嘗試先打印數據然后從數組中獲取。
sendNotification(remoteMessage.getData().get("message"));
Log.d("Push data", remoteMessage.getData().toString());
嘗試使用這個:
@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void show_Notification(){
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
String CHANNEL_ID="MYCHANNEL";
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"name",NotificationManager.IMPORTANCE_LOW);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
.setContentText("Heading")
.setContentTitle("subheading")
.setContentIntent(pendingIntent)
.addAction(android.R.drawable.sym_action_chat,"Title",pendingIntent)
.setChannelId(CHANNEL_ID)
.setSmallIcon(android.R.drawable.sym_action_chat)
.build();
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(1,notification);
}
要從 php 服務器發送Firebase 推送通知,您可以使用此代碼。
<?php
function sendMessage($data, $target, $serverKey){
//FCM api URL
$rsp = [];
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = $serverKey;
$fields = array();
$fields['data'] = $data;
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
//die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
//print_r($result);
return $result;
}
如果你想更新你的 android 代碼,你可以關注這篇文章: Firebase 推送通知
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.