android开发 关于BroadCast Receiver
BroadCast Receiver是android常用的技术之一
用于发送/广播Intent消息
下面就介绍两种简单的使用方法
一. 通过组合的方式
在类中定义一个BroadcastReceiver对象
重写onReceive 这样就能接收到广播
这个可以放到一般的Activity类中
首先注册IntentFilter 指定要接收的消息
//注册一个IntentFilter IntentFilter intentFilter = new IntentFilter( "PlayHandler.Broadcast" ); registerReceiver( myBroadcastReceiver, intentFilter);
然后定义BroadcastReceiver对象 接收消息
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //接收广播 // 注意 这里是主线程上 System.out.println(" thread id :"+Thread.currentThread().getId()); System.out.println("PlayHandler.Broadcast onReceived!!" ); } };
这样一个接收消息处理的对象就完成了
下面来发送一条消息
//使用sendBroadcast 发送广播 Intent intent = new Intent( "PlayHandler.Broadcast" ); sendBroadcast(intent); System.out.println("PlayHandler.Broadcast" );
二. 注册XML
和前面一种方法不同的是 这里使用Manifest来注册了receiver
需要继承BroadcastReceiver类
首先在Manifest中注册
<receiver android:exported="false" android:name="com.example.codetest_1.PlayBroadcastReceiver" > <intent-filter> <action android:name = "PlayBroadcastReceiver.Broadcast" /> </intent-filter> </receiver>
声明一个BroadcastReceiver派生类
public class PlayBroadcastReceiver extends BroadcastReceiver { public static final String BROADCAST_ACTION = "PlayBroadcastReceiver.Broadcast" ; @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub System.out.println("PlayBroadcastReceiver.Broadcast onReceived!!" ); } }
消息的发送和第一种方法一样
intent = new Intent(); intent.setAction(PlayBroadcastReceiver.BROADCAST_ACTION); sendBroadcast(intent); System.out.println("PlayBroadcastReceiver.Broadcast send");
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。