2013-09-24 28 views
0

我將使用2個活動的應用程序。開始或主要活動建立藍牙連接。當我切換到另一個活動時,我鬆開了藍牙連接。切換時可以保持藍牙連接嗎?這裏是OnResume()和onPause()。當我刪除onPause中的btSocket.close()時,連接被保持着,但在onResume嘗試連接時不會進行通信。交換意向

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { 
    if(Build.VERSION.SDK_INT >= 10){ 
     try { 
      final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class }); 
      return (BluetoothSocket) m.invoke(device, MY_UUID); 
     } catch (Exception e) { 
      Log.e(TAG, "Could not create Insecure RFComm Connection",e); 
     } 
    } 
    return device.createRfcommSocketToServiceRecord(MY_UUID); 
    } 

    @Override 
    public void onResume() { 
    super.onResume(); 

    Log.d(TAG, "...onResume - try connect..."); 

    BluetoothDevice device = btAdapter.getRemoteDevice(address); 


try { 
    btSocket = createBluetoothSocket(device); 
} catch (IOException e) { 
    errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); 
} 

btAdapter.cancelDiscovery(); 

try { 
    btSocket.connect(); 
    Log.d(TAG, "....Connection ok..."); 
} catch (IOException e) { 
    try { 
    btSocket.close(); 
    } catch (IOException e2) { 
    errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); 
    } 
} 

// Create a data stream so we can talk to server. 
Log.d(TAG, "...Create Socket..."); 

mConnectedThread = new ConnectedThread(btSocket); 
mConnectedThread.start(); 
} 

@Override 
public void onPause() { 
super.onPause(); 

Log.d(TAG, "...In onPause()..."); 

try  { 
    btSocket.close(); 
} catch (IOException e2) { 
    errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + "."); 
} 
} 

回答

0

你應該讓你的藍牙連接獨立於你的活動。我建議你把所有的藍牙代碼放到一個從MyApp應用類派生的'MyApp'類中,或者放到一個服務中。使用服務將變得更加複雜,但它會爲您提供選項,以便在用戶關閉活動後繼續運行應用程序,例如如果你想完成你的藍牙通信。

,你會發現多寫了兩個選項,因爲它們是常見的方法來構建你的應用程序 - 特別是當有某種形式的網絡通信。

+0

湯姆,謝謝你的提示。這裏是關於服務http://www.vogella.com/articles/AndroidServices/article.html的一些很好的信息 – Bobby