Java 在Android中通过蓝牙发送数据

Java 在Android中通过蓝牙发送数据,java,android,bluetooth,arduino,Java,Android,Bluetooth,Arduino,这是我用来通过蓝牙发送数据的代码,如果我单击按钮,它工作得很好,但是如果我不单击按钮直接调用函数sendData(String…),我就无法使用它 我正在尝试将单击按钮更改为使用语音识别 如果我使用 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "In onCreate()"); setContentView(R.layo

这是我用来通过蓝牙发送数据的代码,如果我单击按钮,它工作得很好,但是如果我不单击按钮直接调用函数sendData(String…),我就无法使用它

我正在尝试将单击按钮更改为使用语音识别

如果我使用

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d(TAG, "In onCreate()");

    setContentView(R.layout.main);

    btnOn = (Button) findViewById(R.id.btnOn);
    btnOff = (Button) findViewById(R.id.btnOff);

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();

    btnOn.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        sendData("a");
        Toast msg = Toast.makeText(getBaseContext(),
            "You have clicked On", Toast.LENGTH_SHORT);
        msg.show();
      }
    });

    btnOff.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        sendData("b");
        Toast msg = Toast.makeText(getBaseContext(),
            "You have clicked Off", Toast.LENGTH_SHORT);
        msg.show();
      }
    });}
但是如果我把sendData移到外面,它就不起作用了

btnOff.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
      }
    });
sendData("b");
这是完整的代码

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.example.ledonoff.R;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import android.widget.Toast;
import android.speech.RecognizerIntent;

import java.util.ArrayList;
import java.util.Locale;
import android.content.ActivityNotFoundException;

public class LEDOnOff extends Activity {
  private static final String TAG = "LEDOnOff";

  Button btnOn, btnOff, btnSpeak;
  public   String cmd = "none";
    private final int SPEECH_RECOGNITION_CODE = 1;
  private static final int REQUEST_ENABLE_BT = 1;
  private BluetoothAdapter btAdapter = null;
  private BluetoothSocket btSocket = null;
  private OutputStream outStream = null;
  private TextView textout;
  // Well known SPP UUID
  private static final UUID MY_UUID =
      UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  // Insert your bluetooth devices MAC address
  private static String address = "98:D3:32:10:91:1F";

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

    Log.d(TAG, "In onCreate()");

    setContentView(R.layout.main);

    btnOn = (Button) findViewById(R.id.btnOn);
    btnOff = (Button) findViewById(R.id.btnOff);
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    textout = (TextView) findViewById(R.id.textout);

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();

    btnOn.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        sendData("a");
        Toast msg = Toast.makeText(getBaseContext(),
            "You have clicked On", Toast.LENGTH_SHORT);
        msg.show();
      }
    });

    btnOff.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        sendData("b");
        Toast msg = Toast.makeText(getBaseContext(),
            "You have clicked Off", Toast.LENGTH_SHORT);
        msg.show();
      }
    });

      btnSpeak.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
            startSpeechToText();

          }
      });

  }




    /**
     * Start speech to text intent. This opens up Google Speech Recognition API dialog box to listen the speech input.
     * */
    private void startSpeechToText() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                "Speak something...");
        try {
            startActivityForResult(intent, SPEECH_RECOGNITION_CODE);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Speech recognition is not supported in this device.",
                    Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * Callback for speech recognition activity
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SPEECH_RECOGNITION_CODE: {
                if (resultCode == RESULT_OK && null != data) {
                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    String text = result.get(0);
                    textout.setText(text); 

                }


              break;


            }
        }
    }

    public String VoiceFilter(String str_voice_input){


        if(str_voice_input.contains("on") ){sendData("a"); //TEST SENDING DATA
          return "a" ;
        }

        if(str_voice_input.contains("off") ){sendData("b"); //TEST SENDING DATA
          return "b" ;
        }

      return "c";


    }

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

    Log.d(TAG, "...In onResume - Attempting client connect...");

    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    // Two things are needed to make a connection:
    //   A MAC address, which we got above.
    //   A Service ID or UUID.  In this case we are using the
    //     UUID for SPP.
    try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    btAdapter.cancelDiscovery();

    // Establish the connection.  This will block until it connects.
    Log.d(TAG, "...Connecting to Remote...");
    try {
      btSocket.connect();
      Log.d(TAG, "...Connection established and data link opened...");
    } catch (IOException e) {
      try {
        btSocket.close();
      } catch (IOException e2) {
        errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }

    // Create a data stream so we can talk to server.
    Log.d(TAG, "...Creating Socket...");

    try {
      outStream = btSocket.getOutputStream();
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
    }
  }

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

    Log.d(TAG, "...In onPause()...");

    if (outStream != null) {
      try {
        outStream.flush();
      } catch (IOException e) {
        errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
      }
    }

    try     {
      btSocket.close();
    } catch (IOException e2) {
      errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
  }

  private void checkBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on

    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) { 
      errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
    } else {
      if (btAdapter.isEnabled()) {
        Log.d(TAG, "...Bluetooth is enabled...");
      } else {
        //Prompt user to turn on Bluetooth
        Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      }
    }
  }

  private void errorExit(String title, String message){
    Toast msg = Toast.makeText(getBaseContext(),
        title + " - " + message, Toast.LENGTH_SHORT);
    msg.show();
    finish();
  }

  private void sendData(String message) {
    byte[] msgBuffer = message.getBytes();

    Log.d(TAG, "...Sending data: " + message + "...");

    try {
      outStream.write(msgBuffer);
    } catch (IOException e) {
      String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
      if (address.equals("00:00:00:00:00:00")) 
        msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
      msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

      errorExit("Fatal Error", msg);       
    }
  }
}
import java.io.IOException;
导入java.io.OutputStream;
导入java.util.UUID;
导入java.util.concurrent.TimeUnit;
导入com.example.ledonoff.R;
导入android.app.Activity;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothSocket;
导入android.content.Intent;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.TextView;
导入android.widget.Toast;
导入android.speech.RecognizerIntent;
导入java.util.ArrayList;
导入java.util.Locale;
导入android.content.ActivityNotFoundException;
公共类LEDOnOff扩展了活动{
私有静态最终字符串TAG=“LEDOnOff”;
按钮btnOn、btnOff、btnSpeak;
公共字符串cmd=“无”;
专用最终整型语音识别码=1;
私有静态最终整数请求_ENABLE_BT=1;
私有蓝牙适配器btAdapter=null;
私有BluetoothSocket btSocket=null;
私有OutputStream outStream=null;
私有文本视图文本输出;
//众所周知的SPP UUID
私有静态最终UUID MY_UUID=
UUID.来自字符串(“00001101-0000-1000-8000-00805F9B34FB”);
//插入蓝牙设备的MAC地址
私有静态字符串地址=“98:D3:32:10:91:1F”;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
d(标记“In onCreate()”);
setContentView(R.layout.main);
btnOn=(按钮)findViewById(R.id.btnOn);
btnOff=(按钮)findViewById(R.id.btnOff);
btnSpeak=(按钮)findViewById(R.id.btnSpeak);
textout=(TextView)findViewById(R.id.textout);
btAdapter=BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
sendData(“a”);
Toast msg=Toast.makeText(getBaseContext(),
“你点击了”,吐司。长度(短);
msg.show();
}
});
setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
sendData(“b”);
Toast msg=Toast.makeText(getBaseContext(),
“你点击了”,吐司。长度(短);
msg.show();
}
});
setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
startSpeechToText();
}
});
}
/**
*启动语音到文本意图。这将打开Google语音识别API对话框,以侦听语音输入。
* */
私有void startSpeechToText(){
意向意向=新意向(识别意向、行动、识别言语);
intent.putExtra(RecognizerIntent.EXTRA_语言,Locale.getDefault());
intent.putExtra(识别器intent.EXTRA_语言_模型,
识别者意图、语言、模型、自由形式);
intent.putExtra(识别器intent.EXTRA\u提示符,
“说点什么……”;
试一试{
startActivityForResult(意图、语音识别码);
}捕获(ActivityNotFoundException a){
Toast.makeText(getApplicationContext(),
“抱歉!此设备不支持语音识别。”,
吐司。长度(短)。show();
}
}
/**
*语音识别活动的回调
* */
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
开关(请求代码){
案例语音识别代码:{
if(resultCode==RESULT\u OK&&null!=数据){
ArrayList结果=数据
.getStringArrayListExtra(识别器意图.额外结果);
String text=result.get(0);
textout.setText(text);
}
打破
}
}
}
公共字符串语音过滤器(字符串字符串字符串语音输入){
if(str_voice_input.contains(“on”){sendData(“a”);//测试发送数据
返回“a”;
}
if(str_voice_input.contains(“off”){sendData(“b”);//测试发送数据
返回“b”;
}
返回“c”;
}
@凌驾
恢复时公开作废(){
super.onResume();
Log.d(在onResume中标记“…正在尝试客户端连接…”);
//使用远程节点的地址设置指向该节点的指针。
BluetoothDevice=btAdapter.getRemoteDevice(地址);
//建立连接需要两件事:
//上面我们看到的MAC地址。
//服务ID或UUID。在本例中,我们使用
//用于SPP的UUID。
试一试{
btSocket=device.createrFComSocketToServiceRecord(我的UUID);
}捕获(IOE异常){
errorExit(“致命错误”,“在onResume()和套接字创建中失败:“+e.getMessage()+”);
}
//发现是资源密集型的。请确保它不会继续进行
//当您尝试连接并传递消息时。
btAdapter.cancelDiscovery();
//建立连接。这将阻止,直到连接为止。
Log.d(标记“…连接到远程…”);
试一试{
btSocket.connect();
Log.d(标记“…连接已建立,数据链路已打开…”);
}捕获(IOE异常){
试一试{
btSocket.close();
}捕获(IOE2异常){
errorExit(“致命错误”,“在onResume()中”,在连接失败期间无法关闭套接字