Android广播篇 系统监听:USB的插拔

Posted 其子昱舟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android广播篇 系统监听:USB的插拔相关的知识,希望对你有一定的参考价值。

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 DemoActivity 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_demo);
        initUsb();
    
 
 
    private void initUsb() 
 
        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) 
                    //"USB连接"
                    Snackbar.make(mUsbConState, "It's Connected", Snackbar.LENGTH_LONG).show();
                 else 
                    Snackbar.make(mUsbConState, "It's No Connected", Snackbar.LENGTH_LONG).show();
                    //"USB断开"
                
            
 
        
    ;
 

以上是关于Android广播篇 系统监听:USB的插拔的主要内容,如果未能解决你的问题,请参考以下文章

Android USB摄像头插拔监听

Android中监控USB的插拔

Android 系统APK-录音机 录音过程不能受外部USB插拔影响

Android TV 中用于以太网 (RJ45) 和 USB 的广播接收器

USB-Blaster的插拔顺序

对于HDMI设备连接状态的监听