0

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

}

}
4

2 回答 2

0

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

于 2012-09-05T14:21:48.107 回答
0

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

于 2012-09-05T14:19:36.403 回答