我已经完全按照本教程中的说明为Android实现了Google GCM: http://developer.android.com/google/gcm/client.html
发送消息时,BroadcastReceiver捕获Intent并调用GcmIntentService类:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
但是在'sendNotification'方法中(在Service类中),“msg”不是我发送的消息,而是类似于:
Bundle[{android.support.content.wakelockid=1, collapse_key=do_not_collapse, from=153438952475}]
我的服务:
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
public NotificationCompat.Builder builder;
private String TAG = this.getClass().getSimpleName();
public GcmIntentService() {
super("GcmIntentService");
}
@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);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
Log.e(TAG,"GoogleCloudMessaging: error: "+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
Log.e(TAG,"GoogleCloudMessaging: deleted: "+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
sendNotification(extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
GcmResult gcm = GcmResult.getGcm(msg);
GcmResultAsync async = new GcmResultAsync();
async.setInfo(getApplicationContext(),gcm );
async.execute();
}
}
顺便提一下,所有权限都存在。
感谢您阅读!
答案 0 :(得分:3)
Google的例子有点误导,因为它将所有额外内容归为一类。确切地说,如何从捆绑中获取消息取决于您如何发送消息。无论您使用哪种方法,都需要您在客户端中输入 '额外' 。
假设您使用PHP发送,那么您的数据块可能看起来像:
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message,
"moredata" => $morestuff),
'delay_while_idle'=> false,
'time_to_live' => 86400,
'collapse_key'=>"".$randomNum.""
);
其中'message'和'moredata'是我发明的键。要在客户端中提取值,您需要:
if (intent.hasExtra("message")) {
String theMessage = intent.getStringExtra("message");
}
和
if (intent.hasExtra("moredata")) {
String moreData = intent.getStringExtra("moredata");
}
您应该能够翻译此代码以使用您自己的键/值对。