jeudi 16 juin 2016

How to send a file via bluetooth socket to PC android

I was trying to send a file via bluetooth on my desktop but... nothing happen! I started modifying the code provided in the developer guide and I got a list of bluetooth device; from selecting one of them I want to send a file (nothing important, just a run-time created file with same writing inside). I got till this point:

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmpSocket = null;
        mmDevice = device;

        ParcelUuid[] parcelUuid = device.getUuids();
        MY_UUID = parcelUuid[0].getUuid(); 
        // Get a BluetoothSocket to connect with the given BluetoothDevice

        Class<?> clazz = device.getClass();
        Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
        Method m = null;
        try {
            m = clazz.getMethod("createRfcommSocket", paramTypes);
            Object[] params = new Object[] {Integer.valueOf(2)}; // 2 seems the right choice to me because with it I got no error
            tmpSocket = (BluetoothSocket) m.invoke(device, params);
        } catch (Exception e) {
            notificateUserError();
            e.printStackTrace();
        }
        mmSocket = tmpSocket;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();

        System.out.println(TAG + " ConnectThread: mmSocket = " + mmSocket.toString());
        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
            System.out.println(TAG + " ConnectThread: connessione al socket riuscita");
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            notificateUserError();
            System.out.println(TAG + " ConnectThread: ERRORE di connessione al socket: " + connectException.toString());
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        manageConnectedSocket(mmSocket);
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

The function manageConnectedSocket(...) is the following:

 public void manageConnectedSocket(BluetoothSocket socket){
    System.out.println(TAG + " manageConnectedSocket: ------- funzione di avvio del ConnectedThread  -------");
    ConnectedThread mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();

    try { byte[] buff = "random_string_for_example".getBytes();
        mConnectedThread.write(buff);
        System.out.println(TAG + " ++ Scrittura riuscita!! ++ ");
    } catch(Exception e){ System.out.println(TAG + " WRITING ATTEMPT ERROR: " + e.toString());}

    mConnectedThread.cancel();
}

Finally, the last thread is ConnectedThread, where i try to send my file (sorry for the write() function, but I don't really know how to write it):

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        System.out.println(TAG + " ConnectedThread: ------- Chiamata del costruttore -------");
        notificateUserStart(); //notify user: i'm about to send the file
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = (InputStream) socket.getInputStream();
            tmpOut = (OutputStream) socket.getOutputStream();
        } catch (IOException e) {
            notificateUserError();
            System.out.println(TAG + " ConnectedThread: ERRORE: "+e.toString());
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        System.out.println(TAG + " ConnectedThread: ------- run() -------");
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] mBuffer){
           File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) {
                    root.mkdirs();
                }
                File gpxfile = new File(root, "prova.txt");
                FileWriter writer = new FileWriter(gpxfile);
                writer.append(mBuffer.toString());
                writer.flush();
                writer.close();



                byte[] bytes = new byte[1024];
                InputStream is = mmSocket.getInputStream();
                FileOutputStream fos = new FileOutputStream(gpxfile);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                OutputStreamWriter osw = new OutputStreamWriter(fos);
                int bytesRead = is.read(bytes, 0, bytes.length);
                fos.write(gpxfile);
                fos.close();
                mmSocket.close();

            } catch (Exception e) {System.out.println(TAG + " ConnectedThread: ERRORE: " + e);

            System.out.println(TAG + " ConnectedThread: scritto su outputStream");
            notificateUserDone();
        } catch (Exception e) {
            System.out.println(TAG + " ConnectedThread: ERRORE: " + e.toString());
            notificateUserError();}


    System.out.println(TAG + " ConnectedThread: scritto su outputStream");
    notificateUserDone();
} catch (Exception e) {
    System.out.println(TAG + " ConnectedThread: ERRORE: " + e.toString());
    notificateUserError();}
}

Aucun commentaire:

Enregistrer un commentaire