Java 以Usb主机模式从android向连接的Usb存储设备发送数据

Java 以Usb主机模式从android向连接的Usb存储设备发送数据,java,android,usb,serial-communication,Java,Android,Usb,Serial Communication,在我的应用程序中,我使用USB主机模式,该模式提供有关连接的USB大容量存储设备的信息,例如我的用例中的USB闪存驱动器。现在我需要在连接的闪存驱动器上创建一个文件,并在该文件中保存一些数据。到目前为止,我发现正在连接到设备,如下所示 MainActivity.java public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.clas

在我的应用程序中,我使用USB主机模式,该模式提供有关连接的USB大容量存储设备的信息,例如我的用例中的
USB闪存驱动器
。现在我需要在连接的闪存驱动器上创建一个文件,并在该文件中保存一些数据。到目前为止,我发现正在连接到设备,如下所示

MainActivity.java

public class MainActivity extends AppCompatActivity {

        private static final String TAG = MainActivity.class.getSimpleName();
        private Button mCheckForDevice;
        private TextView mDeviceInfo;
        private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
        private PendingIntent mPermissionIntent;
        private UsbManager mUsbManager;
        private UsbDevice mDeviceFound;
        private UsbDeviceConnection mConnection;
        private UsbInterface mUsbInterface = null;
        private UsbEndpoint mInputEndpoint = null;
        private UsbEndpoint mOutputEndpoint = null;

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mCheckForDevice = (Button) findViewById(R.id.check);
            mDeviceInfo = (TextView) findViewById(R.id.deviceInfo);
            count=0;

            mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
            mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

            final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
            Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            registerReceiver(mUsbReceiver, filter);


            while (deviceIterator.hasNext()) {
                final UsbDevice device = deviceIterator.next();
                mDeviceFound = device;
                i += "\n" +
                        "DeviceID: " + device.getDeviceId() + "\n" +
                        "DeviceName: " + device.getDeviceName() + "\n" +
                        "VendorID: " + device.getVendorId() + "\n" +
                        "ProductID: " + device.getProductId() + "\n" +
                        "Serial Number: " + device.getSerialNumber() + "\n";
            }
            mCheckForDevice.setOnClickListener(new View.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onClick(View v) {
                    if(deviceList.size() > 0){
                        checkInfo(mDeviceFound);
                    }else{
                        Toast.makeText(getApplicationContext(), "No device found", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        String i = "";
        private int count ;
        private void checkInfo(UsbDevice device) {
            count++;
            if(count == 1) {
                mUsbManager.requestPermission(device, mPermissionIntent);
                mDeviceInfo.setText(i);

            } else
                Toast.makeText(this, "Already connected", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPause() {
            super.onPause();
            count=0;
            try {
                unregisterReceiver(mUsbReceiver);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
//            Toast.makeText(context, "onReceive", Toast.LENGTH_SHORT).show(); writeToFile("onReceive");
                if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this) {
                        UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            Toast.makeText(context, "Permission Granted", Toast.LENGTH_SHORT).show();
                            connectUsb(device);
                        } else {
                            Log.d(TAG, "permission denied for device " + device);
                            Toast.makeText(context, "permission denied for device" + device, Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        };


        private void connectUsb(UsbDevice device) {
            if(device != null){
                for(int i=0;i<device.getInterfaceCount();i++){
                    mUsbInterface = device.getInterface(i);
                    UsbEndpoint tOut = null;
                    UsbEndpoint tIn = null;
                    int usbEndPointCount = mUsbInterface.getEndpointCount();
                    if(usbEndPointCount >=2){
                        for(int j =0;j<usbEndPointCount;j++){
                            if(mUsbInterface.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK){
                                if(mUsbInterface.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT){
                                    tOut = mUsbInterface.getEndpoint(j);
                                }else if(mUsbInterface.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN){
                                    tIn = mUsbInterface.getEndpoint(j);
                                }
                            }
                        }
                        if(tIn!=null & tOut !=null){
                            mInputEndpoint = tIn;
                            mOutputEndpoint = tOut;
                        }
                    }
                }
                mConnection = mUsbManager.openDevice(device);
                if (mConnection.claimInterface(mUsbInterface, true)) {
                    Toast.makeText(this, "Connected to device", Toast.LENGTH_SHORT).show();

                    String msg = "Hello world";
                    byte[] byteArray = msg.getBytes();
                    int dataTransfered = mConnection.bulkTransfer(mOutputEndpoint,byteArray,byteArray.length, 0);

                    int controlTransfer = mConnection.controlTransfer( UsbConstants.USB_DIR_OUT, 1,0,0,byteArray,byteArray.length,0);
                    Toast.makeText(this, "controlTransfer " +controlTransfer, Toast.LENGTH_SHORT).show();

                } else {
                    Log.i(TAG, "Could not connect!");
                    Toast.makeText(this, "Could not connect", Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(this, "Null", Toast.LENGTH_SHORT).show();
            }
        }
public类MainActivity扩展了AppCompatActivity{
私有静态最终字符串标记=MainActivity.class.getSimpleName();
专用按钮mCheckForDevice;
私有文本视图mDeviceInfo;
私有静态最终字符串操作\u USB\u PERMISSION=“com.android.example.USB\u PERMISSION”;
私人悬而未决的侵权意图;
私人UsbManager mUsbManager;
私人UsbDevice MDeviceFund;
专用UsbDeviceConnection mConnection;
专用UsbInterface mUsbInterface=null;
私有UsbEndpoint mInputEndpoint=null;
专用UsbEndpoint MOUTPENDPOINT=null;
@RequiresApi(api=Build.VERSION\u code.LOLLIPOP)
@凌驾
创建时受保护的void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCheckForDevice=(按钮)findViewById(R.id.check);
mDeviceInfo=(TextView)findViewById(R.id.deviceInfo);
计数=0;
mUsbManager=(UsbManager)getSystemService(Context.USB_服务);
mPermissionIntent=PendingIntent.getBroadcast(this,0,新意图(ACTION\u USB\u权限),0);
final HashMap deviceList=mUsbManager.getDeviceList();
迭代器deviceIterator=deviceList.values().Iterator();
IntentFilter筛选器=新建IntentFilter(操作\u USB\u权限);
寄存器接收器(mUsbReceiver,过滤器);
while(deviceIterator.hasNext()){
最终UsbDevice device=deviceIterator.next();
MDeviceFund=设备;
i+=“\n”+
DeviceID:“+device.getDeviceId()+”\n+
DeviceName:“+device.getDeviceName()+”\n+
VendorID:“+device.getVendorId()+”\n+
ProductID:“+device.getProductId()+”\n+
“序列号:”+设备.getSerialNumber()+“\n”;
}
mCheckForDevice.setOnClickListener(新视图.OnClickListener(){
@RequiresApi(api=Build.VERSION\u code.LOLLIPOP)
@凌驾
公共void onClick(视图v){
如果(deviceList.size()>0){
checkInfo(mdevicefund);
}否则{
Toast.makeText(getApplicationContext(),“未找到设备”,Toast.LENGTH_SHORT.show();
}
}
});
}
字符串i=“”;
私人整数计数;
专用void checkInfo(UsbDevice设备){
计数++;
如果(计数=1){
请求权限(设备、mPermissionIntent);
mDeviceInfo.setText(i);
}否则
Toast.makeText(此“已连接”,Toast.LENGTH_SHORT).show();
}
@凌驾
受保护的void onPause(){
super.onPause();
计数=0;
试一试{
未注册接收人(mUsbReceiver);
}捕获(例外e){
e、 printStackTrace();
}
}
专用最终广播接收器mUsbReceiver=新广播接收器(){
公共void onReceive(上下文、意图){
String action=intent.getAction();
//Toast.makeText(上下文“onReceive”,Toast.LENGTH_SHORT).show();writeToFile(“onReceive”);
if(动作\u USB\u权限等于(动作)){
已同步(此){
UsbDevice设备=(UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_设备);
if(intent.getBooleanExtra(UsbManager.EXTRA_权限_授予,false)){
Toast.makeText(上下文,“已授予权限”,Toast.LENGTH_SHORT).show();
连接USB(设备);
}否则{
Log.d(标签,“设备权限被拒绝”+设备);
Toast.makeText(上下文,“设备的权限被拒绝”+设备,Toast.LENGTH_SHORT).show();
}
}
}
}
};
专用void connectUsb(USB设备){
如果(设备!=null){
对于(int i=0;i=2){

对于(int j=0;j您正在搜索批量端点,这意味着您正在尝试使用BBB进行扇区读/写(请参阅大容量存储类BBB的USB规范)

现在我需要在连接的闪存驱动器上创建一个文件,并在文件中保存一些数据。

使用端点执行扇区读/写,但必须在其上编写文件系统驱动程序(如FAT32或EXT4等)。 文件创建是一个文件系统操作,而不是扇区级读/写

一旦与设备建立连接,是否有办法在连接的设备上创建文件?


您必须使用Android文件系统安装工具,然后使用通用文件API创建文件。

在考虑了所有建议后,我找到了一个可以接受的解决方案。使用UsbHostAPI获取设备相关信息,然后
使用存储访问框架执行归档操作。

但是这些信息存储在连接的设备上的什么位置?我指的是位置?
。您可以通过其他方式查看设备。然后您很快就会发现
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/check"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Search for devices "
        android:textColor="@color/black"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/deviceInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/check"
        android:layout_marginTop="14dp"
        android:textColor="@color/black"
        android:textSize="15sp" />
</RelativeLayout>