2012-09-05 47 views
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(); 

} 

} 
+0

好吧,您可能已經知道了這一點,但我會先監視您在服務中設置的BluetoothAdapter的狀態。從那裏你可以使用onBind方法將消息發送回當前活動以調用onBackPressed()。我認爲這肯定會讓你在正確的方向去http://developer.android.com/reference/android/app/Service.html#LocalServiceSample :) – Christopher

回答

0

如果你想返回到前一個屏幕,那麼你可以調用你的devicefound類從Activity繼承的finish方法。

相關問題