我正在开发Android应用程序,我通过GCM获取Json消息,并通过Bundles传递通知。一切正常,我在通知托盘中收到了Bundles消息。
但是我想解析那个JSON Bundle消息,它给了我一个错误:
java.lang.String类型的bundle无法转换为JSONArray
下面给出了通过Bundles的JSON响应以及代码。
Bundle[{summary=Game update 49ers touchdown, android.support.content.wakelockid=1, collapse_key=do_not_collapse, from=931953845039, lastplay=5yd run up the middle}]
服务类:
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private static final String TAG = "PubnubGcm";
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
sendNotification(extras.toString());
try {
JSONArray jsonArray = new JSONArray(extras.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
System.out.println(c.getString("summary"));
/*System.out.println(c.getString(APP_URL));
System.out.println(c.getString(APP_NAME));
System.out.println(c.getString(APP_IMAGE));
System.out.println(c.getString(IMAGE_TYPE));
System.out.println(c.getString(APP_TRACK));*/
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}