リスト ビューからペアリングされた Bluetooth デバイスに接続しようとしましたが、正しく接続できないようです。私のコードは問題ないようですが、電話で実行しても何もしません。どんな助けでも大歓迎です。ありがとうございました。
import java.io.IOError;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.util.Set;
import java.util.UUID;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Devices extends ListActivity {
private ArrayAdapter<String> btArrayAdapter;
private BluetoothAdapter btAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
btAdapter = BluetoothAdapter.getDefaultAdapter();
getPairedDevices();
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
if(pairedDevices.size()>0){
for (BluetoothDevice device :pairedDevices){
String name = device.getName();
btArrayAdapter.add(name);
}
}
setListAdapter(btArrayAdapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Set<BluetoothDevice> device = btAdapter.getBondedDevices();
//System.out.println(device.getClass());
Thread ConnectThread = new Thread();
ConnectThread.start();
}
public class ConnectThread extends Thread{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp = null;
mmDevice = device;
try{
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e){}
mmSocket = tmp;
}
public void run(){
btAdapter.cancelDiscovery();
try{
mmSocket.connect();
}catch (IOException connectException){
try{
mmSocket.close();
}catch (IOException closeException){}
return;
}
//Work to manage connection
}
public void cancel(){
try{
mmSocket.close();
}catch (IOException e){}
}
}
}