Android 通过广播监听USB连接状态的改变

一、原理讲解

      Android通过广播监听USB连接状态的改变的动作在UsbManager.java文件里,为ACTION_USB_STATE。然而在UsbManager中,该常量的注释中包含{@hide},该注释是控制该API是否开放用的。未开发的API意味着google可以随时调整该API的定义或实现方式,而不用保证向下兼容。

      所以尽量避免调用未开发的API,因为一旦系统升级导致其实现方式改变,程序很有可能就直接崩溃了。

注意:

  • 目前仍未发现 ACTION_USB_ACCESSORY_XXX 这种广播
  • 插拔手机与电脑之间的USB线:ACTION_USB_STATE(主要参数是 Boolean connected)
  • 插拔U盘发送的是OTG广播:ACTION_USB_DEVICE_XXX,XXX代表了ATTACH 或 DETACH,这种情况是手机是主,u盘是从,手机给U盘供电。

二、代码如下

1、MyUsbManager.java

package com.example.testapp;

public class MyUsbManager {

	/**
	 * Broadcast Action: A sticky broadcast for USB state change events when in device mode.
	 * This is a sticky broadcast for clients that includes USB connected/disconnected state,
	 * <ul>
	 * <li> {@link #USB_CONNECTED} boolean indicating whether USB is connected or disconnected.
	 * <li> {@link #USB_CONFIGURED} boolean indicating whether USB is configured. currently zero if not configured, one for configured.
	 * <li> {@link #USB_FUNCTION_ADB} boolean extra indicating whether the adb function is enabled
	 * <li> {@link #USB_FUNCTION_RNDIS} boolean extra indicating whether the RNDIS ethernet function is enabled
	 * <li> {@link #USB_FUNCTION_MTP} boolean extra indicating whether the MTP function is enabled
	 * <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the PTP function is enabled
	 * <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the accessory function is enabled
	 * <li> {@link #USB_FUNCTION_AUDIO_SOURCE} boolean extra indicating whether the audio source function is enabled
	 * <li> {@link #USB_FUNCTION_MIDI} boolean extra indicating whether the MIDI function is enabled
	 * </ul>
	 */

	public static final String ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE";
	
	/**
	 * Boolean extra indicating whether USB is connected or disconnected.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
	 */
	public static final String USB_CONNECTED = "connected";

	/**
	 * Boolean extra indicating whether USB is configured.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
	 */
	public static final String USB_CONFIGURED = "configured";

	/**
	 * Boolean extra indicating whether confidential user data, such as photos, should be
	 * made available on the USB connection. This variable will only be set when the user
	 * has explicitly asked for this data to be unlocked.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
	 */
	public static final String USB_DATA_UNLOCKED = "unlocked";

	/**
	 * A placeholder indicating that no USB function is being specified.
	 * Used to distinguish between selecting no function vs. the default function in {@link #setCurrentFunction(String)}.
	 */
	public static final String USB_FUNCTION_NONE = "none";

	/**
	 * Name of the adb USB function.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast
	 */
	public static final String USB_FUNCTION_ADB = "adb";

	/**
	 * Name of the RNDIS ethernet USB function.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast
	 */
	public static final String USB_FUNCTION_RNDIS = "rndis";

	/**
	 * Name of the MTP USB function.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast
	 */
	public static final String USB_FUNCTION_MTP = "mtp";

	/**
	 * Name of the PTP USB function.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast
	 */
	public static final String USB_FUNCTION_PTP = "ptp";

	/**
	 * Name of the audio source USB function.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast
	 */
	public static final String USB_FUNCTION_AUDIO_SOURCE = "audio_source";

	/**
	 * Name of the MIDI USB function.
	 * Used in extras for the {@link #ACTION_USB_STATE} broadcast
	 */
	public static final String USB_FUNCTION_MIDI = "midi";
}

2、UsbActivity.java

package com.example.testapp;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class UsbActivity extends Activity {
	
	private TextView textView;
	private UsbManager usbManager;
	private BroadcastReceiver receiver;
	private IntentFilter intentFilter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ScrollView scrollView = new ScrollView(this);
		LinearLayout linearLayout = new LinearLayout(this);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		textView = new TextView(this);
		scrollView.addView(linearLayout);
		linearLayout.addView(textView);
		
		setContentView(scrollView);
		
		usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		receiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				addText("action : " + action);
				
				if(intent.hasExtra(UsbManager.EXTRA_PERMISSION_GRANTED)) {
					boolean permissionGranted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
					addText("permissionGranted : " + permissionGranted);
				}
				switch(action) {
				case UsbManager.ACTION_USB_ACCESSORY_ATTACHED:
				case UsbManager.ACTION_USB_ACCESSORY_DETACHED:
					//Name of extra for ACTION_USB_ACCESSORY_ATTACHED and ACTION_USB_ACCESSORY_DETACHED broadcasts containing the UsbAccessory object for the accessory.
					UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
					addText(accessory.toString());
					break;
				case UsbManager.ACTION_USB_DEVICE_ATTACHED:
				case UsbManager.ACTION_USB_DEVICE_DETACHED:
					//Name of extra for ACTION_USB_DEVICE_ATTACHED and ACTION_USB_DEVICE_DETACHED broadcasts containing the UsbDevice object for the device.
					UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
					addText(device.toString());
					break;
				case MyUsbManager.ACTION_USB_STATE:
					/*
				     * <li> {@link #USB_CONNECTED} boolean indicating whether USB is connected or disconnected.
				     * <li> {@link #USB_CONFIGURED} boolean indicating whether USB is configured.
				     * currently zero if not configured, one for configured.
				     * <li> {@link #USB_FUNCTION_ADB} boolean extra indicating whether the
				     * adb function is enabled
				     * <li> {@link #USB_FUNCTION_RNDIS} boolean extra indicating whether the
				     * RNDIS ethernet function is enabled
				     * <li> {@link #USB_FUNCTION_MTP} boolean extra indicating whether the
				     * MTP function is enabled
				     * <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the
				     * PTP function is enabled
				     * <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the
				     * accessory function is enabled
				     * <li> {@link #USB_FUNCTION_AUDIO_SOURCE} boolean extra indicating whether the
				     * audio source function is enabled
				     * <li> {@link #USB_FUNCTION_MIDI} boolean extra indicating whether the
				     * MIDI function is enabled
				     * </ul>
				     */
					boolean connected = intent.getBooleanExtra(MyUsbManager.USB_CONNECTED, false);
					addText("connected : " + connected);
					boolean configured = intent.getBooleanExtra(MyUsbManager.USB_CONFIGURED, false);
					addText("configured : " + configured);
					boolean function_adb = intent.getBooleanExtra(MyUsbManager.USB_FUNCTION_ADB, false);
					addText("function_adb : " + function_adb);
					boolean function_rndis = intent.getBooleanExtra(MyUsbManager.USB_FUNCTION_RNDIS, false);
					addText("function_rndis : " + function_rndis);
					boolean function_mtp = intent.getBooleanExtra(MyUsbManager.USB_FUNCTION_MTP, false);
					addText("function_mtp : " + function_mtp);
					boolean function_ptp = intent.getBooleanExtra(MyUsbManager.USB_FUNCTION_PTP, false);
					addText("usb_function_ptp : " + function_ptp);
					boolean function_audio_source = intent.getBooleanExtra(MyUsbManager.USB_FUNCTION_AUDIO_SOURCE, false);
					addText("function_audio_source : " + function_audio_source);
					boolean function_midi = intent.getBooleanExtra(MyUsbManager.USB_FUNCTION_MIDI, false);
					addText("function_midi : " + function_midi);
					break;
				}
			}
		};
		intentFilter = new IntentFilter();
		intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
		intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
		intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		intentFilter.addAction(MyUsbManager.ACTION_USB_STATE);
		registerReceiver(receiver, intentFilter);
		
		boolean hasUsbHost = getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST);
		boolean hasUsbAccessory = getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
		addText("hasUsbHost : " + hasUsbHost);
		addText("hasUsbAccessory : " + hasUsbAccessory);
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}
	
	private void addText(String str) {
		textView.setText(textView.getText().toString() + str + "\n");
	}
}

三、运行截图

这里写图片描述

四、ACTION_USB_DEVICE_ATTACHED 和 ACTION_USB_DEVICE_DETACHED的缺点

广播是去监测U盘插入和拔出的,也就意味着,你只要一插入或者一拔出U盘,就是收到这两个广播。它不会管你的设备有没有准备好,有没有mounted或者unmounted。

因此就需要引入一个新的广播 android.os.storage.extra.VOLUME_STATE。

这个广播就是用来监听Volume状态的。当外置Usb设备在Mounted或者UnMounted的时候则就可以用来做监听 int 类型的 VolumeInfo.EXTRA_VOLUME_STATE。

注意:android.os.storage.extra.VOLUME_STATE 一定要声明读写权限,否则是收不到的。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
可以通过注册广播接收器来监听电池电量和插拔状态变化。具体实现如下: 1. 在 AndroidManifest.xml 文件中添加如下权限: ```xml <uses-permission android:name="android.permission.BATTERY_STATS" /> ``` 2. 创建一个广播接收器 BatteryReceiver,实现电量和插拔状态监听: ```java public class BatteryReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 获取当前电量 int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); // 获取电量最大值 int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); // 计算电量百分比 int batteryPercent = level * 100 / scale; // 获取充电状态 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; // 获取充电方式 int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean isUSBCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean isACCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; // 处理逻辑 if (isCharging) { if (isUSBCharge) { // USB 充电 } else if (isACCharge) { // 交流电充电 } else { // 无线充电 } } else { // 电池供电 } } } ``` 3. 在需要监听电量和插拔状态的页面或服务中注册广播接收器: ```java BatteryReceiver batteryReceiver = new BatteryReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryReceiver, filter); ``` 注意:注册广播接收器后一定要记得在对应的生命周期(如 Activity 的 onDestroy() 方法)中取消注册,避免内存泄漏: ```java unregisterReceiver(batteryReceiver); ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值