Android5.0如何监听USB插拔

USB插拔在3.0之前需要自己写,USBManager并没有提供接口,3.0之后可以直接调用USBManager的USB各种Aciton




     	UsbManager.ACTION_USB_ACCESSORY_ATTACHED
     	UsbManager.ACTION_USB_ACCESSORY_DETACHED
     	UsbManager.ACTION_USB_DEVICE_ATTACHED
     	UsbManager.ACTION_USB_DEVICE_DETACHED



自定义广播使用这些Action,但可以发现都不起作用


继续查看USBManager.java

发现有一个Aciton  

    public static final String ACTION_USB_STATE =
            "android.hardware.usb.action.USB_STATE";

但是USBManager不可以点出来直接调用只能用他的String "android.hardware.usb.action.USB_STATE";

测试发现这个action生效,但不是即时生效的,因为这个action其实是监听USB是否connected,当USB connected时才会生效,有时候你插入了USB,但没connected,这个广播不会发出


有没有一种即插就生效的呢

查看系统源码

监听USB的广播使用的是电池电量变化Action

Intent.ACTION_BATTERY_CHANGE

当使用这个action时 即插就生效,并会持续监听

还有一种是是否是USB充电,只能是判断一下

        int chargePlug = arg1.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
       boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;



下面是例子

package com.android.t8dialer;

import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private final static String ACTION ="android.hardware.usb.action.USB_STATE";


	  
	private	BroadcastReceiver usBroadcastReceiver = new BroadcastReceiver() {



			@Override


			public void onReceive(Context context, Intent intent) {



			// TODO Auto-generated method stub



			String action = intent.getAction();

     	if (action.equals(ACTION)) {


		     	boolean connected = intent.getExtras().getBoolean("connected");

			  if (connected) {
    

				Toast.makeText(MainActivity.this,"is connected", Toast.LENGTH_SHORT).show();

			     } else {

			

				Toast.makeText(MainActivity.this,"no connected", Toast.LENGTH_SHORT).show();


			     }



			  }
			
			
			else if(action.equals(UsbManager.ACTION_USB_ACCESSORY_ATTACHED)){
		
				Toast.makeText(MainActivity.this,"USB_ACCESSORY", Toast.LENGTH_SHORT).show();
				
			}

			else if(action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)){
		
				Toast.makeText(MainActivity.this,"USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT).show();
				
			}
			else if(action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)){
		
				Toast.makeText(MainActivity.this,"DEVICE_DETACHED", Toast.LENGTH_SHORT).show();
				
			}
			else if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
	
				Toast.makeText(MainActivity.this,"BATTERY_CHANGED", Toast.LENGTH_SHORT).show();
				
			}



			}
			

			
			


			};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		IntentFilter filter = new IntentFilter();


		filter.addAction(ACTION);
		filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		filter.addAction(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(usBroadcastReceiver, filter);

		
		


	}
	
	

	

	

}

测试发现 Intent.ACTION_BATTERY_CHANGED更快,"android.hardware.usb.action.USB_STATE"更准确的监听USB是否 connected

我的解决方案是 监听ntent.ACTION_BATTERY_CHANGED广播然后在判断 并且当前充电的状态是USB,那么 判断USB插入了,那么拔出呢 没想出来

最后一定要加上在AndroidManifest.xml配置文件里

 android:minSdkVersion="12"



下面是USBManager.java

/*
* Copyright (C) 2014 MediaTek Inc.
* Modification based on code covered by the mentioned copyright
* and/or permission notice(s).
*/
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package android.hardware.usb;

import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.util.Log;

import java.util.HashMap;

/**
 * This class allows you to access the state of USB and communicate with USB devices.
 * Currently only host mode is supported in the public API.
 *
 * 

You can obtain an instance of this class by calling * {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}. * * {@samplecode * UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);} * *

*

Developer Guides

*

For more information about communicating with USB hardware, read the * USB developer guide.

*
*/ public class UsbManager { private static final String TAG = "UsbManager"; /** * 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, *
    *
  • {@link #USB_CONNECTED} boolean indicating whether USB is connected or disconnected. *
  • {@link #USB_CONFIGURED} boolean indicating whether USB is configured. * currently zero if not configured, one for configured. *
  • {@link #USB_FUNCTION_MASS_STORAGE} boolean extra indicating whether the * mass storage function is enabled *
  • {@link #USB_FUNCTION_ADB} boolean extra indicating whether the * adb function is enabled *
  • {@link #USB_FUNCTION_RNDIS} boolean extra indicating whether the * RNDIS ethernet function is enabled *
  • {@link #USB_FUNCTION_MTP} boolean extra indicating whether the * MTP function is enabled *
  • {@link #USB_FUNCTION_PTP} boolean extra indicating whether the * PTP function is enabled *
  • {@link #USB_FUNCTION_PTP} boolean extra indicating whether the * accessory function is enabled *
  • {@link #USB_FUNCTION_AUDIO_SOURCE} boolean extra indicating whether the * audio source function is enabled *
* * {@hide} */ public static final String ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE"; /** * Broadcast Action: A broadcast for USB device attached event. * * This intent is sent when a USB device is attached to the USB bus when in host mode. *
    *
  • {@link #EXTRA_DEVICE} containing the {@link android.hardware.usb.UsbDevice} * for the attached device *
*/ public static final String ACTION_USB_DEVICE_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED"; /** * Broadcast Action: A broadcast for USB device detached event. * * This intent is sent when a USB device is detached from the USB bus when in host mode. *
    *
  • {@link #EXTRA_DEVICE} containing the {@link android.hardware.usb.UsbDevice} * for the detached device *
*/ public static final String ACTION_USB_DEVICE_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED"; /** * Broadcast Action: A broadcast for USB accessory attached event. * * This intent is sent when a USB accessory is attached. *
    *
  • {@link #EXTRA_ACCESSORY} containing the {@link android.hardware.usb.UsbAccessory} * for the attached accessory *
*/ public static final String ACTION_USB_ACCESSORY_ATTACHED = "android.hardware.usb.action.USB_ACCESSORY_ATTACHED"; /** * Broadcast Action: A broadcast for USB accessory detached event. * * This intent is sent when a USB accessory is detached. *
    *
  • {@link #EXTRA_ACCESSORY} containing the {@link UsbAccessory} * for the attached accessory that was detached *
*/ public static final String ACTION_USB_ACCESSORY_DETACHED = "android.hardware.usb.action.USB_ACCESSORY_DETACHED"; /** * Boolean extra indicating whether USB is connected or disconnected. * Used in extras for the {@link #ACTION_USB_STATE} broadcast. * * {@hide} */ public static final String USB_CONNECTED = "connected"; /** * Boolean extra indicating whether USB is configured. * Used in extras for the {@link #ACTION_USB_STATE} broadcast. * * {@hide} */ public static final String USB_CONFIGURED = "configured"; /** * Name of the USB mass storage USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ public static final String USB_FUNCTION_MASS_STORAGE = "mass_storage"; /** * Name of the adb USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ 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 * * {@hide} */ public static final String USB_FUNCTION_RNDIS = "rndis"; /** * Name of the MTP USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ public static final String USB_FUNCTION_MTP = "mtp"; /** * Name of the PTP USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ public static final String USB_FUNCTION_PTP = "ptp"; /** * Name of the ACM USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * @internal * {@hide} */ public static final String USB_FUNCTION_ACM = "acm"; /** * Name of the ACM USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ public static final String USB_FUNCTION_DUAL_ACM = "dual_acm"; /** * Name of the USB Charging function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * @internal * {@hide} */ public static final String USB_FUNCTION_CHARGING_ONLY = "charging"; /** * Name of the USB BICR function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * @internal * {@hide} */ public static final String USB_FUNCTION_BICR = "bicr"; /** * Name of the audio source USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ public static final String USB_FUNCTION_AUDIO_SOURCE = "audio_source"; /** * Name of the Accessory USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ public static final String USB_FUNCTION_ACCESSORY = "accessory"; /** * Name of the EEM ethernet USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * @internal * {@hide} */ public static final String USB_FUNCTION_EEM = "eem"; //VIA-START VIA USB /** * Name of the VIA_CDROM USB function. * Used in extras for the {@link #ACTION_USB_STATE} broadcast * * {@hide} */ public static final String USB_FUNCTION_VIA_CDROM = "via_cdrom_storage"; //VIA-END VIA USB /** * Name of extra for {@link #ACTION_USB_DEVICE_ATTACHED} and * {@link #ACTION_USB_DEVICE_DETACHED} broadcasts * containing the UsbDevice object for the device. */ public static final String EXTRA_DEVICE = "device"; /** * Name of extra for {@link #ACTION_USB_ACCESSORY_ATTACHED} and * {@link #ACTION_USB_ACCESSORY_DETACHED} broadcasts * containing the UsbAccessory object for the accessory. */ public static final String EXTRA_ACCESSORY = "accessory"; /** * Name of extra added to the {@link android.app.PendingIntent} * passed into {@link #requestPermission(UsbDevice, PendingIntent)} * or {@link #requestPermission(UsbAccessory, PendingIntent)} * containing a boolean value indicating whether the user granted permission or not. */ public static final String EXTRA_PERMISSION_GRANTED = "permission"; private final Context mContext; private final IUsbManager mService; /** * {@hide} */ public UsbManager(Context context, IUsbManager service) { mContext = context; mService = service; } /** * Returns a HashMap containing all USB devices currently attached. * USB device name is the key for the returned HashMap. * The result will be empty if no devices are attached, or if * USB host mode is inactive or unsupported. * * @return HashMap containing all connected USB devices. */ public HashMap getDeviceList() { Bundle bundle = new Bundle(); try { mService.getDeviceList(bundle); HashMap result = new HashMap(); for (String name : bundle.keySet()) { result.put(name, (UsbDevice)bundle.get(name)); } return result; } catch (RemoteException e) { Log.e(TAG, "RemoteException in getDeviceList", e); return null; } } /** * Opens the device so it can be used to send and receive * data using {@link android.hardware.usb.UsbRequest}. * * @param device the device to open * @return a {@link UsbDeviceConnection}, or {@code null} if open failed */ public UsbDeviceConnection openDevice(UsbDevice device) { try { String deviceName = device.getDeviceName(); ParcelFileDescriptor pfd = mService.openDevice(deviceName); if (pfd != null) { UsbDeviceConnection connection = new UsbDeviceConnection(device); boolean result = connection.open(deviceName, pfd); pfd.close(); if (result) { return connection; } } } catch (Exception e) { Log.e(TAG, "exception in UsbManager.openDevice", e); } return null; } /** * Returns a list of currently attached USB accessories. * (in the current implementation there can be at most one) * * @return list of USB accessories, or null if none are attached. */ public UsbAccessory[] getAccessoryList() { try { UsbAccessory accessory = mService.getCurrentAccessory(); if (accessory == null) { return null; } else { return new UsbAccessory[] { accessory }; } } catch (RemoteException e) { Log.e(TAG, "RemoteException in getAccessoryList", e); return null; } } /** * Opens a file descriptor for reading and writing data to the USB accessory. * * @param accessory the USB accessory to open * @return file descriptor, or null if the accessor could not be opened. */ public ParcelFileDescriptor openAccessory(UsbAccessory accessory) { try { return mService.openAccessory(accessory); } catch (RemoteException e) { Log.e(TAG, "RemoteException in openAccessory", e); return null; } } /** * Returns true if the caller has permission to access the device. * Permission might have been granted temporarily via * {@link #requestPermission(UsbDevice, PendingIntent)} or * by the user choosing the caller as the default application for the device. * * @param device to check permissions for * @return true if caller has permission */ public boolean hasPermission(UsbDevice device) { try { return mService.hasDevicePermission(device); } catch (RemoteException e) { Log.e(TAG, "RemoteException in hasPermission", e); return false; } } /** * Returns true if the caller has permission to access the accessory. * Permission might have been granted temporarily via * {@link #requestPermission(UsbAccessory, PendingIntent)} or * by the user choosing the caller as the default application for the accessory. * * @param accessory to check permissions for * @return true if caller has permission */ public boolean hasPermission(UsbAccessory accessory) { try { return mService.hasAccessoryPermission(accessory); } catch (RemoteException e) { Log.e(TAG, "RemoteException in hasPermission", e); return false; } } /** * Requests temporary permission for the given package to access the device. * This may result in a system dialog being displayed to the user * if permission had not already been granted. * Success or failure is returned via the {@link android.app.PendingIntent} pi. * If successful, this grants the caller permission to access the device only * until the device is disconnected. * * The following extras will be added to pi: *
    *
  • {@link #EXTRA_DEVICE} containing the device passed into this call *
  • {@link #EXTRA_PERMISSION_GRANTED} containing boolean indicating whether * permission was granted by the user *
* * @param device to request permissions for * @param pi PendingIntent for returning result */ public void requestPermission(UsbDevice device, PendingIntent pi) { try { mService.requestDevicePermission(device, mContext.getPackageName(), pi); } catch (RemoteException e) { Log.e(TAG, "RemoteException in requestPermission", e); } } /** * Requests temporary permission for the given package to access the accessory. * This may result in a system dialog being displayed to the user * if permission had not already been granted. * Success or failure is returned via the {@link android.app.PendingIntent} pi. * If successful, this grants the caller permission to access the accessory only * until the device is disconnected. * * The following extras will be added to pi: *
    *
  • {@link #EXTRA_ACCESSORY} containing the accessory passed into this call *
  • {@link #EXTRA_PERMISSION_GRANTED} containing boolean indicating whether * permission was granted by the user *
* * @param accessory to request permissions for * @param pi PendingIntent for returning result */ public void requestPermission(UsbAccessory accessory, PendingIntent pi) { try { mService.requestAccessoryPermission(accessory, mContext.getPackageName(), pi); } catch (RemoteException e) { Log.e(TAG, "RemoteException in requestPermission", e); } } private static boolean propertyContainsFunction(String property, String function) { String functions = SystemProperties.get(property, ""); int index = functions.indexOf(function); if (index < 0) return false; if (index > 0 && functions.charAt(index - 1) != ',') return false; int charAfter = index + function.length(); if (charAfter < functions.length() && functions.charAt(charAfter) != ',') return false; return true; } /** * Returns true if the specified USB function is currently enabled. * * @param function name of the USB function * @return true if the USB function is enabled. * * {@hide} */ public boolean isFunctionEnabled(String function) { return propertyContainsFunction("sys.usb.config", function); } /** * Returns the current default USB function. * * @return name of the default function. * * {@hide} */ public String getDefaultFunction() { String functions = SystemProperties.get("persist.sys.usb.config", ""); int commaIndex = functions.indexOf(','); if (commaIndex > 0) { return functions.substring(0, commaIndex); } else { return functions; } } /** * Sets the current USB function. * If function is null, then the current function is set to the default function. * * @param function name of the USB function, or null to restore the default function * @param makeDefault true if the function should be set as the new default function * * {@hide} */ public void setCurrentFunction(String function, boolean makeDefault) { try { mService.setCurrentFunction(function, makeDefault); } catch (RemoteException e) { Log.e(TAG, "RemoteException in setCurrentFunction", e); } } /** * Returns the current USB state. * * @return current USB state. * * @internal * {@hide} */ public int getCurrentState() { try { boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1"); if (!isEmulator) return mService.getCurrentState(); else return 0; } catch (RemoteException e) { Log.e(TAG, "RemoteException in getCurrentState", e); } return 0; } /** * Sets the file path for USB mass storage backing file. * * @param path backing file path * * {@hide} */ public void setMassStorageBackingFile(String path) { try { mService.setMassStorageBackingFile(path); } catch (RemoteException e) { Log.e(TAG, "RemoteException in setDefaultFunction", e); } } }


你可能感兴趣的:(Android5.0如何监听USB插拔)