尝试连接HC-06时app停止了

时间:2016-06-02 23:22:57

标签: android bluetooth

我尝试创建一个与HC-06连接的Android应用程序,并在textview中显示传感器检测到的数据 但当我点击按钮开始连接我的应用程序停止并显示一个吐司说我必须激活蓝牙

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>

1 个答案:

答案 0 :(得分:0)

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

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
}

svg {
  padding: 10px 0 0 10px;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var colors = d3.scale.category10();

var radius = 80,
    padding = 10;

// set up our 3 arcs
var arcs = [
  d3.svg.arc()
    .outerRadius(radius)
    .innerRadius(radius - 8),
  d3.svg.arc()
    .outerRadius(radius - 10)
    .innerRadius(radius - 18),
  d3.svg.arc()
    .outerRadius(radius - 20)
    .innerRadius(radius - 28)
];

// given this csv data
var csv = `Company,score_A,score_B,score_C
Natural Health Trends,10,50,70
Vipshop,90,23,76
Facebook,34,46,87`;

// clean up data
var data = d3.csv.parse(csv, function(d){
  return {
    score_A: +d.score_A,
    score_B: +d.score_B,
    score_C: +d.score_C,
    company: d.Company
  }
});

// an svg for every set of arcs
var svg = d3.select("body").selectAll(".pie")
  .data(data)
  .enter().append("svg")
  .attr("class", "pie")
  .attr("width", radius * 2)
  .attr("height", radius * 2)
  .append("g")
  .attr("transform", "translate(" + radius + "," + radius + ")");
  
// text in center
svg.append("text")
  .attr("dy", ".35em")
  .style("text-anchor", "middle")
  .text(function(d) { return d.company; });

// a g for gray and colored arcs
var g = svg.selectAll(".arc")
  .data(function(d){
    return [d.score_A, d.score_B, d.score_C];
  })
  .enter()
  .append("g");

// gray portion just run 100 %
g.append("path")
  .attr("d", function(d,i){
    return arcs[i]({
      startAngle: 0,
      endAngle: (2 * Math.PI)
    });
  })
  .style("fill", "lightgray");

// colored portion
g.append("path")
  .attr("d", function(d,i){
    return arcs[i]({
      startAngle: 0,
      endAngle: (d / 100) * (2 * Math.PI)
    });
  })
  .style("fill", function(d,i){
    return colors(i);
  });

</script>