您的位置:首页 > 移动开发 > Android开发

android 监控usb插拔

2012-01-13 21:48 127 查看
这篇日志是很久以前写的了,看到评论,有朋友说以下方式是监听sdcard插拔,不可以监听usb。大家可以去查看android 3.0之后的api,会看到如下一句话:

ACTION_MEDIA_MOUNTED

External media is present and mounted at its mount point.

在android中external media不只是sdcard,usb存储设备也包含在其中。实际的开发项目中,关于usb插拔,通过以下的代码,都可以很准确的拿到usb的状态。其实对于usb的插拔还有一种判定方式,即StorageListener。貌似是这样写的,但是这个是对于framework级别app使用才可以编译的过。因此对于系统级别的app,这两种方式大家都可以使用,但是对于第三方的app,只能使用广播的方式去监听。

说到sdcard,android中的Enviroment.getExtralStorageState()接口返回的状态值,只能判定sdcard,对于usb不能准确判定其状态。

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.util.Log;

public class UsbStateReceiver extends BaseReceiver {

private static final String TAG = "UsbStateReceiver";
public static final int USB_STATE_MSG = 0x00020;
public static final int USB_STATE_ON = 0x00021;
public static final int USB_STATE_OFF = 0x00022;

public UsbStateReceiver(Context context) {
super(context);
}

@Override
public void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_CHECKING);
filter.addAction(Intent.ACTION_MEDIA_EJECT);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
// 必须要有此行,否则无法收到广播
filter.addDataScheme("file");
this.mContext.registerReceiver(this, filter);
}

@Override
public void unRegisterReceiver() {
this.mContext.unregisterReceiver(this);
}

@Override
public void onReceive(Context arg0, Intent arg1) {
if( this.mHandler == null ){
Log.v(TAG,"usb state change but handler is null");
return;
}

Log.v(TAG,"usb action = "+arg1.getAction());
Message msg = new Message();
msg.what = USB_STATE_MSG;

if( arg1.getAction().equals(Intent.ACTION_MEDIA_MOUNTED ) ||
arg1.getAction().equals(Intent.ACTION_MEDIA_CHECKING)){
msg.arg1 = USB_STATE_ON;
}else{
msg.arg1 = USB_STATE_OFF;
}
this.mHandler.sendMessage(msg);
}

}


对于多个usb的情况,可以拿到每个usb的路径信息:

通过广播传递过来的intent.getData()会得到一个uri,然后uri.getPath()就是插上usb的路径,可以记录下每次插上或者拔出的usb的路径。起到一些动态的控制等等。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: