要判断外接存储设备的状态只能监听“android.intent.action.MEDIA_MOUNTED”等一系列的action。但是项目需求要将外接存储设备细分:USB连接和TF卡等存储卡两类;但系统只提供一个监听,怎么办?你无法判断监听到的是哪一类存储设备。经过思考发现两类存储在系统的路径是不同的可以根据路径是否存在来进一步区分使用的是哪一类存储。
private final BroadcastReceiver broadcastRec = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent){if(intent.getAction().equals("android.intent.action.MEDIA_MOUNTED"))
{
File file=new File("/sdcard/card/");
File file2=new File("/usb/");
if (file.exists() && !isSdcard) { //判断SD卡 插入
isSdcard=true;
Log.d("explorer", "SDcard is useful!");
Toast.makeText(context, R.string.SDCardin, Toast.LENGTH_LONG).show();
btn_sdcard.setEnabled(true);
String strPath="/sdcard/card/";
path_list.AddPathToList(strPath);
updateFileList();
}
else if(file2.exists() && !isUsb) { //判断usb 接入
//
isUsb=true;
Log.d("explorer", "USB is useful!");
Toast.makeText(context, R.string.USBin, Toast.LENGTH_LONG).show();
btn_usb.setEnabled(true);
String strPath="/usb/";
path_list.AddPathToList(strPath);//显示当前路径为usb
updateFileList();//更新文件显示列表
}
}else if(intent.getAction().equals("android.intent.action.MEDIA_REMOVED")
||intent.getAction().equals("android.intent.action.MEDIA_UNMOUNTED")
||intent.getAction().equals("android.intent.action.MEDIA_BAD_REMOVAL")){
File file=new File("/sdcard/card/");
File file2=new File("/usb/");
if (!file.exists() && isSdcard) {
Log.d("explorer", "SDcard is not useful!");
Toast.makeText(context, R.string.SDCardout, Toast.LENGTH_LONG).show();
isSdcard=false;
btn_sdcard.setEnabled(false);
if(path_list.GetCurPath().startsWith("/sdcard/")){
select_list.ClearList();
path_list.AddPathToList("/");
}
}
else if(!file2.exists() && isUsb){
isUsb=false;
Log.d("explorer", "USB is not useful!");
Toast.makeText(context, R.string.USBout, Toast.LENGTH_LONG).show();
btn_usb.setEnabled(false);
if(path_list.GetCurPath().startsWith("/usb/")){
select_list.ClearList();
path_list.AddPathToList("/");
}
}
updateFileList();
}
}
};
以上是广播接收外接存储插拔状态的。还有就是程序启动时判断usb和sdcard是否存在的:
private void initList(){
File file=new File("/sdcard/card/");
if (file.exists()) {
Log.d("explorer", "SDcard is useful!");
isSdcard=true;
btn_sdcard.setEnabled(true);
}else {
// 当前不可用
isSdcard=false;
Log.d("explorer", "SDcard is no use!");
btn_sdcard.setEnabled(false);
}
String strPath="/";
File file2=new File("/usb/");
if (file2.exists()) {
isUsb=true;
btn_usb.setEnabled(true);
if (isSdcard) {
strPath="/sdcard/card/";
}else {
strPath="/usb/";
}
}else {
isUsb=false;
btn_usb.setEnabled(false);
if (isSdcard) {
strPath="/sdcard/card/";
}else {
strPath="/";
}
}
path_list.AddPathToList(strPath);
updateFileList();
}
最近总有人问能否同时识别多个存储设备,我提供个思路,没有试验过:
在android广播插入存储设备时,它的intent中有data,用方法getDataString()获取其中数据你会发现那里面是这个设备的路径,你根据自己的需要截取路径,并根据这个来识别不同的存储设备。
String path=intent.getDataString();
path=path.substring(
11
)+
"/"
;
//path=file:///mnt/sdcard/external_sdcard