最近需要做个USB设备插拔监听以及U盘数据拷贝的功能,把过程记录下:
一、创建类
BootBroadcastRece
public class BootBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "TAG_BootBroadcastReceiver";
static final String action_boot = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals(action_boot)) {
Log.d(TAG, "设备开机启动中..." );
Thread.sleep(1000);
Intent mainActivityIntent = new Intent(context, WelcomeActivity.class);
mainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
Log.d(TAG, "设备开机启动完成." );
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG,e.getMessage());
}
}
}
二、创建类
UsbReceiver
public class UsbReceiver extends BroadcastReceiver {
private static final String TAG = "TAG_UsbReceiver";
@Override
public void onReceive(Context context, Intent intent) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
switch (intent.getAction()) {
case UsbManager.ACTION_USB_DEVICE_ATTACHED: // 插入USB设备
MyApp.TestToast("插入USB设备");
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED: // 拔出USB设备
MyApp.TestToast("拔出USB设备");
break;
default:
break;
}
}
public static void copyUSBFilesToAndroid(Context context,String sourceDirName, String destDirName, CallbackInit callback) {
List<String> pathList = getUsbPaths(context);
List<File> fileList = new ArrayList<>();
for (String path : pathList) {
// USB挂载点
File sourceDir = new File(path + "/" + sourceDirName);
File destDir = new File(destDirName);
// 确保目标目录存在
if (!destDir.exists()) {
destDir.mkdirs();
}
if (sourceDir.exists() && sourceDir.isDirectory()) {
File[] files = sourceDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".mp4") || file.getName().endsWith(".png") || file.getName().endsWith(".jpg")) {
fileList.add(file);
}
}
for (File file : fileList) {
copyFile(file, new File(destDir, file.getName()));
callback.success(file.getName());
}
}
} else {
callback.fail("源目录不存在或不是目录。");
}
}
}
/**
* 复制文件
*/
private static void copyFile(File sourceFile, File destFile) {
try (InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch (IOException e) {
Log.e(TAG, "文件拷贝出错: " + e.getMessage(), e);
}
}
/**
* 获取所有USB设备挂载点
*/
public static List<String> getUsbPaths(Context cxt) {
List<String> usbPaths = new ArrayList<>();
try {
StorageManager srgMgr = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE);
Class<StorageManager> srgMgrClass = StorageManager.class;
String[] paths = (String[]) srgMgrClass.getMethod("getVolumePaths").invoke(srgMgr);
for (String path : paths) {
Object volumeState = srgMgrClass.getMethod("getVolumeState", String.class).invoke(srgMgr, path);
if (!path.contains("emulated") && Environment.MEDIA_MOUNTED.equals(volumeState))
usbPaths.add(path);
}
} catch (Exception e) {
e.printStackTrace();
}
return usbPaths;
}
}
三、在AndroidManifest.xml添加
android:name=".receiver.UsbReceiver" 这里根据自己的目录地址填写
<receiver android:name=".receiver.UsbReceiver" android:exported="true">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
<data android:scheme="file"/>
</intent-filter>
</receiver>
四、调用
//在U盘中的文件夹名称
String sourceDirName = "video";
//要拷贝的目标地址
String destDirName = Environment.getExternalStorageDirectory().toString() + "/video";
UsbReceiver.copyUSBFilesToAndroid(MyApp.mContext, sourceDirName, destDirName, new CallbackInit() {
@Override
public void success(String fileName) {
// fileName文件名称
//这里可以结合具体的页面做个进度条管理
Log.i(TAG, "复制完成");
}
@Override
public void fail(String error) {
Log.e(TAG, "复制失败:" + error);
}
});