广播
1、IP拨号器
原理说明:接收拨打电话的广播,修改广播内携带的电话号码,把修改后的电话号码拨打出去。
定义广播接收者接收打电话广播
public class IpDialerBroadcast extends BroadcastReceiver {
//当广播接收者接收到广播时,此方法会调用
@Override
public void onReceive(Context context, Intent arg1) {
//获取到用户拨打的号码
String oldTel=getResultData();
SharedPreferences spf=context.getSharedPreferences("IpTel", Context.MODE_PRIVATE);
String ipNum=spf.getString("ipNum", "");
//修改广播内的号码
String newTel=oldTel+ipNum;
setResultData(newTel);
}
}
在AndroidManifest.xml文件中定义该广播接收者接收的广播类型
<receiver android:name="com.example.ip_dialer.IpDialerBroadcast">
<intent-filter >
<action android:name="android.intent.action.NEW_OUTGOING_CALL"></action>
</intent-filter>
</receiver>
接收打电话广播需要权限
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
即使广播接收者的进程没有启动,当系统发送的广播可以被该接收者接收时,系统会自动启动该接收者所在的进程
2、监听SD卡状态
广播接收者的定义
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//区分接收到的是哪个广播
String action=intent.getAction();
if("android.intent.action.MEDIA_MOUNTED".equals(action)){
Toast.makeText(context, "SD卡可用", Toast.LENGTH_SHORT).show();
}
else if("android.intent.action.MEDIA_REMOVED".equals(action)){
Toast.makeText(context, "SD卡拨出", Toast.LENGTH_SHORT).show();
}
else if("android.intent.action.MEDIA_UNMOUNTED".equals(action)){
Toast.makeText(context, "SD不可以用", Toast.LENGTH_SHORT).show();
}
}
在AndroidManifest.xml文件中定义广播接收者接收的类型,监听SD卡常见的三种状态,所以广播接收者需要接收三种广播
<receiver android:name="com.lyjs.sdstatueslistener.SdListener">
<intent-filter >
<action android:name="android.intent.action.MEDIA_MOUNTED"/>
<action android:name="android.intent.action.MEDIA_REMOVED"/>
<action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
<data android:scheme="file"/>
</intent-filter>
</receiver>

浙公网安备 33010602011771号