广播接受者创建
1创建广播接收者(买了一台收音机)
2 注册广播接收者
3 添加过滤器(添加频道)
4 添加权限
1创建广播接收者 2注册广播接收者
new -other -broadcastreceiver
添加广播接收者名称例如MyTelephoneReceiver
完成后会产生一个MyTelephoneReceiver的类,并且在AndroidMainifest文件中注册。
MyTelephoneReceiver类
public class MyTelephoneReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
//当接收了广播之后会调用该方法
}
}
AndroidMainifest.xml文件
<receiver
android:name=".MyTelephoneReceiver"
android:enabled="true"
android:exported="true">
</intent-filter>
</receiver>
3 添加过滤器 4 添加权限
想要接受外拨电话的系统广播就要添加外拨电话的过滤器
在AndroidMainifest.xml文件中添加过滤器,并添加权限
<receiver
android:name=".MyTelephoneReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
5 接收到广播后,判断号码并拦截
在MyTelephoneReceiver类中添加代码
public class MyTelephoneReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
//当接收了广播之后会调用该方法
String number=getResultData();//获取号码
Log.i("mybroadcastreceiver","我监听到了有人向外拨打电话"+number);
if(number.equals("13312345678")){
setResultData(null);
}
}
}
网友评论