Android 系统监听,监听USB的插拔

效果图:

Android 系统监听,监听USB的插拔_第1张图片

------------------------------------ UsbAccessoryActivity ------------------------------

package com.example.mystudydemo;

import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;

public class UsbAccessoryActivity extends AppCompatActivity {
    PendingIntent mPermissionIntent;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    TextView mUsbConState;

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

        mUsbConState = findViewById(R.id.usb_connect_state_tv);

        initUsbAccessoryWidget();
    }


    private void initUsbAccessoryWidget() {

        mPermissionIntent = PendingIntent.getBroadcast(this, 0,
                new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);

        registerReceiver(mUsbReceiver, filter);

    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
                if (usbCharge) {
                    mUsbConState.setText("USB连接");
                    Snackbar.make(mUsbConState, "It's Connected", Snackbar.LENGTH_LONG).show();
                } else {
                    Snackbar.make(mUsbConState, "It's No Connected", Snackbar.LENGTH_LONG).show();
                    mUsbConState.setText("USB断开");

                }
            }

        }
    };

}

------------------------------------ activity_usb_accessory.xml------------------------------




    

 

你可能感兴趣的:(Android,开发)