第一步:需要继承BroadcastReceiver类,覆写其中的onReceive()方法.
class MyBroadcastReceiver extends BroadcastReceiver { //接收到广播会被自动调用 @Override public void onReceive (Context context, Intent intent) { //从Intent中获取action …your code here… } }
application> <activity name=""/> <receiver android:name=".MyBroadcastReceiver"> <!-- intent过滤器,指定可以匹配哪些intent, 一般需要定义action 可以是自定义的也可是系统的 --> <intent-filter> <action android:name="com.app.bc.test"/> </intent-filter> </receiver> </application>
Intent intent = new Intent(“com.app.bc.test”); sendBroadcast(intent);//发送广播事件
//生成一个BroadcastReceiver对象 SMSReceiver smsReceiver = new SMSReceiver(); //生成一个IntentFilter对象 IntentFilter filter = new IntentFilter(); filter.addAction(“android.provider.Telephony.SMS_RECEIVED”); //将BroadcastReceiver对象注册到系统当中 //此处表示该接收器会处理短信事件 TestBC1Activity.this.registerReceiver(smsReceiver, filter);
SMSReceiver smsReceiver = new SMSReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(“android.provider.Telephony.SMS_RECEIVED”); TestBC1Activity.this.registerReceiver(smsReceiver, filter);