2015-09-18 2 views
1

У меня есть приложение Java отправляет байты над USB на устройство Android, проблема не кажется, читать все байты на Android стороныОтправка данных через USB для Android приложения

Вот как посылаются информация

private static void writeAndRead() throws LibUsbException { 
    String question = "Hello Android I'll be your host today, how are you?"; 

    byte[] questionBuffer = question.getBytes(); 
    ByteBuffer questionData = BufferUtils.allocateByteBuffer(questionBuffer.length); 
    IntBuffer transferred = IntBuffer.allocate(1); 

    int result = 0; 
    System.out.println("Sending question: " + question); 
    System.out.println("Length of buffer: " + questionBuffer.length); 
    result = LibUsb.bulkTransfer(handle, END_POINT_OUT_ACC, questionData, transferred, 5000); 

    if(result < 0) { 
     throw new LibUsbException("Bulk write error!", result); 
    } 
} 

Этот метод кажется завершить не бросать исключение, и он сообщает, что послал длину буфера 51.

на Android стороны я следующее

public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "MainActivity"; 

    private UsbManager manager; 
    private UsbAccessory accessory; 
    private ParcelFileDescriptor accessoryFileDescriptor; 
    private FileInputStream accessoryInput; 
    private FileOutputStream accessoryOutput; 

    private String question = ""; 
    private TextView questionTV; 

    Runnable updateUI = new Runnable() { 
     @Override 
     public void run() { 
      questionTV.append(question); 
     } 
    }; 

    Runnable readQuestionTask = new Runnable() { 
     @Override 
     public void run() { 

      byte[] buffer = new byte[51]; 
      int ret; 

      try { 
       ret = accessoryInput.read(buffer); 
       Log.d(TAG, "Read: " +ret); 
       if (ret == 51) { 
        String msg = new String(buffer); 
        question += " Question: " + msg; 
       } else { 
        question += " Read error"; 
       } 
       Log.d(TAG, question); 

      } catch (IOException e) { 
       Log.e(TAG, "Read error ", e); 
       question += " Read error"; 
      } 

      questionTV.post(updateUI); 
      try { 
       Thread.sleep(100); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 

     } 
    }; 


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

     questionTV = (TextView) findViewById(R.id.hello_world); 
     questionTV.setMovementMethod(new ScrollingMovementMethod()); 

     Intent intent = getIntent(); 
     manager = (UsbManager) getSystemService(Context.USB_SERVICE); 
     accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); 
     if(accessory == null) { 
      questionTV.append("Not started by the accessory itself" 
        + System.getProperty("line.separator")); 
      return; 
     } 

     Log.d(TAG, accessory.toString()); 
     accessoryFileDescriptor = manager.openAccessory(accessory); 
     Log.d(TAG, "File Descriptor " +accessoryFileDescriptor.toString()); 
     if (accessoryFileDescriptor != null) { 
      FileDescriptor fd = accessoryFileDescriptor.getFileDescriptor(); 
      accessoryInput = new FileInputStream(fd); 
      accessoryOutput = new FileOutputStream(fd); 
     } 
     new Thread(readQuestionTask).start(); 

    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

} 

Следующий фрагмент кода

 try { 
      ret = accessoryInput.read(buffer); 
      Log.d(TAG, "Read: " +ret); 
      if (ret == 51) { 
       String msg = new String(buffer); 
       question += " Question: " + msg; 
      } else { 
       question += " Read error"; 
      } 
      Log.d(TAG, question); 

     } catch (IOException e) { 
      Log.e(TAG, "Read error ", e); 
      question += " Read error"; 
     } 

Reports в консоли содержимое question строки как быть

09-18 09:58:30.084 26198-26221/com.example.paulstatham.testusb D/MainActivity﹕ Read: 51 
09-18 09:58:30.084 26198-26221/com.example.paulstatham.testusb D/MainActivity﹕ Question: ������������������������������������������������������������������������������������������������������ 

Сама деятельность просто показывает, как "Вопрос:"

Я предполагаю, что эти странные символы являются только значением байта по умолчанию, когда сначала был назначен массив байтов byte[] buffer = new byte[51];

К сожалению, характер приложения затрудняет его отладку.

Все советы, почему ret = accessoryInput.read(buffer); ничего не читает?

EDIT: Фактически он что-то читает, поскольку accessoryInput.read(buffer); будет блокироваться до тех пор, пока не будет введен вход, и он не блокирует.

Так почему же byte[] заполнен мусором?

Я думал, что это может что-то делать с тем фактом, что ByteBuffer отправляется

LibUsb.bulkTransfer(handle, END_POINT_OUT_ACC, questionData, transferred, 5000); 

Но я попытался превращающего его в Android

ByteBuffer buf = ByteBuffer.wrap(buffer); 
String msg = new String(buf.array()); 
question += " Question: " + msg; 

И это дало мне одни и те же символы для мусора

ответ

0

Еще раз, отвечая на мой вопрос, вопрос был здесь

String question = "Hello Android I'll be your host today, how are you?"; 

byte[] questionBuffer = question.getBytes(); 
ByteBuffer questionData = BufferUtils.allocateByteBuffer(questionBuffer.length); 
IntBuffer transferred = IntBuffer.allocate(1); 

Я никогда не положил byte[] в к ByteBuffer

questionData.put(questionBuffer) решает эту проблему!

+0

не могли бы вы поделиться со мной всем кодом, у меня тоже есть такое же приложение. Я новичок в android, поэтому буду благодарен за вашу помощь. Я хочу понять, как работает мой адрес электронной почты: [email protected] –