1

Зависает на строчке msg = ois.readObject(); Причем иногда зависает, а иногда нет. В чём дело, кто подскажет?

import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class CommunicatorImpl extends Thread implements Communicator {

    interface CommunicationListener {
        void onMessage(Object message);
    }

    private final BluetoothSocket socket;
    private final InputStream inputStream;
    private final OutputStream outputStream;
    private final CommunicationListener listener;

    private ObjectOutputStream oos;
    private  ObjectInputStream ois;

    public CommunicatorImpl(BluetoothSocket socket, CommunicationListener listener) {
        this.socket = socket;
        this.listener = listener;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.d("CommunicatorImpl", e.getLocalizedMessage());
        }
        inputStream = tmpIn;
        outputStream = tmpOut;

        try {
            oos = new ObjectOutputStream(new BufferedOutputStream(outputStream));
            oos.flush();
            ois = new ObjectInputStream(new BufferedInputStream(inputStream));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void startCommunication() {
        Log.d("CommunicatorImpl", "Run the communicator");
        while (true) {
            if (listener != null) {
                Object msg = null;
                try {
                    msg = ois.readObject();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(msg!=null) {
                    listener.onMessage(msg);
                }
            }
        }
    }

    public void write(Object message) {
//        Log.d("CommunicatorImpl", "Write " + message);
        try {
            oos.writeObject(message);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void stopCommunication() {
        try {
            socket.close();
        } catch (IOException e) {
            Log.d("CommunicatorImpl", e.getLocalizedMessage());
        }
    }

}


package com.fannasankh.bluetoothmaze;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;
import java.io.Serializable;
import java.util.UUID;

public class ClientThread extends Thread implements Serializable {

    private volatile Communicator communicator;

    private final BluetoothSocket socket;
    private BluetoothAdapter bluetoothAdapter;
    private final CommunicatorService communicatorService;

    public ClientThread(BluetoothDevice device, CommunicatorService communicatorService) {

        this.communicatorService = communicatorService;

        BluetoothSocket tmp = null;
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        try {
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(BluetoothActivity.UUID));
        } catch (IOException e) {
            Log.d("ClientThread", e.getLocalizedMessage());
        }
        socket = tmp;
    }

    public synchronized Communicator getCommunicator() {
        return communicator;
    }

    public void run() {
        bluetoothAdapter.cancelDiscovery();
        try {
            Log.d("ClientThread", "About to connect");
            socket.connect();
            Log.d("ClientThread", "Connected");
            synchronized (this) {
                communicator = communicatorService.createCommunicatorThread(socket);
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d("ClientThread", "Start");
                    communicator.startCommunication();
                }
            }).start();
        } catch (IOException connectException) {
            try {
                socket.close();
            } catch (IOException closeException) {
                Log.d("ClientThread", closeException.getLocalizedMessage());
            }
        }
    }

    public void cancel() {
        if (communicator != null) communicator.stopCommunication();
    }
}
4
  • а как ещё мне реализовать чтение того, что приходит? Я первый раз с этим работаю. Реализация переделана с приложения, которое пересылает сообщения напрямую через Input/OutputStream. А мне потребовались объекты. 13 апр 2017 в 20:47
  • Ну на данный момент я не знаю, как сделать иначе. 13 апр 2017 в 20:55
  • @АртёмАлтухов самый простой вариант - использовать булеву переменную: while (isWorking) { ... } с установкой в false в stopCommunication.
    – Regent
    14 апр 2017 в 5:46
  • а из-за этого может быть работа через раз? Сейчас попробую сделать 15 апр 2017 в 7:53

2 ответа 2

1

Метод readObject() блокирующий, то есть текущий поток исполнения заблокируется на этом методе, пока в сокет не придут данные. Зависает потому, что с другой стороны объект не отправляется по сокету в этот ois и читать нечего.

1
  • Комментарии не предназначены для расширенной дискуссии; разговор перемещён в чат.
    – user177221
    27 мая 2017 в 9:32
0

В общем решил я проблему, методом тыка, не совсем понял, что происходит, если кто-нибудь объяснит, буду благодарен. Поправка: проблема стала реже, но не ушла.

private class WriteTask extends AsyncTask<String, Void, Void> {
        protected Void doInBackground(String... args) {
            try{
                clientThread.getCommunicator().write(args[0]);
            } catch (Exception e) {
                Log.d("BluetoothActivity", e.getClass().getSimpleName() + " " + e.getLocalizedMessage());
            }
            return null;
        }
    }

метод write

 public void write(Object message) {
        final Object msg = message;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    oos.writeObject(msg);
                    oos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

раньше было тоже самое, но в write я не создавал новый поток. Но ведь по идее, если я вызываю write из объекта AsyncTask, то новый поток и так создаётся. Или я не прав?

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.