无法使用蓝牙HC-06发送数据 - 应用程序停止工作

时间:2017-03-10 22:39:39

标签: android android-studio bluetooth arduino

我试图在Arduino和Android设备之间建立连接。 我正在使用:

  • Arduino Leonardo
  • 蓝牙设备:HC-06

我的Android应用程序应该读取从Arduino设备发送的数据。这是Arduino的代码。

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:

   delay(500);
   Serial.print("#A~");
   Serial1.print("#A~");
}

我的应用程序正在与Arduino建立连接,但事实是我的应用程序在从Arduino接收数据时崩溃了。它说"不幸的是,BluetoothApp已停止运行"。

奇怪的是,我可以使用适用于Android的蓝牙终端应用程序从Arduino接收数据。

以下是Android的代码:

    package com.example.matt.onresumeapp;

import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.String;
import java.util.UUID;

public class ComunicationActivity extends AppCompatActivity {


    TextView copyInfo;
    TextView handlerInfo;
    Handler h;
    BluetoothAdapter btAdapter;

    private String adress;
    private ConnectedThread mConnectedThread;
    private static UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothSocket mmSocket;
    private StringBuilder stBuilder = new StringBuilder();

    final int handlerState = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comunication);

        copyInfo = (TextView) findViewById(R.id.copyInfo);
        handlerInfo = (TextView) findViewById(R.id.handlerInfo);



        h = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if(msg.what == handlerState){

                    String readMessage = (String) msg.obj;
                    stBuilder.append(readMessage);

                    int endOfLine = stBuilder.indexOf("~");


                    if(stBuilder.charAt(0) == '#'){

                        String dataInPrint = stBuilder.substring(1, endOfLine);
                        handlerInfo.setText(dataInPrint);

                    }

                    stBuilder.delete(0, endOfLine);

                }

            }
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter();

    }

    private BluetoothSocket btSocketConnection (BluetoothDevice device) throws IOException{

        return device.createInsecureRfcommSocketToServiceRecord(myUUID);
    }


    @Override
    public void onResume() {
        super.onResume();

        Intent newIntent = getIntent();
        adress = newIntent.getStringExtra("EXTRA_ADRESS");


        BluetoothDevice device = btAdapter.getRemoteDevice(adress);

        try {
            mmSocket = btSocketConnection(device);



        } catch (IOException e) {

            Toast.makeText(getBaseContext(), "Socket's method failed", Toast.LENGTH_LONG).show();

        }

        try {
            mmSocket.connect();
        } catch (IOException e){

            try {

                mmSocket.close();
            } catch (IOException e1)
            {
                Toast.makeText(getBaseContext(), "Socket's connect() method failed", Toast.LENGTH_LONG).show();
            }

        }
        mConnectedThread = new ConnectedThread(mmSocket);
        mConnectedThread.start();


    }



    private class ConnectedThread extends Thread{

        private InputStream mmInStream;
        private OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket){

            mmSocket = socket;

            InputStream tmpIn = null;
            OutputStream tmpOut= null;

            try {

                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e){

                Toast.makeText(getBaseContext(), "Error occurred when creating input stream", Toast.LENGTH_LONG).show();

            }

            try {
                tmpOut = socket.getOutputStream();

            } catch (IOException e){


                Toast.makeText(getBaseContext(), "Error occurred when creating output stream", Toast.LENGTH_LONG).show();
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;

        }


        public void run() {
            super.run();

            byte[] mmBuffer = new byte[1024];
            int numBytes;

            while (true){
                try{
                    numBytes = mmInStream.read(mmBuffer);

                    String readMessage = new String(mmBuffer, 0, numBytes);
                    h.obtainMessage(handlerState, numBytes, -1, readMessage).sendToTarget();

                } catch (IOException e){

                    Toast.makeText(getBaseContext(), "Input stream was disconnected", Toast.LENGTH_LONG).show();
                    break;
                }

            }

        }
    }

}

我试图解决这个问题几天但没有任何进展...... 我非常感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:1)

<强>解决:

刚刚更改了处理程序方法:

 h = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if(msg.what == handlerState){

                    byte[] rBuff = (byte[]) msg.obj;

                    String readMessage = new String(rBuff, 0, msg.arg1);
                    handlerInfo.setText(readMessage);

                }

            }
        };