2014-10-24 4 views
0

Сервера: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); 
    } 
} 

Он работал вчера, но теперь он ничего на устройстве не показывает. Я не знаю, что случилось. Я ничего не изменил. Может кто-нибудь об этом знает? (Я работаю на реальном устройстве)

EDIT:

Он работает на эмуляторе.

МАНИФЕСТ:

<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> 

+0

Что вы видите в своих журналах? Вы уже регистрируете несколько вещей на клиенте и на сервере. Предоставляют ли вам какие-либо намеки? Вы получаете исключение? Попробуйте добавить больше журналов и поставить точку останова, чтобы посмотреть, что происходит. Я не думаю, что кто-то может действительно помочь вам быть честным, учитывая количество информации, которую вы предоставили. Вы должны быть намного более ясными и ясными с ошибками, которые вы получаете, чем «Вчера он работал, но теперь он ничего не показывает на устройстве». – kha

+0

@hha Можете ли вы взглянуть на мой манифест ?, может быть, об этом. Я не получал никаких журналов, никаких ошибок. –

ответ

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" /> 

* Примечание Пожалуйста, измените имя пакета Согласно прикладному основному пакету.