我试图在我的Android设备上使用GCM发送通知,但我总是收到InvalidRegistration错误。
以下是应该发送通知的PHP代码:
<?php
define('API_ACCESS_KEY', 'API KEY HIDDEN');
$registrationIds = array( $_GET['id']);
// prep the bundle
$msg = array
(
'message' => 'TestMessage',
'title' => 'TestTitle',
'subtitle' => 'TestSubtitle',
'tickerText' => 'TestTicker',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/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;
?>
这是注册的完成方式:
private void registerInBackground() {
new AsyncTask<Void, Object, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
//Here I save the registration ID, and when I try to use it manually, by running the PHP script above, I get the error.
sendRegistrationIdToBackend();
// Persist the registration ID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
Toast.makeText(context, msg + "\n", Toast.LENGTH_SHORT).show();
}
}.execute(null, null, null);
运行应用程序并调用注册应用程序的方法后,我获得了注册ID。然后,当我输入localhost/app/sendNotification.php?id=xxxxxxxxxxxxxx
时,我得到了
{"multicast_id":8460288429151356251,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
答案 0 :(得分:11)
无效的注册ID检查注册ID的格式 你传递给服务器。确保它与注册ID匹配 手机在com.google.android.c2dm.intent.REGISTRATION中收到 意图,并且您不会截断它或添加额外的 字符。错误代码为InvalidRegistration时发生。
所以基本上你在将手机收到的DeviceID发送到服务器时出错了。确保您的代码不会以任何方式改变deviceId。您尚未发布接受身份证的代码。该部分存在错误或存储了DeviceId。我不认为您在错误日志显示的无效注册中发布的代码中有任何错误
答案 1 :(得分:8)
如果您从数据库中检索令牌,其他任何人都要确保该列的数据类型是文本或非常长的varchar(如200)。令牌长度超过100个字符,因此它可能会减少一半存储在db
中答案 2 :(得分:0)
我通过发送设备注册ID解决了这个问题,比如
<?php
require_once('loader.php');
// return json response
$json = array();
$registatoin_ids = array("APA91bHhzESU4GQKwS_I-sMMpAPZ44GbC0wvDAO-Dch87_jwJzaB1gK5PPeaGmt6vFZx2Bvd6AC8EkYDl6PurNUDO6zLoxX50q7gLc8GMOLGcwmQgiWwSZS-PPOFn1MpA5hz_TFQ6S-4tstLO");
$message = array("product" => "shirt");
$result = send_push_notification($registatoin_ids, $message);
echo $result;
?>
在register.php文件中。 你将从谷歌云获得此设备注册ID。