How to receive USB connection status broadcast?

若如初见. 提交于 2019-12-04 10:28:49

Maybe the reason it doesn't work is that since Android 6.0, the default USB mode is Charging and, maybe ACTION_USB_DEVICE_ATTACHED doesn't get fired up when connected in that mode..

Instead, now I have another solution:

String usbStateChangeAction = "android.hardware.usb.action.USB_STATE";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(LOG_TAG, "Received Broadcast: "+action);
        if(action.equalsIgnoreCase(usbStateChangeAction)) { //Check if change in USB state
            if(intent.getExtras().getBoolean("connected")) {
                // USB was connected
            } else {
                // USB was disconnected
            }
        }
    }

That is, the broadcast android.hardware.usb.action.USB_STATE is sent whenever there is a toggle in the USB state.

Unlike android.hardware.usb.action.USB_DEVICE_ATTACHED which is broadcasted only when something like a MTP mode is enable, android.hardware.usb.action.USB_STATE is broadcasted whenever it detects an USB connection that's capable of connecting to a host (say computer), irrespective of its current USB Mode like Charging, MTP or whatever.. (it's called USB config to be more precise)

Here the perfect steps to check that external usb connection occur or not in android activity. Just Follow the steps one by one.

In Android Manifest file:

<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />

Inside your USB checking Activity Tag:

 <activity android:name=".USBEnabled">
        <intent-filter>
            <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        </intent-filter>

        <meta-data
            android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
            android:resource="@xml/device_filter" />

    </activity>

Inside your connectivity checking USBEnabled class :

public class USBEnabled extends AppCompatActivity {
private static final String TAG = "UsbHost";

TextView mDeviceText;
Button mConnectButton;
UsbManager mUsbManager;
UsbDevice mDevice;
PendingIntent mPermissionIntent;

private static final int REQUEST_TYPE = 0x80;
private static final int REQUEST = 0x06;
private static final int REQ_VALUE = 0x200;
private static final int REQ_INDEX = 0x00;
private static final int LENGTH = 64;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_usbenabled);

    mDeviceText = (TextView) findViewById(R.id.text_status);
    mConnectButton = (Button) findViewById(R.id.button_connect);
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
}

@Override
protected void onRestart() {
    super.onRestart();
    recreate();
}

@Override
protected void onResume() {
    super.onResume();

    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);
    updateDeviceList();
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mUsbReceiver);
}

public void onConnectClick(View v) {
    if (mDevice == null) {
        return;
    }
    mUsbManager.requestPermission(mDevice, mPermissionIntent);
}


private static final String ACTION_USB_PERMISSION = "com.android.recipes.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                    && device != null) {

                getDeviceStatus(device);
            } else {
                Log.d(TAG, "permission denied for device " + device);
            }
        }
    }
};


private void getDeviceStatus(UsbDevice device) {
    UsbDeviceConnection connection = mUsbManager.openDevice(device);
    byte[] buffer = new byte[LENGTH];
    connection.controlTransfer(REQUEST_TYPE, REQUEST, REQ_VALUE, REQ_INDEX,
            buffer, LENGTH, 2000);
    connection.close();
}

private void updateDeviceList() {
    HashMap<String, UsbDevice> connectedDevices = mUsbManager
            .getDeviceList();
    if (connectedDevices.isEmpty()) {
        mDevice = null;
        mDeviceText.setText("No Devices Currently Connected");
        mConnectButton.setEnabled(false);
    } else {
        for (UsbDevice device : connectedDevices.values()) {
            mDevice = device;
        }
        mDeviceText.setText("USB Device connected");
        mConnectButton.setEnabled(true);
    }
}}

Inside your class xml file :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
    android:id="@+id/button_connect"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="onConnectClick"
    android:text="Connect" />

<TextView
    android:id="@+id/text_status"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="22dp" />

<TextView
    android:id="@+id/text_data"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="22dp" />
</LinearLayout>

Now create a new resource directory called xml and create new xml file called device_filter.xml with the following code.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device />
</resources>

Debug and run the application, it will show external usb device connectivity status without any error. I hope you will get output for your scenario.

Enjoy!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!