1)Broadcast Receive是系统级别的事件处理机制。
2)自定义一个广播步骤: 在程序组件中构建要广播的Intent,使用sendBroadcast方法发送出去; 定义一个广播接收器(该接收器继承BroadcastReceiver),覆盖onReceive方法响应事件。最后注册
该广播接收器(可在代码中注册,也可在AndroidManifest.xml配置文件中注册)。
3)在AndroidManifest.xml配置文件中注册广播接收器:
<receiver android:name="MyReceiver"> <intent-filter> <action android:name="com.amaker.ch08.action.MY_ACTION"/> </intent-filter> </receiver> |
在代码中注册,一般在Activity.onResume()方法中使用Context.registerReceiver()方法注册一个广播
接收器,在Activity.onPause()中使用Contenxt.unregisterReceiver()方法来注销一个广播接收器。
注册: IntentFilter filter = new IntentFilter(); MyReceiver r = new Myreceiver(); registerReceiver(r,filter); 注销: unregisterReceiver(r); |
4)BroadcastReceiver组件并没提供可视化的界面来显示广播信息,需要使用Notification和
NotificationManager来实现可视化的信息显示。通过它们可以显示广播信息的内容、图标以及振动等信
息。其使用步骤一般先获得系统级的服务NotificationManager,然后实例化Notification,设置其属性
,通过NotificationManager发出通知即可。
String service = NOTIFICATION_SERVICE; NotificationManager nm = (NotificationManager)getSystemService(service);
Notification n = new Notification(); int icon = n.icon = R.drawable.icon;//设置显示图标,该图标会在状态栏显示 String tickerText = "Test Notification";//设置显示提示信息,该图标也在状态栏显示 long when = System.currnetTImeMillis(); //显示时间 n.icon=icon; n.tickerText = tickerText; n.when = when; //为Notification设置提示音 n.defaults |=Notification.DEFAULT_SOUND; n.sound = Uri.parse("file:///sdcard/sound.mp3"); n.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6"); //为Notification设置振动 n.defaults |= Notification.DEFAULT_VIBRATE; long[] vibrate = {0,50,100,150}; //0ms后震动,震动50ms后停止,再过100ms震动,震动150ms n.vibrate = vibrate;
Intent intent = new Intent(this, MainActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);//获得PendingIntent n.setLatestEventInfo(this, "My Title", "My Content, pi); //设置事件信息 int ID = 1; //标志该通知的ID nm.notify(ID,n); //发出通知 | 5)AlarmManager提供一种系统级的提示服务,允许你安排在将来的某个时间执行一个服务。
AlarmManager对象一般不直接实例化,而是通过Context.getSystemService(Context.ALARM_SERVICE)方
法获得。
AlarmManager的使用步骤: 获得AlarmManager实例; 定义一个PendingIntent发出广播; 调用AlarmManager的方法,设置定时或重复提醒。
final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent = new Intent(); intent.setAction(MY_ACTION); intent.putExtra("msg", "你该起床了!"); final PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0); final long time = System.currentTimeMillis(); |
然后可以调用AlarmManager的方法进行相应操作。
AlarmManager常用属性和方法:
实际遇到的问题:
在定义广播接收类的时候,如果先在所在activity的类中声明这个类,再在后面定义,则程序报错,形如:
public class SplashActivity extends Activity { private BroadcastReceiver connectionReceiver;
.......
connectionReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { } };
至于为什么报错还不清楚。但是网上一般的写法都是
private BroadcastReceiver connectionReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { } };
|