蓝牙连接丢失时如何返回上一屏幕?

时间:2012-09-05 14:13:47

标签: android bluetooth

首先,我的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();

}

}

2 个答案:

答案 0 :(得分:0)

据我所知,你应该在这种情况下使用BroadcastReceiver。 像这样http://android-er.blogspot.com/2011/05/start-bluetooth-discoverable-and.html

答案 1 :(得分:0)

如果要返回上一个屏幕,则可以调用devicefound类从Activity继承的finish方法。