Java I';我正在尝试在Android Studio中实现蓝牙功能,在连接问题上需要一些帮助
我使用了Bluetooth API,下面的代码用于打开/关闭、显示配对设备列表和连接配对设备。 其他功能运行良好,但连接设备不起作用。 我尝试使用线程双向,当蓝牙打开时,serverthread(acceptthread)生成并启动。当我在列表中选择设备时,clientthread(connectthread)生成并启动。这是我的意图,但当我尝试在手机上连接时,应用程序被关闭(几乎在客户端,偶尔在服务器上)。 我想可能是UUID问题,所以我检查了UUID 00Java I';我正在尝试在Android Studio中实现蓝牙功能,在连接问题上需要一些帮助,java,android,multithreading,bluetooth,Java,Android,Multithreading,Bluetooth,我使用了Bluetooth API,下面的代码用于打开/关闭、显示配对设备列表和连接配对设备。 其他功能运行良好,但连接设备不起作用。 我尝试使用线程双向,当蓝牙打开时,serverthread(acceptthread)生成并启动。当我在列表中选择设备时,clientthread(connectthread)生成并启动。这是我的意图,但当我尝试在手机上连接时,应用程序被关闭(几乎在客户端,偶尔在服务器上)。 我想可能是UUID问题,所以我检查了UUID 00enter code here001
enter code here
001101-0000-1000-8000-00805F9B34FB,但没有帮助。enter code here
很抱歉导入代码块,我非常感谢您的帮助
'''
package com.practice.bluetoothmodule;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
TextView bthStatus;
Button bthOn;
Button bthOff;
Button bthCon;
BluetoothAdapter bthAdapter;
Set<BluetoothDevice> pairedDevices;
List<String> listofPairedDevices;
private String btAddress=null;
BluetoothDevice bthDevice;
AcceptThread acceptThread;
ConnectThread connectThread;
private Handler mHandler = null;
final static int BT_REQUEST_ENABLE=1;
final static UUID BT_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bthStatus = (TextView)findViewById(R.id.text_check);
bthOn = (Button)findViewById(R.id.bth_on);
bthOff=(Button)findViewById(R.id.bth_off);
bthCon=(Button)findViewById(R.id.dev_con);
bthAdapter=BluetoothAdapter.getDefaultAdapter();
bthOn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View view){
bluetoothOn();
}
});
bthOff.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View view){
bluetoothOff();
}
});
bthCon.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View view){
listPairedDevices();
}
});
}
@Override
public void onStart(){
super.onStart();
}
@Override
public void onDestroy(){
super.onDestroy();
if(acceptThread != null){
acceptThread.cancel();
acceptThread=null;
}
if(connectThread != null){
connectThread.cancel();
connectThread=null;
}
}
void bluetoothOn(){
if(bthAdapter == null){
Toast.makeText(getApplicationContext(),"블루투스를 지원하지 않는 기기입니다",Toast.LENGTH_SHORT).show();
}
else{
if(bthAdapter.isEnabled()){
Toast.makeText(getApplicationContext(),"블루투스가 이미 활성화된 상태입니다",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 활성화 되어 있지 않습니다",Toast.LENGTH_SHORT).show();
Intent intentBthEnable = new Intent(bthAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intentBthEnable,BT_REQUEST_ENABLE);
}
}
}
void bluetoothOff(){
if(bthAdapter.isEnabled()){
bthAdapter.disable();
Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되었습니다.",Toast.LENGTH_SHORT).show();
bthStatus.setText("비활성화");
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 이미 비활성화 상태입니다",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
switch(requestCode){
case BT_REQUEST_ENABLE:
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(),"블루투스 활성화",Toast.LENGTH_LONG).show();
bthStatus.setText("활성화");
start();
} else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"취소",Toast.LENGTH_LONG).show();
bthStatus.setText("비활성화");
}
break;
}
super.onActivityResult(requestCode,resultCode,data);
}
void listPairedDevices(){
if(bthAdapter.isEnabled()){
pairedDevices = bthAdapter.getBondedDevices();
if(pairedDevices.size()>0){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("장치 선택");
listofPairedDevices = new ArrayList();
for(BluetoothDevice device: pairedDevices){
listofPairedDevices.add(device.getName());
}
final CharSequence[] items= listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);
listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
connectSelectedDevice(items[item].toString());
}
});
AlertDialog alert=builder.create();
alert.show();
}
else{
Toast.makeText(getApplicationContext(),"페어링된 장치가 없습니다",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되어 있습니다.",Toast.LENGTH_LONG).show();
}
}
void connectSelectedDevice(String selectedDeviceName){
for(BluetoothDevice tempDevice: pairedDevices){
if(selectedDeviceName.equals(tempDevice.getName())){
bthDevice=tempDevice;
btAddress=bthDevice.getAddress();
break;
}
}
connect(bthDevice);
//Toast.makeText(getApplicationContext(),"연결 시도"+bthDevice.getName(),Toast.LENGTH_LONG).show();
}
public synchronized void start(){
acceptThread = new AcceptThread();
acceptThread.start();
}
public synchronized void connect(BluetoothDevice device){
connectThread=new ConnectThread(device);
connectThread.start();
}
private class AcceptThread extends Thread{
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp=null;
try{
tmp=bthAdapter.listenUsingRfcommWithServiceRecord("Listen",BT_UUID);
Toast.makeText(getApplicationContext(),"서버 열림",Toast.LENGTH_LONG).show();
}catch(IOException e){
Toast.makeText(getApplicationContext(),"서버 안열림",Toast.LENGTH_LONG).show();
}
mmServerSocket=tmp;
}
public void run(){
BluetoothSocket socket=null;
while(true){
try{
socket=mmServerSocket.accept();
} catch(IOException e){
break;
}
if(socket != null){
Toast.makeText(getApplicationContext(),"연결됨",Toast.LENGTH_SHORT).show();
try{
sleep(3000);
} catch (Exception e){}
}
}
}
public void cancel(){
try{
mmServerSocket.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
private class ConnectThread extends Thread{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp=null;
mmDevice=device;
try{
tmp=device.createRfcommSocketToServiceRecord(BT_UUID);
//Toast.makeText(getApplicationContext(),"클라 초기화 됨.",Toast.LENGTH_LONG).show();
}catch (IOException e){
//Toast.makeText(getApplicationContext(),"클라 초기화 실패.",Toast.LENGTH_LONG).show();
}
mmSocket=tmp;
//Toast.makeText(getApplicationContext(),"클라 초기화",Toast.LENGTH_LONG).show();
}
public void run() {
try {
bthAdapter.cancelDiscovery();
mmSocket.connect();
Toast.makeText(getApplicationContext(), "클라이언트 연결", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "연결실패", Toast.LENGTH_LONG).show();
}
}
public void cancel(){
try{
mmSocket.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
'''
“”
包com.practice.bluetoothmodule;
导入androidx.appcompat.app.AlertDialog;
导入androidx.appcompat.app.appcompat活动;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothServerSocket;
导入android.bluetooth.BluetoothSocket;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.SystemClock;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.io.UnsupportedEncodingException;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Set;
导入java.util.UUID;
导入java.util.concurrent.ExecutionException;
公共类MainActivity扩展了AppCompatActivity{
文本视图bthStatus;
按钮按钮;
巴顿霍夫;
按钮bthCon;
蓝牙适配器;
设置配对设备;
成对设备列表;
私有字符串btAddress=null;
蓝牙设备;
接受线程接受线程;
连接螺纹连接螺纹;
私有处理程序mHandler=null;
最终静态int BT_请求_启用=1;
最终静态UUID BT_UUID=UUID.fromString(“fa87c0d0-afac-11de-8a39-0800200c9a66”);
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bthStatus=(TextView)findViewById(R.id.text\u检查);
bthOn=(按钮)findViewById(R.id.bth_on);
bthOff=(按钮)findViewById(R.id.bth_off);
bthCon=(按钮)findViewById(R.id.dev\u con);
bthAdapter=BluetoothAdapter.getDefaultAdapter();
bthOn.setOnClickListener(新建按钮.OnClickListener(){
@凌驾
公共void onClick(视图){
蓝牙();
}
});
bthOff.setOnClickListener(新建按钮.OnClickListener(){
@凌驾
公共void onClick(视图){
bluetoothOff();
}
});
setOnClickListener(新建按钮.OnClickListener(){
@凌驾
公共void onClick(视图){
listPairedDevices();
}
});
}
@凌驾
public void onStart(){
super.onStart();
}
@凌驾
公共空间{
super.ondestory();
if(acceptThread!=null){
acceptThread.cancel();
acceptThread=null;
}
if(connectThread!=null){
connectThread.cancel();
connectThread=null;
}
}
虚空蓝牙(){
if(bthAdapter==null){
Toast.makeText(getApplicationContext(),”블루투스를 지원하지 않는 기기입니다",吐司。长度(短)。show();
}
否则{
if(bthAdapter.isEnabled()){
Toast.makeText(getApplicationContext(),”블루투스가 이미 활성화된 상태입니다“,Toast.LENGTH_SHORT).show();
}
否则{
Toast.makeText(getApplicationContext(),”블루투스가 활성화 되어 있지 않습니다“,Toast.LENGTH_SHORT).show();
意向意向书表格=新意向书(bthAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(可管理、BT请求和启用);
}
}
}
void bluetoothOff(){
if(bthAdapter.isEnabled()){
bthAdapter.disable();
Toast.makeText(getApplicationContext(),”블루투스가 비활성화 되었습니다.“,Toast.LENGTH_SHORT).show();
bthStatus.setText(“비활성화");
}
否则{
Toast.makeText(getApplicationContext(),”블루투스가 이미 비활성화 상태입니다“,Toast.LENGTH_SHORT).show();
}
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
开关(请求代码){
案例BT_请求_启用:
if(resultCode==RESULT\u OK){
Toast.makeText(getApplicationContext(),”블루투스 활성화“,Toast.LENGTH_LONG).show();
bthStatus.setText(“활성화");
start();
}else if(resultCode==RESULT\u取消){
Toast.makeText(getApplicationContext(),”취소“,Toast.LENGTH_LONG).show();
bthStatus.setText(“비활성화");
}
打破
}
super.onActivityResult(请求代码、结果代码、数据);
}
void listPairedDevices(){
if(bthAdapter.isEnabled()){
pairedDevices=bthAdapter.getBondedDevices();
如果(pairedDevices.size()>0){
AlertDialog.Builder=新建AlertDialog.Builder(此);
builder.setTitle(“장치 선택");
listofPairedDevices=new ArrayList();
用于(蓝牙设备:pairedDevices){
空气列表