简体   繁体   中英

Bluetooth Connection and Receive/Display Data on Screen

I am trying to connect my android phone to a Bluetooth chip on a circuit connected to a sonar sensor. The sensor/circuit is programmed to accept a connection and continuously display data in the form of a message. My code allows me to connect but it won't display data on the screen. Help?

Below you can find my java code.

public class ConnectThread extends Activity {
    static BluetoothSocket mmSocket;
    static BluetoothSocket mmSocket2;
    static BluetoothDevice mmDevice;
    static BluetoothDevice mmDevice2;
    static InputStream mmInputStream;
    static OutputStream mmOutputStream;
    static BluetoothAdapter mBluetoothAdapter;
    static BluetoothAdapter mBluetoothAdapter2;
    TextView myLabel;
    TextView Display;
    static volatile boolean stopWorker;
    static Thread workerThread;
    static byte[] readBuffer;
    static int readBufferPosition;

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

    Button button = (Button)this.findViewById(R.id.button1);
    myLabel = (TextView)findViewById(R.id.textView1);
    Display = (TextView)findViewById(R.id.Display);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(ConnectThread.this, "Connection in progress", Toast.LENGTH_SHORT).show();
            myLabel.setText("Connection in progress");
            try 
            {
                 findBT();
                 openBT();

            }
            catch (IOException ex) { }
           }        
         });}



        void findBT() 
        {


            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if(mBluetoothAdapter == null)
            {
                myLabel.setText("No bluetooth adapter available");
            }

            if(!mBluetoothAdapter.isEnabled())
            {
                Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetooth, 0);
            }

            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if(pairedDevices.size() > 0)
            {
                for(BluetoothDevice device1 : pairedDevices)
                {
                    if(device1.getName().equals("HC-05")) 
                    {
                        mmDevice = device1;
                        myLabel.setText("Bluetooth Device Found");
                        break;
                    }
                }

                if(pairedDevices.size()==0){myLabel.setText("Please Pair devices");}
            }




        }
        public int openBT() throws IOException
        {
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);        
            mmSocket.connect();
            mmOutputStream = mmSocket.getOutputStream();
            mmInputStream = mmSocket.getInputStream();


            return 1;
        }

        void ListenForData()
        {
            final Handler handler = new Handler(); 
            final byte delimiter = 10; //This is the ASCII code for a newline character

            stopWorker = false;
            readBufferPosition = 0;
            readBuffer = new byte[1024];
            workerThread = new Thread(new Runnable()
            {
                public void run()
                {                
                   while(!Thread.currentThread().isInterrupted() && !stopWorker)
                   {
                        try 
                        {
                            int bytesAvailable = mmInputStream.available();                        
                            if(bytesAvailable > 0)
                            {
                                byte[] packetBytes = new byte[bytesAvailable];
                                mmInputStream.read(packetBytes);
                                for(int i=0;i<bytesAvailable;i++)
                                {
                                    byte b = packetBytes[i];
                                    if(b == delimiter)
                                    {
                                        byte[] encodedBytes = new byte[readBufferPosition];
                                        System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                        final String data = new String(encodedBytes, "US-ASCII");
                                        readBufferPosition = 0;

                                        handler.post(new Runnable()
                                        {
                                            public void run()
                                            {
                                                Display.setText(data);

                                            }
                                        });
                                    }
                                    else
                                    {
                                        readBuffer[readBufferPosition++] = b;
                                    }
                                }
                            }
                        } 
                        catch (IOException ex) 
                        {
                            stopWorker = true;
                        }
                   }
                }
            });

            workerThread.start();
        }



        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
            { myLabel.setText("CONNECTED");}
        }
        void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    }
        }

Pass your message using handler like:

public static final int MESSAGE_PROGRESS = 1;
public static final String TOAST = "toast";


Message msg = mHandler.obtainMessage(ConnectThread.MESSAGE_PROGRESS);
Bundle bundle = new Bundle();
bundle.putString(ConnectThread.TOAST, progressMessage);
msg.setData(bundle);
mHandler.sendMessage(msg);

and set Text with help of handler like:

String data;
private final Handler mHandler = new Handler() {
void handleMessage(Message msg) {
switch (msg.what) {
    case MESSAGE_TOAST:
     if(data = msg.getData().getString(TOAST)) {
        Display.setText(data);
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM