GCM无法接收消息

时间:2014-10-24 06:55:07

标签: android google-cloud-messaging

服务器:

var GCM = require('gcm').GCM;

var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var gcm = new GCM(apiKey);

var message = {
    registration_id: 'APA91bEAjoFkJu6KF-UgbLWhB-qbHs6fHeYANpB1XFT4Y8NQbjaOJPQ_PItvBpPF5Zi3thEB6H-_0SXkT7JcYB4yGMOa-jZyeygkxTzy56bbqG8zqLSGouFpSr4F5uGvHzEywH_E3Lko8W57XiCe8F_NJGSvkA0i1jAvXkVvCYTzEyar-OAec10', // required
    collapse_key: 'Collapse key', 
    'data.key1': 'value1',
    'data.key2': 'value2'
};

gcm.send(message, function(err, messageId){
    if (err) {
        console.log("Something has gone wrong!");
    } else {
        console.log("Sent with message ID: ", messageId);
    }
});

客户:

public class GcmMessageHandler extends IntentService {

     String mes;
     private Handler handler;
    public GcmMessageHandler() {
        super("GcmMessageHandler");
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        handler = new Handler();
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

       mes = extras.getString("title");
       showToast();
       Log.i("GCM", "Received : (" +messageType+")  "+extras.getString("title"));

        GcmBroadcastReceiver.completeWakefulIntent(intent);

    }

    public void showToast(){
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(),mes , Toast.LENGTH_LONG).show();
            }
         });

    }
}

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Explicitly specify that GcmMessageHandler will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmMessageHandler.class.getName());

        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

它在昨天工作,但现在它没有在设备上显示任何内容。我不知道有什么不对。我没有改变任何事情。有人可以对此有所了解吗? (我正在使用真实的设备)

修改

它适用于模拟器。

清单:

  

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />     
     

<application

    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" 
    >
    <activity
        android:name="com.hmkcode.android.gcm.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.hmkcode.android.gcm" />
        </intent-filter>
    </receiver>
    <service android:name=".GcmMessageHandler" />

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

1 个答案:

答案 0 :(得分:1)

检查此代码可能对您有帮助:

protected void gcm() {
    // TODO Auto-generated method stub
    GCMHelper gcmhelper = new GCMHelper();
    String gcmtokenAlready = gcmhelper.alreadyregisterGCM();
    if(gcmtokenAlready.length()>0){

        To do code here

    }else{
        gcmhelper.registerGCM();
    }

// GCMHelper

public class GCMHelper {
private final String SENDER_ID = ContextProvider.getContext().getResources().getString(R.string.GCM_ID);
private final Context context = ContextProvider.getContext();
/**
 *  This method is used to register the device with the GCM.
 *
 * @param context the context
 */
public void registerGCM() {
    GCMRegistrar.checkDevice(context);
    GCMRegistrar.checkManifest(context);        
    GCMRegistrar.register(context, SENDER_ID);
}

/**
 * Already register gcm.
 *
 * @param context the context
 * @return the string
 */
public String alreadyregisterGCM() {
    GCMRegistrar.checkDevice(context);
    GCMRegistrar.checkManifest(context);
    return GCMRegistrar.getRegistrationId(context);
}

}

// GCMIntentService
//注意将此类放在应用程序的主包中。

public class GCMIntentService extends GCMBaseIntentService {

/**
 * Instantiates a new GCM intent service.
 */
public GCMIntentService() {
    super(ContextProvider.getContext().getResources().getString(R.string.GCM_ID));
}

/*
 * (non-Javadoc)
 * 
 * @see
 * com.google.android.gcm.GCMBaseIntentService#onError(android.content.Context
 * , java.lang.String)
 */
@Override
protected void onError(Context arg0, String arg1) {
    // TODO Auto-generated method stub
    Log.d(TAG, "Error: " + "sError");
}

/*
 * @see Used when message comes form GCM server. Call your notification
 * class here
 */

/* (non-Javadoc)
 * @see com.google.android.gcm.GCMBaseIntentService#onMessage(android.content.Context, android.content.Intent)
 */
@Override
protected void onMessage(Context context, Intent arg1) {
    // TODO Auto-generated method stub
    String notiData = arg1.getStringExtra("message");
    /**Start BroadCast*/
    Intent mintent = new Intent("PAYMENT_STATUS_MESSAGE");
    mintent.putExtra("PAYMENT_STATUS_MESSAGE", notiData);
    //Send BroadCast
    sendBroadcast(mintent);
    //Generate Notification
    generateNotification(context, notiData);
}

/*
 * (non-Javadoc)
 * 
 * @see
 * com.google.android.gcm.GCMBaseIntentService#onRegistered(android.content
 * .Context, java.lang.String)
 */
@Override
protected void onRegistered(Context context, String token) {
    /** Saving the device token in the Application Class */
    Log.v(TAG, "Registered First Time");

}


/* (non-Javadoc)
 * @see com.google.android.gcm.GCMBaseIntentService#onUnregistered(android.content.Context, java.lang.String)
 */
@Override
protected void onUnregistered(Context arg0, String arg1) { }

/**
 * Issues a notification to inform the user that server has sent a message.
 *
 * @param context the context
 * @param message the message
 */
private void generateNotification(Context context, String message) {
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)   context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher, message, when);         
    String title = "New POC Alert";         
    Intent notificationIntent = new Intent(context, null);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);
}

}

// Mainfest Config

  <!-- GCM Permission -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.VIBRATE" />
 <permission
    android:name="com.sc.candidate.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.sc.candidate.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="vibrate" />

  <!-- For GCM -->
    <receiver
        android:name="com.google.android.gcm.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.sc.candidate" />
        </intent-filter>
    </receiver>

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

*请注意请根据您的应用程序主程序包更改软件包名称。