2012-03-17 33 views
8

Tengo un problema al enviar archivos de gran tamaño a través de conectores bluetooth. Los archivos más pequeños se transfieren correctamente. Creo que hasta 161280 bytes se transfieren correctamente.Bluetooth file transfer Android

EDIT: Hice algunas pruebas más y reduje la causa. Parece que

outStream.write(mybytearray, 0, mybytearray.length); 

en la parte del código de envío NO está escribiendo más de 161280 bytes. Vi este comportamiento al no cerrar la conexión del zócalo, causando que el read en la parte receptora "bloquee" en 161280 bytes. ¿Qué hay de malo con el flujo de salida de bluetooth aquí? ¿Qué estoy haciendo mal?

EDIT 2: Hacer esto le permite llevarlo a cabo.

for(int i = 0 ; i < mybytearray.length ; i++){ 
    outStream.write(mybytearray[i]); 
} 

código de envío:

try { 
     outStream = mBluetoothSocket.getOutputStream(); 
     Log.d(TAG,"outStream created success!"); 
    } catch (IOException e) { 
     Log.d(TAG, 
       "ON RESUME: Output stream creation failed.", 
       e); 
    } 

    File myFile = new File(file_name); 
    Log.d(TAG,"file /source.pdf created success!"); 

    byte[] mybytearray = new byte[(int)myFile.length()]; 
    Log.d(TAG,"file length() =" + (int)myFile.length()); 

    FileInputStream fis = new FileInputStream(myFile); 
    Log.d(TAG,"fis created"); 

    BufferedInputStream bis = new BufferedInputStream(fis,1272254); 
    Log.d(TAG,"bis created success"); 

    bis.read(mybytearray,0,mybytearray.length); 
    Log.d(TAG,"ALL Bytes read from bis"); 

    outStream.write(mybytearray, 0, mybytearray.length); 
    Log.d(TAG,"BYTES WRITTEN to OUTSTREAM of socket"); 


    outStream.flush(); 
    Log.d(TAG,"bytes flushed"); 
    outStream.close(); 

código de recepción:

// Attach the i/p stream to the socket 
    try { 
     InputStream in = socket.getInputStream(); 
     mIn = in; 
     Log.d(TAG, "input stream acquired"); 

    } catch (IOException e1) { 
     e1.printStackTrace(); 
    } 
    // Create output streams & write to file 
    FileOutputStream fos = new FileOutputStream(
      Environment.getExternalStorageDirectory() 
        + "/copy.pdf"); 
    try { 
     bytesRead = mIn.read(buffer, 0, buffer.length); 
     Log.d(TAG, "bytesRead first time =" + bytesRead); 
     current = bytesRead; 

     do { 
      Log.d(TAG, "do-while -- current: " + current); 
      bytesRead = mIn.read(buffer, current, 
        buffer.length - current); 
      Log.d(TAG, "bytesRead: =" + bytesRead); 

      if (bytesRead >= 0) 
       current += bytesRead; 
     } while (bytesRead > -1); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     Log.d(TAG, "do while end:-- buffer len= " 
       + buffer.length + " current: " + current); 

     fos.write(buffer); 
     Log.d(TAG, "fos.write success! buffer: " 
       + buffer.length + " current: " + current); 

     fos.flush(); 
     fos.close(); 
    } 
} 
socket.close(); 

Logcat:

D/ReceiveService(5761): do-while -- current: 155232 
D/ReceiveService(5761): bytesRead: =1008 
D/ReceiveService(5761): do-while -- current: 156240 
D/ReceiveService(5761): bytesRead: =1008 
D/ReceiveService(5761): do-while -- current: 157248 
D/ReceiveService(5761): bytesRead: =1008 
D/ReceiveService(5761): do-while -- current: 158256 
D/ReceiveService(5761): bytesRead: =1008 
D/ReceiveService(5761): do-while -- current: 159264 
D/ReceiveService(5761): bytesRead: =1008 
D/ReceiveService(5761): do-while -- current: 160272 
D/ReceiveService(5761): bytesRead: =1008 
D/ReceiveService(5761): do-while -- current: 161280 
W/System.err(5761): java.io.IOException: Software caused connection abort 
W/System.err(5761): at android.bluetooth.BluetoothSocket.readNative(Native Method) 
W/System.err(5761): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:307) 
W/System.err(5761): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96) 
W/System.err(5761): at com.bt.server.ReceiveService$AcceptThread.run(ReceiveService.java:141) 

Estoy usando Motorola Milestone. Android 2.1

+0

Pega los registros del dispositivo emisor, incluidas las indicaciones de fecha y hora. Esperanza enviando y recibiendo se está haciendo en un hilo separado. –

+0

Buscar SO para "Cancelación de conexión causada por el software". –

+0

Sí, están en hilos separados. Diferentes teléfonos. El dispositivo de envío envía datos casi instantáneamente. – shiraz

Respuesta

2

Pude resolver este problema enviando pequeños trozos de datos a la extensión bluetooth. Resultó que 8 * 1024 era un buen tamaño de búfer, lo que ayudó a enviar datos sin interrupciones a lo largo de la transmisión y evitar la corrupción de datos en el extremo receptor.

BufferedInputStream bis = new BufferedInputStream(fis, 8 * 1024); 


byte[] buffer = new byte[8192]; 
int len 
while ((len = bis.read(buffer)) != -1) { 
    outStream.write(buffer, 0, len); 
} 
+1

Tengo un problema con enviar un archivo de imagen simple a través de bluetooth usando la muestra de chat bluetooth. En realidad, mi requisito era enviar cualquier archivo oevr bluetooth. Para esto, ¿cómo puedo establecer el tamaño del búfer, cómo recibir pequeños fragmentos de datos y combinarlos en el lado del receptor? ¿Podrías por favor compartirme tu código? –

+0

puede echar un vistazo a este http://stackoverflow.com/questions/16954082/send-text-file-using-bluetooth-sockets-in-android – neerajDorle

+0

Estoy desarrollando una solución que se basa en su enfoque, pero Estoy atascado en outStream.write (mybytearray, 0, mybytearray.length); simplemente no escribirá datos en el flujo de salida.No hay errores, el archivo se crea con un tamaño de 0 bytes y los registros se detienen justo después de bis.read (mybytearray, 0, mybytearray.length). ¿Algunas ideas? –