如何在Android Studio中与USB闪存盘通信并实现文件备份
解决方案:识别USB闪存盘并获取路径
针对你的锁定平板备份应用场景,以下是无需依赖Android Studio识别USB设备,直接通过代码实现U盘检测、路径获取和文件备份的方案:
一、监听USB挂载广播触发应用唤醒
当用户插入U盘时,系统会发送ACTION_MEDIA_MOUNTED广播,你可以通过广播接收器监听该事件,触发应用唤醒和备份流程:
1. 在Manifest中注册广播接收器
<receiver android:name=".UsbMountReceiver"> <intent-filter> <action android:name="android.intent.action.MEDIA_MOUNTED" /> <data android:scheme="file" /> </intent-filter> </receiver>
2. 实现广播接收器逻辑
public class UsbMountReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) { Uri uri = intent.getData(); if (uri != null) { String usbPath = uri.getPath(); // 唤醒应用主界面并传入U盘路径 Intent launchIntent = new Intent(context, MainActivity.class); launchIntent.putExtra("USB_PATH", usbPath); launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(launchIntent); } } } }
二、获取U盘的准确挂载路径
如果广播获取的路径不准确,可通过以下两种方式获取可移动存储的路径:
方法1:遍历/storage目录筛选可移动存储
public static String getUsbStoragePath() { File storageDir = new File("/storage/"); File[] storageVolumes = storageDir.listFiles(); if (storageVolumes != null) { for (File volume : storageVolumes) { // 排除内部存储和内置SD卡(根据实际设备调整判断逻辑) if (!volume.getName().equals("emulated") && !volume.getName().startsWith("sdcard")) { return volume.getAbsolutePath(); } } } return null; }
方法2:通过StorageManager API(Android 10+)
@RequiresApi(api = Build.VERSION_CODES.Q) public static String getUsbPathUsingStorageManager(Context context) { StorageManager storageManager = context.getSystemService(StorageManager.class); List<StorageVolume> volumes = storageManager.getStorageVolumes(); for (StorageVolume volume : volumes) { // 判断是否为可移动存储且已挂载 if (volume.isRemovable() && volume.getState().equals(Environment.MEDIA_MOUNTED)) { return volume.getDirectory().getAbsolutePath(); } } return null; }
三、实现文件备份逻辑
获取U盘路径后,即可遍历U盘内的视频文件并复制到平板内部存储:
public static void backupFilesFromUsb(String usbPath, String destPath) { File usbDir = new File(usbPath); File destDir = new File(destPath); if (!destDir.exists()) { destDir.mkdirs(); } File[] files = usbDir.listFiles((dir, name) -> name.endsWith(".mp4") || name.endsWith(".mov")); if (files != null) { for (File file : files) { try { File destFile = new File(destDir, file.getName()); // 复制文件(大文件建议用流分块复制) Files.copy(file.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); // 处理复制失败逻辑,比如记录日志 } } } }
四、适配锁定设备的权限与唤醒
- 权限配置:在Manifest中声明必要权限,内部应用可通过adb直接授予系统权限:
adb shell pm grant com.your.package.name android.permission.READ_EXTERNAL_STORAGE adb shell pm grant com.your.package.name android.permission.WRITE_EXTERNAL_STORAGE - 确保应用始终运行:将应用设置为设备所有者,避免被系统杀死:
adb shell dpm set-device-owner com.your.package.name/.DeviceOwnerReceiver
内容的提问来源于stack exchange,提问作者Josh Hunter
相关产品推荐
相关产品推荐

