使用GCM在应用程序上发送通知,返回InvalidRegistration错误

Val*_*Val 8 php android google-cloud-messaging

我正在尝试在我的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;
?>
Run Code Online (Sandbox Code Playgroud)

这是注册的完成方式:

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);
Run Code Online (Sandbox Code Playgroud)

运行应用程序并调用注册应用程序的方法后,我获得了注册ID.然后,当我输入localhost/app/sendNotification.php?id=xxxxxxxxxxxxxx

{"multicast_id":8460288429151356251,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
Run Code Online (Sandbox Code Playgroud)

小智 13

无效的注册ID检查传递给服务器的注册ID的格式.确保它与com.google.android.c2dm.intent.REGISTRATION意图中手机收到的注册ID相匹配,并且您不会截断它或添加其他字符.错误代码为InvalidRegistration时发生.

所以基本上你在将手机收到的DeviceID发送到服务器时会出错.确保您的代码不会以任何方式改变deviceId.您尚未发布接受ID的代码.该部分存在错误或存储DeviceId.我不认为您发布的代码中有任何错误,因为errorLog显示的无效注册


Nas*_*Sr. 9

如果您从数据库中检索令牌,其他任何人都要确保该列的数据类型是文本或非常长的varchar(如200).令牌长度超过100个字符,因此它可能会被切成两半以存储在D b