我正在构建一个用于在移动设备上显示心电图的应用程序,所以我尝试 通过蓝牙建立连接。但是当我尝试配对时 蓝牙,显示已配对的设备。但是当我尝试连接时 说找不到设备。.我不知道如何解决问题。请 建议我的代码中的问题以连接配对设备: 这将不胜感激
这是我的bluetooth.java
public class bluetooth extends Activity implements AdapterView.OnItemClickListener {
public static void disconnect(){
if (connectedThread !=null){
connectedThread.cancel();
connectedThread= null;
}
}
public static void gethandler(Handler handler){
mHandler= handler;
}
static Handler mHandler =new Handler();
static ConnectedThread connectedThread;
public static final UUID my_UUID= UUID.fromString("f53a07d4-3010-11e9-b210-d663bd873d93");
protected static final int SUCCESS_CONNECT=0;
protected static final int MESSAGE_READ=1;
ListView listView;
//ArrayAdapter is an Android SDK class for adapting an array of objects as a datasource.
// Adapters are used by Android to treat a result set uniformly whether it's from a database, file, or in-memory objects
// so that it can be displayed in a UI element.
// The ArrayAdapter is useful for the latter. Use it anywhere you would use an Adapter. E.g. attach to Android UI elements.
ArrayAdapter<String> list_adapter;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
///ArrayList is an implementation of java.util.List that's backed by an array. You can use it anywhere you would use a java.util.List.
//// E.g. where you need to maintain order of a collection of objects where duplicates are allowed.
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devies;
IntentFilter filter;
BroadcastReceiver receiver;
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//in Android the visual design is created in xml . And each Activity is associated to a design
//
//setContentView(R.layout.main)
//R means Resource
//
//layout means design
//
//main is the xml you have created under res->layout->main.xml
//
//Whenever you want to change your current Look of an Activity or when you move from
// one Activity to another . The other Activity must have a design to show . So we call this method in onCreate
// and this is the second statement to set the design
setContentView(R.layout.activity_bluetooth);
init();
if(btAdapter==null){
Toast.makeText(getApplicationContext(),"no bt detected", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onCreate: no");
finish();
}
else{
if(!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void getPairedDevices(){
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT(){
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
}
private void startDiscovery(){
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
String s="";
list_adapter.add(device.getName()+" "+s+""+"\n"+device.getAddress());
}
}
}
private void init() {
listView =(ListView)findViewById(R.id.list_item);
listView.setOnItemClickListener(this);
list_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listView.setAdapter(list_adapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices =new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devies = new ArrayList<BluetoothDevice>();
receiver =new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action =intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devies.add(device); //!!!!!!!!!!
String s="";
for (int a=0;a<pairedDevices.size();a++){
if(device.getName().equals(pairedDevices.get(a))){
s="(paired)";
break;
}
}
list_adapter.add(device.getName()+" "+s+""+"\n"+device.getAddress());
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState()==btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(list_adapter.getItem(position).contains("(paired)")){
BluetoothDevice selectedDevice = devies.get(position);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
else{
Toast.makeText(getApplicationContext(),"device not paired", Toast.LENGTH_SHORT).show();
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice=device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(my_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discover y because it will slow down the connection
btAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
//connectedThread = new ConnectedThread(mmSocket);
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
// Incoming and the outgoing strings are carried out inside this thread read is for reading incoming messages through a socket and write is for sending messages to the remote device
static class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
// socket not created
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
StringBuffer sbb = new StringBuffer();
public void run() {
byte[] buffer ;
int bytes;
// receiving message
while(true) {
try {
try {
sleep(30);
} catch (InterruptedException e) {
break;
}
buffer = new byte[1024];
// Read from the InputStream
bytes = mmInStream.read(buffer);
// message is in bytes form so reading them to obtain message
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
// connection was lost and start your connection again
Log.e(TAG, "disconnected", e);
break;
}
}
}
public void write(String income) {
try {
mmOutStream.write(income.getBytes());
for (int i=0;i<income.getBytes().length;i++)
Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
try{
Thread.sleep(20);
}
catch (InterruptedException e1){
e1.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void cancel(){
try {
mmSocket.close();
}
catch (IOException e){}
}
}
}
但是我的问题是,mmsocket是否有问题
我在Android手机中像beow一样跳动。