Android入门:播音发送者与广播接收者

Android入门:广播发送者与广播接收者一、广播发送者&广播接收者介绍1.广播接收者广播接收者简单地说就是接

Android入门:广播发送者与广播接收者


一、广播发送者&广播接收者介绍



1.广播接收者


广播接收者简单地说就是接收广播意图的Java类,此Java类继承BroadcastReceiver类,重写:

public void onReceive(Context context,Intent intent),其中intent可以获得传递的数据;

广播意图就是通过Context.sendBroadcast(Intent intent)或Context.sendOrderedBroadcast(Intent intent)发送的意图,通过这个语句,能够广播给所有满足条件的组件,比如intent设置了action="com.xiazdong",则所有在AndroidManifest.xml中设置过<action android:name="com.xiazdong"/>的广播接收者都能够接收到广播;


:onReceive方法必须在10秒内完成,如果没有完成,则抛“Application No Response”当广播接收者onReceive方法需要执行很长时间时,最好将此耗时工作通过Intent发送给Service由Service完成,并且不能使用子线程解决,因为BroadcastReceiver是接收到广播后才创建的,并且生命周期很短,因此子线程可能在没有执行完就已经被杀死了。


Intent intent = new Intent();intent.setAction("...");Context.sendOrderedBroadcast(intent,null);


广播接收者核心代码:




(1)广播发送者:





2.有序广播实例



场景说明:

Android入门:播音发送者与广播接收者


(1)广播发送者


<receiver android:name=".Receiver">      <intent-filter android:priority="1000"><!-- 设置最高优先级 -->         <action android:name="com.xiazdong"/>      </intent-filter> </receiver>