несколько дней я работаю над этим проектом, и теперь я расстроен, потому что моя программа не работает. Так что я работаю в студии Android, мой проект - запустить двигатель мотоцикла с помощью смартфона. Мое приложение работает нормально, если я просто использую кнопку и включаю двигатель без проблем. Но я добавляю новую функцию, которая является голосовой командой. это может запустить двигатель, используя мой голос. Таким образом, распознавание речи обнаруживает мой голос и преобразовывает его в текст. но если я поставлю код для отправки данных запуска двигателя через Bluetooth. программа не работает и выдает сообщение «Ошибка подключения: проверьте модуль Bluetooth устройства: подключение закрыто»
Я думаю, что код Bluetooth не может работать внутри «protected void onActivityResult ..». Есть ли какое-либо решение для этого? Заранее спасибо.
Вот мой код:
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth";
ToggleButton t1, t2, t3, t4, t5, t6, t7, t8;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (ToggleButton) findViewById(R.id.toggleButton1);
t2 = (ToggleButton) findViewById(R.id.toggleButton2);
t3 = (ToggleButton) findViewById(R.id.toggleButton3);
t3.setOnTouchListener(btnTouch);
t4 = (ToggleButton) findViewById(R.id.toggleButton);
t4.setOnTouchListener(btnTouch2);
t1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (t1.isChecked()) {
sendData("A");
Toast.makeText(MainActivity.this, "Ignition ON!", Toast.LENGTH_SHORT).show();
} else {
sendData("a");
Toast.makeText(MainActivity.this, "Ignition OFF!", Toast.LENGTH_SHORT).show();
}
}
});
t2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (t2.isChecked()) {
sendData("B");
Toast.makeText(MainActivity.this, "Security On!", Toast.LENGTH_SHORT).show();
} else {
sendData("b");
Toast.makeText(MainActivity.this, "Security Off!", Toast.LENGTH_SHORT).show();
}
}
});
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
}
//Start Engine OnPressed Button
private View.OnTouchListener btnTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN)
sendData("C");
else if (action == MotionEvent.ACTION_UP)
sendData("c");
return false; // the listener has NOT consumed the event, pass it on
}
};
//Horn OnPressed Button
private View.OnTouchListener btnTouch2 = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN)
sendData("D");
else if (action == MotionEvent.ACTION_UP)
sendData("d");
return false; // the listener has NOT consumed the event, pass it on
}
};
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if (Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(HomeScreen.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 = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.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...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} 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, "...Create 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("Bluetooth Error: ", "Make sure the bluetooth is on. ");
}
}
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 support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "Please check device's Bluetooth Module: " + e.getMessage();
if (HomeScreen.address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nPlease Update your MAC Address";
// msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Connection Failed: ", msg);
}
}
public void btnVoice(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (result.get(0).toString().equals("start engine"))
{
Toast.makeText(MainActivity.this, "ENGINE ON!", Toast.LENGTH_SHORT).show();
sendData("C");
}
if (result.get(0).toString().equals("turn off engine"))
{
Toast.makeText(MainActivity.this, "ENGINE OFF!", Toast.LENGTH_SHORT).show();
sendData("c");
}
}
break;
}
}
}