android 监控usb插拔

本文介绍了如何在Android中通过监听特定的广播来获取USB存储设备及SD卡的插入和移除状态。不仅可以准确判断SD卡的状态,还能通过URI获取到USB设备的路径信息。

这篇日志是很久以前写的了,看到评论,有朋友说以下方式是监听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不能准确判定其状态。

 

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

      通过广播传递过来的intent.getData()会得到一个uri,然后uri.getPath()就是插上usb的路径,可以记录下每次插上或者拔出的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);   }

}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值