2013-02-17 78 views
0

我有以下代碼開始活動,代碼是當用戶點擊Android設備上的菜單按鈕時出現的子菜單,它的問題是,當按鈕被點擊一個新的活動開始了,這會丟失之前形成的藍牙連接!新的活動開始於意圖

@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     Intent serverIntent = null; 
     Intent PassIntent; 
     Intent PassIntent1; 
     switch (item.getItemId()) { 
     /*case R.id.home: 
      // Launch the DeviceListActivity to see devices and do scan 
      serverIntent = new Intent(this, engineStarter.class); 
      startActivity(serverIntent); 
      return true;*/ 
     /*case R.id.insecure_connect_scan: 
      // Launch the DeviceListActivity to see devices and do scan 
      serverIntent = new Intent(this, DeviceListActivity.class); 
      startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE); 
      return true;*/ 
     /*case R.id.discoverable: 
      // Ensure this device is discoverable by others 
      ensureDiscoverable(); 
      return true;*/ 
     case R.id.setpassword: 
      PassIntent = new Intent(this, SetPassword.class); 
      startActivity(PassIntent); 
      return true; 
     case R.id.home: 
      // Launch the DeviceListActivity to see devices and do scan 
      serverIntent = new Intent(this, engineStarter.class); 
      startActivity(serverIntent); 
      return true; 
     } 
     return false; 
    } 
+0

我真正想要的只是加載活動與以前的狀態,而不是再次創建活動性和鬆散的連接! – Naaz 2013-02-17 20:02:38

+0

爲什麼不通過服務來管理藍牙連接? – 2013-02-17 20:38:22

+0

我試過了,但我記得我被卡在某個地方,所以只是沒有這樣去! – Naaz 2013-02-17 21:05:55

回答

1

你有兩個選擇:

1-更改您的活動的啓動模式android:launchMode="singleTask",因此它不創建一個新的實例每次調用startActivity

2-時間保持你Bluetooth連接在一個service

還有另一種可能的解決方案,但可能不是優雅之一,是定義一個自定義的application類,你可以維護在這種情況下,Bluetooth連接將會緊挨着applicationContext

+0

謝謝我會嘗試一個使用singleTask的選項 – Naaz 2013-02-17 21:04:24

+0

「還有另一種可能的解決方案,但可能不太好,它是定義一個自定義應用程序類,您可以在其中維護藍牙連接」 - 我只是在做同樣的事情這一次,但我認爲我不會將它綁定到相同的背景下,你可以在這方面進一步闡述一下嗎? – Naaz 2013-02-17 21:05:22

+0

發佈你的代碼,因爲我不知道你在做什麼。 – iTech 2013-02-17 21:11:23

0

另一種方法是保持相同的Activity,但將新的fragments加載到替換當前片段的活動中。使用FragmentManager時,您可以將新片段推送到堆棧以向前導航並將其彈出以向後導航。這將允許您瀏覽內容並保持藍牙連接。