首先,我的 android 设备会扫描蓝牙设备,然后将它们显示在列表视图中。我选择其中一个,然后出现一个新屏幕。断开连接时如何返回主屏幕。以下是所选设备屏幕的代码。
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();
}
}