一、U盘插入、移除
Intent.ACTION_MEDIA_MOUNTED
public static final String ACTION_MEDIA_MOUNTED = "android.intent.action.MEDIA_MOUNTED";
Intent.ACTION_MEDIA_REMOVED
public static final String ACTION_MEDIA_REMOVED = "android.intent.action.MEDIA_REMOVED";
二、U盘文件读写
- 创建广播接收器监听U盘插入及移除(静态注册/动态注册)
- 获取U盘挂载虚拟路径,进行文件读写操作
package com.skyworthdigital.stb.dataprovider;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.io.File;
public class UDiskReceiver extends BroadcastReceiver {
private static final String TAG = "UDiskReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) {
Log.d(TAG, "U盘挂载成功,可以进行读写操作!");
String uDiskDirPath = intent.getData().getPath();
File uDiskDir = new File(uDiskDirPath);
if (uDiskDir.canRead()) {
}
if (uDiskDir.canWrite()) {
}
} else if (Intent.ACTION_MEDIA_REMOVED.equals(intent.getAction())) {
Log.d(TAG, "U盘移除!");
}
}
}
AndroidManifest.xml(静态注册方式)
<receiver android:name=".UDiskReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_REMOVED" />
</intent-filter>
</receiver>
|