首先配置权限
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
对于整个程序而言设置过滤器
<receiver android:name=".PhoneStateReceiver">
<intent-filter android:priority="1000"><!-- 设置优先级以防被别的程序截取 -->
<!-- <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> -->
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="com.high.PmRestart"/>
<category android:name="android.intent.category.HOME"/>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.MEDIA_MOUNTED"/><!--SD卡插入 -->
<action android:name="android.intent.action.MEDIA_EJECT" /><!-- SD卡拔出 -->
<!-- <action android:name="android.intent.action.ACTION_MEDIA_UNMOUNTED" />sd卡存在,但还没有挂载
<action android:name="android.intent.action.ACTION_MEDIA_REMOVED" />sd卡被移除
<action android:name="android.intent.action.ACTION_MEDIA_SHARED" />sd卡作为 USB大容量存储被共享,挂载被解除
<action android:name="android.intent.action.ACTION_MEDIA_BAD_REMOVAL" />sd卡已经从sd卡插槽拔出,但是挂载点还没解除
<action android:name="android.intent.action.ACTION_MEDIA_SCANNER_STARTED" />开始扫描
<action android:name="android.intent.action.ACTION_MEDIA_SCANNER_FINISHED" />扫描完成 -->
<data android:scheme="file"/><!-- 没有一行代码就无法监听SD卡 -->
</intent-filter>
</receiver>
最后就可以在广播中干我们最想做的事……
@Override
public void onReceive(Context context, Intent intent) {
try {
share.CreateFileWrite("PhoneStateReceiver:Action " + intent.getAction());
if (intent.getAction().equals(ACTION)) {
//开机自启动
share.CreateFileWrite("PhoneStateReceiver:BOOT_COMPLETED");
//Intent activityIntent = new Intent(context, MobileAudio.class);
// 要想在Service中启动Activity,必须设置如下标志
//activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(activityIntent);
//SelectTable(context);
start(context);
} else if (intent.getAction().equals(ACTION2)){
share.CreateFileWrite("PhoneStateReceiver:AUTO_START");
start(context);
} else if (intent.getAction().equals(Intent.ACTION_MEDIA_EJECT)){
//SD卡拔出
share.CreateFileWrite("PhoneStateReceiver:Intent.ACTION_MEDIA_EJECT");
//start(context);
} else if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)){
//SD卡可读
share.CreateFileWrite("PhoneStateReceiver:Intent.ACTION_MEDIA_MOUNTED");
start(context);
}
} catch (Exception e) {
share.CreateFileWrite(e.toString());
}
}