Последовательная передача растрового изображения через Bluetooth генерирует несколько inputstream.read()

Я разрабатываю приложение для Android, которое передает изображения с одного устройства на другое. Полученное изображение будет храниться в локальной базе данных моего приложения, созданной с помощью SQLite. Для достижения своих целей я преобразовал растровое изображение в byte[] и передал его на другое устройство с помощью outputStream. Я добился успеха в приведенной выше реализации, но не смог передать второе изображение на подключенное устройство.

Проблема, с которой я столкнулся, заключается в следующем: первая передача любого изображения успешна с одиночным outputStream.write() и одиночным inputStream.read(), но < strong>последовательная передача того же/другого изображения завершается ошибкой с одним вызовом метода outputStream.Write() и несколько inoutStream.read().

Я хотел бы знать ошибку в реализации входных и выходных потоков в моем коде.

Заранее спасибо.

Код потока для запуска соединения выглядит следующим образом:

        private class StartConnectionThread extends Thread{
    private final BluetoothSocket bluetoothSocket;
    private final BluetoothDevice bluetoothDevice;
    public StartConnectionThread(BluetoothDevice device){
        BluetoothSocket tempBluetoothSocket=null;
        bluetoothDevice=device;
        try
        {
            System.out.println(uuid);
            tempBluetoothSocket=device.createRfcommSocketToServiceRecord(uuid);
        }
        catch(IOException ioException)
        {

        } 
        bluetoothSocket=tempBluetoothSocket;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("StartConnectionThread Run");
        bluetoothAdapter.cancelDiscovery();
        try
        {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            bluetoothSocket.connect();

        }
        catch(IOException ioException)
        {
            System.out.println(ioException);
            try
            {
                bluetoothSocket.close();
            }
            catch(IOException cancelIOException)
            {

            }
            return;
        }
        manageConnectedSocket(bluetoothSocket);
    }
    public void cancel()
    {
        try
        {
            bluetoothSocket.close();
        }
        catch(IOException ioException)
        {

        }
    }
}

Код потока для принятия соединения выглядит следующим образом:

        private class AcceptConnectionThread extends Thread
{
    private final BluetoothServerSocket bluetoothServerSocket;
    public AcceptConnectionThread() {
        // TODO Auto-generated constructor stub
        System.out.println("constructor");
        BluetoothServerSocket tempBluetoothServerSocket=null;
        try
        {
            tempBluetoothServerSocket=bluetoothAdapter.listenUsingRfcommWithServiceRecord("My Souvenirs", uuid);
        }
        catch(IOException ioException)
        {
        } 
        bluetoothServerSocket=tempBluetoothServerSocket;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("AcceptConnectionThread Run");
        BluetoothSocket bluetoothSocket=null;
        while(true)
        {
            try
            {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(bluetoothServerSocket);
                if(bluetoothServerSocket!=null)
                {
                    bluetoothSocket=bluetoothServerSocket.accept();
                }
                else {
                    System.out.println("bluetoothserversocket==null");
                }
                System.out.println("accept");
            }
            catch(IOException ioException){
                System.out.println("exception after accept");
                System.out.println(ioException);
                break;
            }
            if(bluetoothSocket!=null)
            {
                manageConnectedSocket(bluetoothSocket);
                try {
                    bluetoothServerSocket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    public void cancel()
    {
        try{
            bluetoothServerSocket.close();
        }
        catch(IOException ioException){

        }
    }

}

Код для метода manageConnectedSocket(), вызываемого в приведенных выше потоках, выглядит следующим образом:

        public void manageConnectedSocket(BluetoothSocket bluetoothSocket)
{

    manageConnectedDevicesThread=new ManageConnectedDevicesThread(bluetoothSocket);
    Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.request);
    ByteArrayOutputStream baos= new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
    byte[] bytes=baos.toByteArray();
    manageConnectedDevicesThread.write(bytes);
    System.out.println("manageConnectedSocket() method called");
    manageConnectedDevicesThread.start();
    System.out.println("success");      
    Intent intent=new Intent();
    intent.setAction("received");
    sendBroadcast(intent);
}

Код потока для управления подключенными устройствами выглядит следующим образом:

        private class ManageConnectedDevicesThread extends Thread
{
    private final BluetoothSocket connectedBluetoothSocket;
    InputStream tempInputStream=null;
    OutputStream tempOutputStream=null;
    public ManageConnectedDevicesThread(BluetoothSocket socket) {
        // TODO Auto-generated constructor stub
        connectedBluetoothSocket=socket;
        try
        {
            tempInputStream=socket.getInputStream();
            tempOutputStream=socket.getOutputStream();
        }
        catch(IOException ioException)
        {

        }
        inputStream=tempInputStream;
        outputStream=tempOutputStream;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("ManageConnectedDevicesThread Run");
        Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        ByteArrayOutputStream baos= new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
        byte[] buffer=new byte[1024*8];
        int bytes;
        while(true)
        {
            try
            {
                bytes=inputStream.read(buffer);
                handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
                System.out.println("handler");
            }
            catch(IOException ioException)
            {
                System.out.println("for handler:" +ioException);
                break;
            }
        }
    }
    public void write(byte[] bytes)
    {
        try
        {
            outputStream.write(bytes,0,bytes.length);
        }
        catch(IOException ioException){
            System.out.println("exception in write statement of managing connections");
        }

    }


    public void close()
    {
        try {   
            connectedBluetoothSocket.close();
        } catch (IOException e) {
            // TODO: handle exception
        }
    }
}

Код обработчика, реализованный в моем приложении, выглядит следующим образом:

    private final Handler handler=new Handler(){
public void handleMessage(Message msg) {
    switch (msg.what) {

    case MESSAGE_READ:
        byte[] readBuf = (byte[]) msg.obj;
        // construct a string from the valid bytes in the buffer
        String readMessage = new String(readBuf, 0, msg.arg1);
        byte[] b=readMessage.getBytes();
        if(sendingDeviceFlag==0)
        {
            Intent intent=new Intent();
            intent.setAction("received");
            sendBroadcast(intent);
            bluetoothDatabase.open();
            bluetoothDatabase.insert_slam(readMessage, readBuf);
            writeCount++;
            System.out.println("write count = "+writeCount);
            Cursor cursor=bluetoothDatabase.getSlam();
            if(cursor!=null)
            {
                cursor.moveToFirst();
                while(cursor.moveToNext())
                {
                    byte[] barray=cursor.getBlob(cursor.getColumnIndex("img"));
                    Bitmap bitmap1=BitmapFactory.decodeByteArray(barray, 0, barray.length);
                    imageView.setImageBitmap(bitmap1);
                }
                System.out.println("Count = "+cursor.getCount());
            }
            else {
                System.out.println("cursor null");
            }
            bluetoothDatabase.close();              
        }

        break;
    }
    };

Код для сброса соединения выглядит следующим образом:

        void resetConnection()  
{
    if(inputStream!=null)
    {
        try {
            inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
    if(outputStream!=null)
    {
        try {
            outputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
    if(startConnectionThread!=null) //my changes
    {
        System.out.println("start wala active tha");    
        startConnectionThread.cancel(); 
    }
    if(acceptConnectionThread!=null)    
    {
        System.out.println("accept wala active tha");   
        acceptConnectionThread.cancel();    
        acceptConnectionThread.interrupt();
        acceptConnectionThread=new AcceptConnectionThread();
        acceptConnectionThread.start();
    }
    if(manageConnectedDevicesThread!=null)
    {
        System.out.println("manage wala active tha");   
        manageConnectedDevicesThread.close();   
    }
}
    }

Пользователь щелкнет сопряженное или найденное устройство в списке, чтобы отправить изображение. Код для события click в списке выглядит следующим образом:

            devicesListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            if(startConnectionThread!=null)
            {
                Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.request);
                ByteArrayOutputStream baos= new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
                byte[] bytes=baos.toByteArray();
                manageConnectedDevicesThread.write(bytes);
                Intent intent=new Intent();
                intent.setAction("received");
                sendBroadcast(intent);
            }
            else {
                System.out.println("click on list view");
                sendingDeviceFlag=1;
                writeCount=0;
                System.out.println("after reset");
                bluetoothAdapter.cancelDiscovery();
                String address=new String();
                address=arrayAdapter.getItem(arg2);
                selectedBluetoothDevice=bluetoothAdapter.getRemoteDevice(address.substring(address.length()-17));
                startConnectionThread=new StartConnectionThread(selectedBluetoothDevice);
                startConnectionThread.start();
            }
        }
    });

person Varun Kumar    schedule 05.02.2014    source источник
comment
вы получаете сообщение об ошибке или время истекло?   -  person pageman    schedule 07.02.2014
comment
Я не получаю никакой ошибки. При последовательной передаче любого другого или того же изображения метод inputstream.read() вызывается чаще, чем при одиночном вызове outputstream.write().   -  person Varun Kumar    schedule 07.02.2014
comment
Я могу ошибаться в интерпретации этого, но я думаю, что это потому, что при последовательной передаче байт [] разбивается где-то между передачей из выходного потока во входной поток.   -  person Varun Kumar    schedule 07.02.2014
comment
Было бы очень любезно с вашей стороны, если бы вы могли помочь мне найти решение моей проблемы.   -  person Varun Kumar    schedule 07.02.2014