我试图在一个信使应用程序,但这里的扭转是,我有两个实体(即两个应用程序A& B)在这里。
现在,我试图使用Firebase将消息传递逻辑放在两者之间。Firebase不支持在同一个项目url上进行两个不同应用程序(A & B)之间的通信。为了克服这一限制,我对应用程序B也使用了相同的应用程序A的google-service.json
。
对于应用程序B,我刚刚更改了项目id
和auth key
。这似乎和我想的一样有效。我也使用Firebase控制台测试了推送通知,它似乎一直在工作。
然后,我尝试实现服务器逻辑。做一对一的通知。
案例1
但是这里出现的问题是,在应用程序B中,如果我发送通知请求,我会得到一个MismatchSenderId
错误,其中项目id还没有经过调整。
{"multicast_id":[removed],"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
案例2
对于应用程序A,下面是我得到的响应:
{"multicast_id":[removed],"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1473661851590851%0e4bcac9f9fd7ecd"}]}
为此,成功的值是1
,因此,应该发送通知,但当我从设备发出请求时它不会发送。但是,当我使用Postman或任何其他客户端执行相同的服务器调用时,它是完美无缺的。
这是我的代码MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
private static final String FRIENDLY_ENGAGE_TOPIC = "friendly_engage";
@Override
public void onCreate() {
String savedToken = Utility.getFirebaseInstanceId(getApplicationContext());
String defaultToken = getApplication().getString(R.string.pref_firebase_instance_id_default_key);
Log.d("GCM", savedToken);
if (savedToken.equalsIgnoreCase(defaultToken))
//currentToken is null when app is first installed and token is not available
//also skip if token is already saved in preferences...
{
String CurrentToken = FirebaseInstanceId.getInstance().getToken();
if (CurrentToken != null)
Utility.setFirebaseInstanceId(getApplicationContext(), CurrentToken);
Log.d("Value not set", CurrentToken);
updateFCMTokenId(CurrentToken);
}
super.onCreate();
}
/**
* The Application's current Instance ID token is no longer valid
* and thus a new one must be requested.
*/
@Override
public void onTokenRefresh() {
// If you need to handle the generation of a token, initially or
// after a refresh this is where you should do that.
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "FCM Token: " + token);
Utility.setFirebaseInstanceId(getApplicationContext(), token);
updateFCMTokenId(token);
}
private void updateFCMTokenId(final String token) {
SQLiteHandler db = new SQLiteHandler(getBaseContext());
final HashMap<String, String> map = db.getUserDetails();
//update fcm token for push notifications
StringRequest str = new StringRequest(Request.Method.POST, AppConfig.UPDATE_GCM_ID, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("GCM RESPONSE", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> param = new HashMap<>();
param.put("user_id", map.get("uid"));
param.put("gcm_registration_id", token);
return param;
}
};
str.setShouldCache(false);
str.setRetryPolicy(new DefaultRetryPolicy(AppConfig.DEFAULT_RETRY_TIME, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(str);
}
}
FirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
try {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getData().get("message"));
} catch (Exception e) {
e.printStackTrace();
}
//Calling method to generate notification
sendNotification(remoteMessage.getData().get("message"));
}
//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, ChatRoomActivity.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);
android.support.v4.app.NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("NAME")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
下面是Manifest.xml中Application
标记中的声明
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
提亚
案件1已解决
我设法解决了案例1,对于B,我必须使用B的服务器api键,类似地,对于A
编辑2
添加服务器端代码
public function sendNotification($message, $gcm_id, $user_level)
{
if ($user_level == "level") {
$server_key = "xys";
} else $server_key = "ABC";
$msg = array
(
'message' => $message,
'title' => 'Title',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'to' => $gcm_id,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . $server_key,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
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);
curl_close($ch);
echo $result;
}
发布于 2016-09-12 07:45:30
编辑#1:
1)确保您正在向fcm发送有效的json。2)确保您发送到正确的令牌。
关于如何发送通知的其他信息:
向特定设备发送消息
若要向特定设备发送消息,请将特定应用程序实例的注册令牌设置为
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send
向主题发送消息
这里的主题是:/ the /foo
curl -H "Content-type: application/json" -H "Authorisation:key=<Your Api key>" -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send
向设备组发送消息
向设备组发送消息与向单个设备发送消息非常相似。将to参数设置为设备组的唯一通知键。
curl -H "Content-type: application/json" -H "Authorisation:key=<Your Api key>" -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send
原件:
问题在于您的服务器配置。如果您想要在单个服务器中管理两个防火墙应用程序,您必须使用位于以下位置的firebase APK_KEY配置两个防火墙应用程序:
转到Firebase控制台中的应用程序,->点击右上角的三个点,->管理->云消息-> (服务器键)
在您为两个应用程序获得两个服务器密钥之后,您必须像这样配置它:
var firebaseLib = require("firebase");
var app1Config = {
apiKey: "<PROJECT_1_API_KEY>",
authDomain: "<PROJECT_1_ID>.firebaseapp.com",
databaseURL: "https://<PROJECT_1_DATABASE_NAME>.firebaseio.com",
storageBucket: "<PROJECT_1_BUCKET>.appspot.com",
}
var app2Config = {
apiKey: "<PROJECT_2_API_KEY>",
authDomain: "<PROJECT_2_ID>.firebaseapp.com",
databaseURL: "https://<PROJECT_2_DATABASE_NAME>.firebaseio.com",
storageBucket: "<PROJECT_2_BUCKET>.appspot.com",
}
var firebaseApp1 = firebaseLib.initailize(app1Config); // Primary
var firebaseApp2 = firebaseLib.initailize(app2Config, "Secondary"); // Secondary
发布于 2016-12-14 04:59:09
我修正了误差MismatchSenderId
例子如下:
有效令牌:cwsm26j-8qM:APA91bEGbg5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
无效令牌: APA91bEGbg5xxxxxxxxxxxxxxxxxxxxxx
https://stackoverflow.com/questions/39444560
复制相似问题