GCM errorCode = NotRegistered

时间:2016-03-29 11:27:15

标签: java android google-cloud-messaging

我正在开发一个使用GCM技术的应用。我正在尝试使用令牌(“cX1gcdNYiQQ:APA91bE4 ...”)从我的基于Java(Eclipse)的服务器发送推送通知 注册到我的应用程序的用户已保存在我的数据库中。 当我尝试向用户发送通知时,它说 “errorCode = NotRegistered”。我试图删除令牌并再次注册,但它仍然给我这个错误,总是这个错误没有别的。 我通过USB线将应用程序运行到我的智能手机(LG)。 我该怎么做才能解决这个问题,我做错了什么?

服务器代码:

    package jdbc;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.sound.midi.SysexMessage;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

public class GcmSender {
     private static final int GCM_RETRIES = 0;

    public void sendGooglePushNotification(String token, String type, String      
     data) {

        // Create Message
    Message.Builder builder = new Message.Builder().delayWhileIdle(true);

    try {
        builder.addData(Params.TYPE_MESSAGE, URLEncoder.encode(type, "UTF-       
       8"));
        builder.addData(Params.DATA_MESSAGE, URLEncoder.encode(data, "UTF-
   8"));
      } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
           e1.printStackTrace();
        }

       Message gcm_message = builder.build();

       // Create Sender
        Sender sender = new Sender(Params.GCM_SERVER_KEY);

         // Sending Message with Sender to the list of users.
        try {

           Result rs=sender.send(gcm_message, token, GCM_RETRIES);
           String ans=rs.toString();
            System.out.println(ans);

            //System.out.println("notification sent");
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           // Failed to Send Message.

       }

   }

AndroidManifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.world.bolandian.watchme"
     android:installLocation="preferExternal">

     <!-- To access Google+ APIs: -->
     <uses-permission android:name="android.permission.INTERNET" />
     <!--
     To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user.
              This disconnect
      option is required to comply with the Google+ Sign-In developer 
   policies
     -->
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<!-- To retrieve the account name (email) as part of sign-in: -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

<!-- [START gcm_permission] -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<permission
    android:name="com.world.bolandian.watchme.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.world.bolandian.watchme.permission.C2D_MESSAGE" />

<!-- [END gcm_permission] -->
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="com.world.bolandian.watchme.MainActivity" />

            <category android:name="android.intent.category.default" />
        </intent-filter>
    </activity>
    <!--
    <activity
        android:name="."
        android:label="@string/title_activity_register" >
        <intent-filter>
            <action android:name="com.world.bolandian.watchme.Register" />

            <category android:name="android.intent.category.default" />
        </intent-filter>
    </activity>
    -->
    <activity
        android:name=".Login"
        android:label="@string/title_activity_login"
        android:windowSoftInputMode="adjustResize|stateHidden">
        <intent-filter>
            <action android:name="com.world.bolandian.watchme.Login" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <!--
    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.world.bolandian.watchme" />
        </intent-filter>
    </receiver>
    -->
    <service
        android:name=".MyGcmListenerService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>
    <service
        android:name=".MyInstanceIDListenerService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID" />
        </intent-filter>
    </service>
    <service
        android:name=".RegistrationIntentService"
        android:exported="false"></service>

    <meta-data
        android:name="com.google.android.gms.wallet.api.enabled"
        android:value="true"/>
</application>

这是Android应用中的监听器代码(从谷歌开发者网站下载)

package com.world.bolandian.watchme;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent; 
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GcmListenerService;

public class MyGcmListenerService extends GcmListenerService {

private static final String TAG = "MyGcmListenerService";

/**
 * Called when message is received.
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("gcm_message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
    } else {
        // normal downstream message.
    }

    // [START_EXCLUDE]
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to 
   the user
     * that a message was received.
     */
    sendNotification(message);
    // [END_EXCLUDE]
    }
    // [END receive_message]

   /**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received.
 */
    private void sendNotification(String message) {
       Intent intent = new Intent(this, MainActivity.class);
       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /*          Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

      Uri defaultSoundUri =      RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      NotificationCompat.Builder notificationBuilder = new No    tificationCompat.Builder(this)
            //.setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("GCM Message")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

2 个答案:

答案 0 :(得分:1)

你可以试试这个approch ..

    <!-- GCM connects to Internet Services. -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <!-- Keeps the processor from sleeping when a message is received. -->
     <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!-- Only this application can receive the messages and registration result -->
        <permission
        android:name="com.world.bolandian.watchmek.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

        <!-- This app has permission to register and receive message -->
        <uses-permission android:name="com.world.bolandian.watchme.permission.C2D_MESSAGE" />
        <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />



        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.world.bolandian.watchme" />
            </intent-filter>
        </receiver>

        <service android:name=".GcmIntentService" />

您可以检查服务器端编程是否正确。  here(使用注册令牌ID和api密钥检查推送通知)

Not Register由于以下问题而来。

  1. 如果客户端应用程序取消注册GCM。如果是客户端应用程序 自动取消注册,可能发生

  2. 如果用户卸载     应用程序。例如,在iOS上,如果是APNS反馈服务     报告APNS令牌无效。

  3. 如果注册令牌过期(例如,Google可能决定刷新注册令牌,或者iOS设备的APNS令牌已过期)。
  4. 如果客户端应用程序已更新但新版本未配置为     收到消息。
  5. 然后,首先您可以检查您的API密钥。在与测试服务器进行检查后,从设备重新生成令牌或注册ID。 here(仅限GCM字段)或here

    要获得帮助,您可以关注this link

    我希望这会对你有所帮助。感谢

    对不起我的英文

答案 1 :(得分:0)

此消息表示移动设备未在GCM Server中注册。 可能存在错误:

  1. 检查设备注册的项目编号。 即regId = gcm.register(PROJECT_NUMBER); 服务器中使用的项目编号和Api密钥应该相同 项目

  2. 检查gcm / send请求中发送到GCM服务器的注册ID。 它应该与移动设备的注册ID匹配(从移动设备获取ID) logs:正确匹配服务器中使用的id)

  3. 如果无效,请尝试使用curl请求发送gcm请求。

    curl --header“授权:key = API_KEY” - 标题内容     键入:“application / json”https://android.googleapis.com/gcm/send -d     “{\”data \“:{\”消息\“:\”欢迎推送通知\“}     \“registration_ids \”:[\“regId \”]}“

  4. 如果curl请求有效,则服务器出现问题,如果没有,请检查移动应用注册步骤。