在Android上从BlueTooth获取文本

时间:2012-10-18 02:09:26

标签: android bluetooth

我正在为android(API级别:7)编写一个应用程序,它允许在android设备和另一个设备(例如,另一个Android设备)之间进行文本消息交换。这是BlueToothChat的简单版本。

我正在使用sucess连接并启动监听线程,但是当消息到来时(当达到命令设置文本os stBluetooth TextView并收到消息时),应用程序崩溃。拜托,这里有人会帮助我吗?

我的整个代码如下:

public class ControlebluetoothActivity extends Activity {
    //variaveis globais:
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    TextView stBluetooth;
    TextView stHttp;


    protected BluetoothSocket mySocket;
    private BluetoothDevice  mBluetoothDevice = null;
    private InputStream MyInStream;
    private OutputStream MyOutStream;
    private ConnectedThread mConnectedThread;
    private Verifica mVerifica;

    private boolean flag_t;
    byte[] bufferIn = new byte[100];
    byte[] bufferIn_temp = new byte[10];
    int bytesIn=0;
    int bytesIn_tmp=0;
    String strTempIn;
    String strTempIn2;
    String strBufferIn;
    String recebido;
    Timer timer = new Timer();

    byte[] buffer = new byte[1024];
    int bytes=0;




    private static final int REQUEST_ENABLE_BT = 2;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");



    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        stBluetooth=(TextView)findViewById(R.id.status_bluetooth);
        stHttp=(TextView)findViewById(R.id.status_http);

        //verifica se o dispositivo aceita bluetooth
        if (mBluetoothAdapter == null) {
            stBluetooth.setText("Dispositivo não possui bluetooth");

        } else {


                //ativação do bluetooth caso este nao esteja habilitado

                if (!mBluetoothAdapter.isEnabled()) 
                    {       
                        stBluetooth.setText("Habilitando bluetooth");
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    }  

                //scaneando e conectando:
                if (mBluetoothAdapter.isEnabled()) 
                {
                    stBluetooth.setText("Conectando ao shield bluetooth");
                    String endereco ="00:12:05:01:94:20"; //for the beginning, i fixed the MAC addres of my bluetooth device

                    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(endereco);

                }

                BluetoothSocket tmp = null;

                try {
                    tmp = mBluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) {
                    stBluetooth.setText("Primeira tentativa - falha");
                }
                mySocket = tmp;

                try {
                mySocket.connect();
                } catch (IOException e) {
                    stBluetooth.setText("Segunda tentativa - falha");
                }   

                try {
                    MyInStream = mySocket.getInputStream();
                } catch (IOException e) {
                    stBluetooth.setText("Falha de conexão");
                }

                stBluetooth.setText("Conectado a "+mySocket.getRemoteDevice());

                //thread que faz a comunicação



                mConnectedThread = new ConnectedThread(mySocket);
                mConnectedThread.start();


      }
 }


    private class ConnectedThread extends Thread {

        public ConnectedThread(BluetoothSocket socket) {
        mySocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        MyInStream = tmpIn;
        MyOutStream = tmpOut;


        }
        public void run() {


            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = MyInStream.read(buffer);

                    recebido=buffer.toString();

                } catch (IOException e) {

                }

                stBluetooth.setText("Dado: "+recebido);  //it crashes here!!!


            }
        }



    }  





    private class Verifica extends Thread {

        public Verifica() {


        }
        public void run() {



            while (true) {
                        stBluetooth.setText("dado: "+buffer.toString());
                        try{ Thread.sleep(1000); }catch(InterruptedException e){ }
                }


        }
    }




 }

1 个答案:

答案 0 :(得分:0)

您的应用崩溃的原因是您正在尝试从内部线程更新GUI线程。

试试这个:

public void run() {

    // Keep listening to the InputStream while connected
    while (true) {
        try {
            // Read from the InputStream
            bytes = MyInStream.read(buffer);

            recebido=buffer.toString();

        } catch (IOException e) {
        }

        runOnUiThread(new Runnable() {
            public void run() {
                stBluetooth.setText("Dado: "+recebido);
            }
        });

    }
}