Android学习笔记之广播机制(1)
fmms
13年前
<p>广播接收者(BroadcastReceiver)用于异步接收广播Intent,广播Intent的发送是通过调用Context.sendBroadcast()、Context.sendOrderedBroadcast()或者Context.sendStickyBroadcast()来实现的。通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收。</p> <p>广播机制:</p> <p><img title="Android学习笔记之广播机制(1) " border="0" alt="Android学习笔记之广播机制(1) " src="https://simg.open-open.com/show/4b33d6c3ef8169ca8d3a117a168b7e65.jpg" width="500" height="283" /></p> <p>要实现一个广播接收者方法如下:</p> <p><br /> 界面:</p> <pre class="brush:java; toolbar: true; auto-links: false;">package mars.testbc; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class TestActivity extends Activity { /** Called when the activity is first created. */ private Button sendButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.testreceiver); sendButton = (Button)findViewById(R.id.sendButton); sendButton.setOnClickListener(new BroadcastListener()); } class BroadcastListener implements OnClickListener{ public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_EDIT); TestActivity.this.sendBroadcast(intent); } } }</pre> <p><br /> 第一步:要想实现一个广播机制,就必须实现一个类,这个类继承于BroadcastReceiver并重写onReceive()方法。</p> <pre class="brush:java; toolbar: true; auto-links: false;">package mars.testbc; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class TestReceiver extends BroadcastReceiver{ public TestReceiver(){ System.out.println("TestReceiver"); } @Override public void onReceive(Context context, Intent intent) { System.out.println("onReceive"); } }</pre> <p>事件响应的实现应在onReceive方法中实现。</p> <p>第二步:订阅感兴趣的广播Intent,订阅方法有两种:<br /> 第一种:使用代码进行订阅<br /> IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");<br /> IncomingSMSReceiver receiver = new IncomingSMSReceiver();<br /> registerReceiver(receiver, filter);<br /> 第二种:在AndroidManifest.xml文件中的<application>节点里进行注册:<br /> <intent-filter>是一个过滤器。</p> <p>在发送广播过程中,如果某个BroadCastReceiver的Action和这里的Action相符合,则启动,接受广播。</p> <pre class="brush:java; toolbar: true; auto-links: false;"><receiver android:name=".TestReceiver"> <intent-filter> <action android:name="android.intent.action.PICK" /> </intent-filter> </receiver></pre> <p><br /> 生命周期:</p> <p>每次广播到来时,会重新创建BroadcastReceiver对象,并且调用onReceive()方法,执行完以后,该对象即被销毁.</p> <p>当onReceive()方法在10秒内没有执行完毕,Android会认为该程序无响应.所以在</p> <p>BroadcastReceiver里不能做一些比较耗时的操作,否侧会弹出ANR(Application No </p> <p>Response)的对话框.。</p> <p> </p>