接收数据消息
为了监听数据消息,注册一个Broadcast Receiver,来过滤发送的Intent中所包含的动作字符串。
GTalk数据消息和一般的广播Intent处理一样,所以,当它们被Broadcast Receiver接收时,它们没有任何关联的发送者信息。如果你需要这些元数据,你必须在源Intent中通过Bundle来添加,如上一节中代码展示的那样。
接下来的代码框架显示了如何注册一个简单的Broadcast Receiver实现,它能处理前一个列子中发送的Intent:
BroadcastReceiver otaGTalkIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context _context, Intent _intent) {
if (_intent.getAction().equals(ACTION_OTA_ELIMINATE)) {
String sender = _intent.getStringExtra(“sender”);
String target = _intent.getStringExtra(“target”);
String lat = _intent.getStringExtra(“lat”);
String lng = _intent.getStringExtra(“long”);
Location location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(Double.parseDouble(lat));
location.setLongitude(Double.parseDouble(lng));
// TODO: Do something with the data transmitted.
}
}
};
IntentFilter filter = new IntentFilter(ACTION_OTA_ELIMINATE);
registerReceiver(otaGTalkIntentReceiver, filter);