GCM не получил сообщение

Сервер:

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"> 
</uses-permission></uses-permission></uses-permission></uses-permission></uses-sdk>
<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">
 </category></action></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">
 </category></action></intent-filter>
 </receiver>
 <service android:name=".GcmMessageHandler">

 </service></application>
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">
 </category></action></action></intent-filter>
 </receiver>

 </uses-permission></uses-permission></uses-permission></permission></uses-permission></uses-permission></uses-permission></uses-permission>

* Обратите внимание, пожалуйста, измените имя пакета. В соответствии с вашим основным пакетом приложений.

licensed under cc by-sa 3.0 with attribution.