我使用下面的代码使用GCM向客户端发送通知。下面的代码写在MainActivity.class中的onClickListener按钮上。通知已成功发送和接收。当我尝试阅读通知信息时,它没有任何
//发送通知代码//
String to = "To_sendor_id";
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action", "SAY_HELLO");
String id = Integer.toString(Integer.parseInt("1"));
try {
gcm.send(to + "@gcm.googleapis.com", id, data);
} catch (IOException e) {
e.printStackTrace();
}
String msg = "Sent message";
Log.d("Sent",msg);
//接收者代码
public class SeriousBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try { String action = intent.getAction();
Log.i("messages","action=" + action);
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
String payload = intent.getStringExtra("my_message");
Log.i("messages", "payload=" + payload);
String action = intent.getStringExtra("my_action");
Log.i("messages", "action=" + action);
Log.i("messages " , intent.getExtras().toString());} finally {
}
}
最后一次Log.i的输出:I / messages:Bundle [{message_type = send_event,event = sent,google.message_id = 1}]
答案 0 :(得分:0)
尝试使用GcmListenerService
代替WakefulBroadcastReceiver
,如下所示:
public class EMSListenerService extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
super.onMessageReceived(from, data);
String my_message = data.getString("my_message");
String my_action = data.getString("my_action");
//do something here
}
}
不要忘记向menifest文件添加服务,如下所示:
<service
android:name=".services.EMSListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>