最初に、私のAndroidデバイスはBluetoothデバイスをスキャンしてから、リストビューに表示します。そのうちの1つを選択すると、新しい画面が表示されます。接続が失われたときにメイン画面に戻る方法。以下は、選択したデバイス画面のコードです。
public class devicefound extends Activity implements OnClickListener {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button b1;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static String address;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.b1).setOnClickListener(this);
b1 = (Button) findViewById(R.id.b1);
}
@Override
public void onStart() {
super.onStart();
String address = getIntent().getStringExtra("address");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
run();
}
public void run(){
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) { }
return;
}
}
public void onClick(View v){
String message1 = "1";
byte[] msgBuffer1 = message1.getBytes();
try{
outStream = btSocket.getOutputStream();
} catch (IOException e){ }
try {
outStream.write(msgBuffer1);
} catch (IOException e) {
}
}
}
@Override
public void onPause() {
super.onPause();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) { }
}
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}