Почему TextView не может показать какие-либо данные с последовательного Bluetooth?

Мне нужно показать данные TextView с серийного Bluetooth. Но когда я подключил свое приложение к последовательному устройству, оно подключилось, но внезапно закрылось. LogCat ничего не показывает, поэтому я не знаю, что не так.

Это код, когда приложение слушает inputstream при подключении:

public void run() {
    Log.i(TAG, "BEGIN mConnectedThread");
    byte[] buffer = new byte[1024];
    int bytes;

    while (true) {
        try {

            // Read from the InputStream
            bytes = mmInStream.read(buffer);

            //mEmulatorView.write(buffer, bytes);

            mTextView.append(new String(buffer));
            // Send the obtained bytes to the UI Activity
            //mHandler.obtainMessage(BlueTerm.MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            String a = buffer.toString();
            mTextView.setText(a);
            a = "";
        } catch (IOException e) {
            Log.e(TAG, "disconnected", e);
            connectionLost();
            break;
        }
    }
}

а также TextView mTextView = (TextView) findViewById(R.id.dataTerm);
и на макете:

<TextView
    android:id="@+id/dataTerm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Так кто-нибудь знает, что пошло не так? Любые ответы так полезны, спасибо..

Код, который, наконец, работает

  1. На основной файл, в моем случае с именем FinalSetting:
    В методе Activity объявите:

    //Layout View   
    private static TextView mTextView;
    

    На onCreate(Bundle savedInstanceState) метод объявить textview:

    mTextView = (TextView) findViewById(R.id.dataTerm);
    

    На Handler метод:

    case MESSAGE_READ:
        byte[] readBuf = (byte[]) msg.obj;              
        //mEmulatorView.write(readBuf, msg.arg1);
        // construct a string from the valid bytes in the buffer
        String readMessage = new String(readBuf, 0, msg.arg1);
        //mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
        mTextView.setText(readMessage);
        break;
    
  2. На BluetoothService.java файл:
    Давайте прямо к методу

    //This thread runs during a connection with a remote device.
    //It handles all incoming and outgoing transmissions.
    
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
    
        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
    
            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
    
        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];
            //final byte[] buffer = new byte[1024];
            int bytes;
    
            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
    
                    //Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(FinalSetting.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }
    
        /**
        * Write to the connected OutStream.
        * @param buffer  The bytes to write
        */
        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);
    
                // Share the sent message back to the UI Activity
                mHandler.obtainMessage(FinalSetting.MESSAGE_WRITE, buffer.length, -1, buffer).sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }
    
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }    
    }
    

После подключения к последовательному устройству Bluetooth данные будут отображаться на TextView, Надеюсь это поможет:D

1 ответ

Похоже, что вы пытаетесь изменить mTextView в потоке, не являющемся пользовательским интерфейсом, что является недопустимым и может быть причиной для FC (если нет каких-либо других проблем). Однако вы можете добиться этого, как показано ниже:

Изменить это:

mTextView.append(new String(buffer));

К этому:

mTextView.post(new Runnable() {
    @Override
    public void run() {
        mTextView.append(new String(buffer));
    }
});
Другие вопросы по тегам