«

安卓监听sd卡插入和卸载

时间:2024-3-2 18:11     作者:韩俊     分类: Android


第一步

在AndroidManifest.xml增加如下代码

<receiver android:name="com.xxx.receiver.UsbCardLinsenerReceiver" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_EJECT" />

<data android:scheme="file" />
</intent-filter>
</receiver>

增加权限<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

第二部

写一个类,继承BroadcastReceiver
public class UsbCardLinsenerReceiver extends BroadcastReceiver {

String TAG = "usbCardLinsenerReceiver";

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
Log.i(TAG, Intent.ACTION_MEDIA_MOUNTED);
Message msg = new Message();
msg.what = MainActivity.SDMOUNTD_MSG;
MainActivity.handler.sendMessage(msg);//将sd卡插入信息传到主界面

Log.i(TAG, "Starting dataCopyToDBServer");
} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
Log.i(TAG, Intent.ACTION_MEDIA_UNMOUNTED);
}

else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
Log.i(TAG, Intent.ACTION_MEDIA_EJECT);
}

}

}

第三部

在主界面handler就可以进行相应操作了

if (msg.what == SDMOUNTD_MSG) {
Toast.makeText(MainActivity.this, "SD卡已插入", 0).show();
System.out.println("SD卡已插入");
}

标签: android

热门推荐