首先,代码都是用在项目里的,肯定是可用的。踩过的一些坑一起会写在下面。如果有更好的方法,请告知我。
用广播接收U盘插板的状态,其中插板的判断可以加入 && "/storage/usbdrive".equals(path)"android.intent.action.MEDIA_MOUNTED".equals(action)
其中”/storage/usbdrive”是我修改过的U盘的挂载路径,根据你们自己系统的路径进行修改。
<receiver android:name=".receiver.USBDiskReceiver"><intent-filter android:priority="1000" ><action android:name="android.intent.action.MEDIA_MOUNTED" /><action android:name="android.intent.action.MEDIA_UNMOUNTED" /><data android:scheme="file" /></intent-filter></receiver>
public class USBDiskReceiver extends BroadcastReceiver {public SharedPreferences cacheSp;@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();String path = intent.getData().getPath();if (!TextUtils.isEmpty(path)){if ("android.intent.action.MEDIA_UNMOUNTED".equals(action)) {Log.d("usb",unmounted);}if ("android.intent.action.MEDIA_MOUNTED".equals(action)) {Log.d("usb",mounted);}}}}
用这个方法是没有办法判断U盘是不是已经挂载上了,比如开机前别人就插上了U盘。
提供两个方法判定U盘是不是插入了:
1、提供一个方法,原理是U盘在挂载上的时候会在/proc/mounts里写入U盘的挂载路径,所以我的path传入”/storage/usbdrive”即可判定
public class USBDiskState {private static final String MOUNTS_FILE = "/proc/mounts";public static boolean isMounted(String path) {boolean blnRet = false;String strLine = null;BufferedReader reader = null;try {reader = new BufferedReader(new FileReader(MOUNTS_FILE));while ((strLine = reader.readLine()) != null) {if (strLine.contains(path)) {blnRet = true;break;}}} catch (Exception e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}reader = null;}}return blnRet;}}
2、这是一种更简单粗暴的方法,android在U盘插入的时候会自动生成一个LOST.DIR的文件夹,所以直接判断目录下是否有文件也行file.listFiles().length == 0。
几个方法结合使用,效果更佳。
读U盘内容是没问题,再说说写入U盘权限的问题。
也是两个方法,自用第一条。。
1、因为我们是自研版,所以写出来的应用是系统级别的,添加了一条系统权限就行了
<uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE"/>
2、可以参考
Android实现识别/挂载U盘
如果觉得《Android U盘插拔监听详细版以及U盘写入权限解决办法》对你有帮助,请点赞、收藏,并留下你的观点哦!