xamarin android USB

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    private static string ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    protected void USBTest()
    {
        var usbManager = (UsbManager)this.Application.ApplicationContext.GetSystemService(UsbService);
        UsbDevice usbDevice = null;
        foreach (var key in usbManager.DeviceList.Keys)
        {
            var device = usbManager.DeviceList[key];
            var productId = device.ProductId;
            var vendorId = device.VendorId;
            
            // 根据 厂商id 与 设备id 找设备
            if (productId == 8211 && vendorId == 1305)
            {
                usbDevice = device;
                break;
            }
        }

        if (usbDevice == null)
        {
            return "没USB设备!";
        }

        UsbReciever usbReciever = new UsbReciever();
        PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(this, 0, new Intent(
            ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        RegisterReceiver(usbReciever, filter);

        usbManager.RequestPermission(usbDevice, mPermissionIntent);

        /*
        if (!usbManager.HasPermission(usbDevice))
        {
            // 没权限.
            // log "没USB权限!";
        }
        */

        UsbDeviceConnection connection = null;
        // 待发数据
        var buffer = new byte[100];
        try
        {
            connection = usbManager.OpenDevice(usbDevice);
            var endPoint = usbDevice.GetInterface(0).GetEndpoint(0);
            connection.BulkTransfer(endPoint, buffer, buffer.Length, 0);
        }
        catch (Exception ex)
        {
            // log "打印失败," + System.Environment.NewLine + ex.Message + System.Environment.NewLine + ex.StackTrace;
        }
        finally
        {
            if (connection != null)
            {
                connection.Close();
            }
        }
    }
    
    public class UsbReciever : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            String action = intent.Action;
            if (ACTION_USB_PERMISSION.Equals(action))
            {
                lock (this)
                {
                    UsbDevice device = (UsbDevice)intent
                            .GetParcelableExtra(UsbManager.ExtraDevice);

                    if (intent.GetBooleanExtra(
                            UsbManager.ExtraPermissionGranted, false))
                    {
                        if (device != null)
                        {
                            // call method to set up device communication
                        }
                    }
                    else
                    {

                    }
                }
            }
        }
    }
}

posted @ 2021-11-11 17:14  whyfate  阅读(438)  评论(0编辑  收藏  举报