尝试连接 HC-06 时应用程序已停止



我试图创建一个与HC-06连接并在文本视图中显示传感器检测到的数据的android应用程序但是当我单击按钮开始连接时,我的应用程序已停止并显示一个吐司,说我必须激活蓝牙

package com.example.admin.app_sniff;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class Activity_2 extends Activity
{   private static final int REQUEST_ENABLE_BT = 1;
    TextView myLabel;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    volatile boolean stopWorker;
    BluetoothAdapter bluetoothAdapter ;
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);

        ImageButton bt1 = (ImageButton) findViewById(R.id.demarrer);
        ImageButton bt2 = (ImageButton)findViewById(R.id.arreter);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
         myLabel = (TextView)findViewById(R.id.text1);
    //Open Button
        bt1.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v)
            {
               F1();
            }
        });

    //Close button
        bt2.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                while (!stopWorker)
                {
                try
                {
                    closeBT();
                }
                catch (IOException ex) {
                stopWorker=true;}
                }}
        });
    }
    public void F1(){
        while (!stopWorker)
        {
        try
        {
            findBT();
            openBT();
        }
        catch (IOException ex) {
        stopWorker=true ;
        }
        }
    }
   public void findBT()
    {

        if (bluetoothAdapter == null) {
            myLabel.setText(R.string.Bluetooth_NOT_support);
        } else {
            myLabel.setText(R.string.Bluetooth_support);
            if (!bluetoothAdapter.isEnabled()) {
                myLabel.setText(R.string.not_enabled);
                Intent enableBluetooth = new    Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetooth,REQUEST_ENABLE_BT);
                myLabel.setText(R.string.enabled);
            }
        }


        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("HC-06"))
                {
                    mmDevice = device;
                    break;
                }
            }
        }
        myLabel.setText(R.string.Bluetooth_Device_not_found);
    }
    public void 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();
        beginListenForData();
        Toast.makeText(this, "Bluetooth Opened", Toast.LENGTH_LONG)
                .show();
    }
    public void beginListenForData()
    {
        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()
                                        {
                                            myLabel.setText(data);
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    { stopWorker = true;
                    }
                 }
            }
        });
        workerThread.start();
    }

   public void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText(R.string.Bluetooth_Closed);
    }
}

这是我的 XML 布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/background2"
    tools:context="com.example.admin.app_sniff.Activity_2">
    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/demarrer"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="382dp"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/text1"
            android:layout_row="2"
            android:layout_column="0" />
    </GridLayout>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/demarrer"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="53dp"
        android:src="@drawable/btn1"
        android:contentDescription="@string/de"
        />
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/arreter"
        android:layout_alignBottom="@+id/demarrer"
        android:layout_toRightOf="@+id/demarrer"
        android:layout_toEndOf="@+id/demarrer"
        android:src="@drawable/btn2"
        android:contentDescription="@string/ar"
        />
</RelativeLayout>

您是否在 AndroidManifest 中添加了使用蓝牙的权限?

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

最新更新