这是我的:bluetooth.java。当我测试我的应用程序时,它会跳出这个错误"线程已经启动了。然后我不能再发送我的数据了,然后我退出我的应用,然后我再次启动我的应用程序,然后它允许我使用应用程序。"。太令人困惑了。我希望你能帮助我。谢谢你的帮助。
public class bluetooth extends AppCompatActivity {
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
on = (ImageView) findViewById(R.id.btn_enable);
find = (ImageView) findViewById(R.id.btn_scan);
mPairedBtn = (ImageView) findViewById(R.id.btn_view_paired);
BA = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
back =(ImageView) findViewById(R.id.backblue);
ontext = (TextView) findViewById(R.id.connecttext);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(bluetooth.this,MainActivity.class);
startActivity(intent);
}
});
//xử lí các nút
if (BA == null) {
showUnsupported();
} else {
mPairedBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = BA.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
showToast("No Paired Devices Found");
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(bluetooth.this, DeviceListActivity.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
find.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
BA.startDiscovery();
}
});
on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (BA.isEnabled()) {
BA.disable();
showDisabled();
/* try
{
btSocket.close();
} catch (IOException e2)
{
}*/
on.setImageResource(R.drawable.offlight);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
on.setImageResource(R.drawable.onlight);
}
}
});
if (BA.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
//thong bao cho may la chuong trinh nay co he su dung dc gi bluetooth
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
/* BroadcastReceiver dùng để nhận các intent từ hệ thống hoặc trao đổi dữ liệu giữa hai hay nhiều ứng dụng.*/
registerReceiver(mReceiver, filter);
// MAC-address of Bluetooth module (you must edit this line)
address = "30:14:10:09:07:86";
//create device and set the MAC address
BluetoothDevice device = BA.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
//btSocket.connect();
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
Toast.makeText(getApplicationContext(),"cant do this",Toast.LENGTH_LONG).show();
}
}
ConnectedThread.createInstance(btSocket);
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
if(ConnectedThread.getInstance()!= null){
ConnectedThread.getInstance().start();
}else {
ConnectedThread.getInstance().cancel();
}
}
@Override
public void onResume() {
super.onResume();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(MY_UUID);
//creates secure outgoing connecetion with BT device using UUID
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Enabled");
showEnabled();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(bluetooth.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
}
};
}
这是我制作的一个库,你可能想试一试:
https://github.com/omaflak/Bluetooth-Android
它与HC-06完美配合,对你来说应该是一样的。这就是我如何使用类:
Bluetooth bt = new Bluetooth();
bt.enableBluetooth();
bt.setBluetoothCallback(new Bluetooth.BluetoothCallback() {
@Override
public void onConnect(BluetoothDevice device) {
bt.send("hello world!");
}
@Override
public void onDisconnect(BluetoothDevice device, String message) {
Log.e(TAG, "Disconnected!");
}
@Override
public void onMessage(String message) {
Log.e(TAG, "Received: "+message);
}
@Override
public void onError(String message) {
Log.e(TAG, "Error: "+message);
}
@Override
public void onConnectError(BluetoothDevice device, String message) {
Log.e(TAG, message);
bt.connectToDevice(device); // try to connect again
}
});
/*
Connection...
/! you must be paired with the device via the settings app /!
*/
bt.connectToName("HC-06");
//you can also connect with: bt.connectToAddress(address) and bt.connectToDevice(device)
编辑:在Arduino方面,您必须在每条消息的末尾放一个\n。您可以简单地使用Serial.println("message").
第2版:您可以在此处找到我的Arduino代码:https://causeyourestuck.io/2015/12/14/communication-between-android-and-hc-06-module/
我知道我的答案来得很晚,但我想提到(并链接)一个适用于Android的基于消息的蓝牙库,它使用起来非常简单,希望它对某人有用:
https://github.com/BasicAirData/BluetoothHelper
它是安卓设备(客户端)和微控制器(服务器)之间的一个简单的基于消息的蓝牙无线通信层,可以与任何基于Arduino的微控制器和蓝牙接口(如廉价的HC-05)一起使用。
它是根据GPL-3条款获得许可的。
设置非常简单:
- 将蓝牙权限添加到AndroidManifest.xml:
<uses-permission android:name = "android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name = "android.permission.BLUETOOTH"/>
- 在活动中声明一个新的BluetoothHelper实例:
BluetoothHelper mBluetoothHelper = new BluetoothHelper();
- 设置BluetoothHelperListener以接收消息和连接状态的更改:
mBluetoothHelper.setBluetoothHelperListener(new BluetoothHelper.BluetoothHelperListener() {
@Override
public void onBluetoothHelperMessageReceived(BluetoothHelper bluetoothhelper, final String message) {
// Do something with the message received
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// // Update your UI
// }
// });
}
@Override
public void onBluetoothHelperConnectionStateChanged(BluetoothHelper bluetoothhelper, boolean isConnected) {
// Do something, depending on the new connection status
}
});
使用更简单:
- 使用配对设备连接:
mBluetoothHelper.Connect(mBluetoothDevice);
// mBluetoothHelper.Connect("HC-05"); <-- use it as alternative
- 发送消息:
mBluetoothHelper.SendMessage("Hello World");
- 检查连接状态:
mBluetoothHelper.isConnected();
- 断开连接
mBluetoothHelper.Disconnect();
GitHub页面上有很多文档,一个Android和Arduino代码的基本示例,以及一个简单但功能齐全的开源应用程序的链接,该应用程序使用HC-05与Arduino连接。