BroadcastReceiver能干什么?
首先就说说我们的手机,很肯定的是每个人的手机都会被这样或者那样的手机号码骚扰,这个时候如果我们有个号码黑名单存在我们的手机里(数据库里吧),当接受到来电的时候,可以先匹配数据库,如果匹配到的话,可以做出相应的动作,直接挂断或者静音,不提示就可以了。。。
1,首先有个Activity用来发送:通过BroadcastReceiverActivity.this.sendBroadcast(intent)发送广播
2,然后自然会有个来接受的了,我这里是myBroadcastReceiver,他继承自BroadcastReceiver,里面有个方法:onReceive(),在这个方法里就可以干我们想做的事情了,要是匹配到黑名单可以直接挂掉电话的
实现一个广播的步骤:
1,在一个Activity中使用sendBroadCast ()发送一个广播消息
2,在发送之前当然要有数据(intent封装action)
3,接收,在onReceive()里可以用一个intent来接受,
4,在广播里面最好不要进行比较长的操作,这些可以交给Service或者Activity来处理
sendBroadCast ()--->intent (action)--->onReceive()
3,这还不算,需要在manifest里面配置receiver和相应的intent-filter才可以:
<receiver android:name=".myBroadcastReceiver">
<intent-filter >
<action android:name="com.myBroadCast.action"/>
</intent-filter>
</receiver>
action是我自己定义的:
private String BROADCAST = "com.myBroadCast.action";
Intent intent = new Intent();
intent.setAction(BROADCAST);
好了学习学习DEMO了:BroadcastReceiverActivity.java
public class BroadcastReceiverActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new myOnClickListener());
}
class myOnClickListener implements OnClickListener{
private String BROADCAST = "com.myBroadCast.action";
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(BROADCAST);
BroadcastReceiverActivity.this.sendBroadcast(intent);
Log.v("send", "send Broadcast");
}
}
}
然后是Receiver了:myBroadcastReceiver.java
public class myBroadcastReceiver extends BroadcastReceiver{
public myBroadcastReceiver(){
Log.v("BroadCastReceiver","constuctor Receiver");
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.v("BroadCastReceiver", "recieve something");
}
}
运行下试试吧;
点击这个button:
可以看到基本可以接受了,中间ANCTION配置不对,一直收不到!