(节选自 Professional android 2 application development)
使用Intent广播事件
-------------------
sendBroadcast()
用于广播的Intent,用来通知系统或应用程序的事件的监听程序,在程序间扩展应用程序模型.
public static final String NE_LIFEFORM_DETECTED = "com.paad.action.NEW_LIFEFORM";
Intent intent=new Intent(NEW_LIFEFORM_DETECTED);
intent.putExtra("lifeformName",lifeformType);
intent.putExtra("longitude",currentLognitude);
intent.putExtra("latitude",currentLatitude);
sendBroadcast(intent);
用Broadcast Receivers监听广播:
------------------------------
Broadcast Receiver 用来监听广播Intent,它需要注册,1,在代码里,2,在manifest里.
当注册Broadcast Receiver时,必须使用一个Intent Filter指定哪一个Intent被监听.
建立Broadcast Receiver,从BroadcastReceiver继承,覆盖onReceive()
public class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context,Intent intent)[
if(intent.getAction().equals(...)){
//...
}
}
}
注意:
1. onReceive必须在5秒内完成,否则就会出现强制关闭对话框。
2. 带有receiver的应用程序不用运行,
典型的Broadcas Receivers将更新内容,打开服务,更新activity ui,或通知使用通知管理器. 5秒钟限制使
主要的处理不在并且也不应当在Broadcast Receiver里进行.
注册:
---------
1. 在Manifest里注册,
2. 用代码注册: 只有运行才能响应广播.
IntentFilter filter = new IntentFilter(NEW_LIFEFORM_DETECTED);
LifeformDetectedBroadcastReceiver r=new LifeformDetectedBroadcastReceiver();
registerReceiver(r,filter);
3. 取消注册: unregisterReceiver(receiver);
保证发送广播Intent的顺序:
--------------------------
使用sendOrderedBroadcast()
发送sticky Intent
sendStickyBroadcast(intent);
删除sticky Intent
removeStickyBroadcast(intent);
本地android broadcast actions:
跟踪设备状态信息用:
ACTION_BOOT_COMPLETED
ACTION_CAMERA_BUTTON
ACTION_DATA_CHANGED ACTION_TIME_CHANGED
ACTION_MEDIA_BUTTON
ACTION_MEDIA_EJECT
示例:
发送广播 (下面的代码和BroadcaseReceiver可以不在同一个Application):
-------------
Intent intent=new Intent();
intent.setAction("xxx.yyy"); // or Intent intent=new Intent("xxx.yyy");
intent.putExtra("info","some string.");
sendBroadcast(intent);
接收广播 (下面的代码所在的Application即使不运行,也可以接收xxx.yyy这个广播):
----------
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context,Intent intent){
if(intent.getAction().equals("xxx.yyy")){
Log.i("BroadcastReceiver","received customed broadcast ..");
String info=intent.getStringExtra("info");
Toast.makeText(context, info, 0).show();
}
}
}
注册:
阅读(662) | 评论(0) | 转发(0) |