2011-05-19 104 views
2

我正嘗試通過藍牙從桌面應用程序(用Java編寫)連接到Android應用程序。
對於我正在使用的桌面應用程序BlueCove API。
當我啓動服務器(桌面應用程序)並啓動Android應用程序時,連接工作正常。 (即,客戶端發送「Hello World」,服務器將其打印在控制檯中)。但是,當我離開應用程序時(通過按「返回」或「主頁」按鈕)並返回到它,套接字連接似乎已丟失。
爲什麼我會失去藍牙客戶端/服務器連接?

如何檢查藍牙插座是否已連接?
我想檢查套接字的連接到沒有再次連接。

我應該在,onResume方法中寫什麼(如果是這種情況)?
我想在onDestroy方法我應該關閉套接字。

下面是客戶端服務器的源代碼:
Server
Client

我使用IntentFilter檢查連接的狀態也嘗試過,但沒有奏效。

@Override 
    public void onCreate(Bundle savedInstanceState) { 
      // ..... 

     IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); 
     IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); 
     IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); 
     this.registerReceiver(mReceiver, filter1); 
     this.registerReceiver(mReceiver, filter2); 
     this.registerReceiver(mReceiver, filter3); 

} 

//The BroadcastReceiver that listens for bluetooth broadcasts 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      //Device found 
      Toast.makeText(BluetoothClient.this, "Device not found", 2).show(); 
     } 
     else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { 
      //Device is now connected 
      Toast.makeText(BluetoothClient.this, "Device connected", 2).show(); 
     } 
     else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
      //Done searching 
      Toast.makeText(BluetoothClient.this, "Done searching", 2).show(); 
     } 
     else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { 
      //Device is about to disconnect 
      Toast.makeText(BluetoothClient.this, "Device about to connect", 2).show(); 
     } 
     else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { 
     //Device has disconnected 
      Toast.makeText(BluetoothClient.this, "Device disconnected", 2).show(); 
     }   
    } 
}; 
+0

你會得到什麼錯誤?我已經看到你已經在UI和Log中都輸入了一些錯誤消息。 – garzanti 2011-05-21 05:17:04

+0

客戶端應用程序在它再次啓動時失敗: 'Log.d(TAG,「即將連接」); socket.connect();' 它被卡在connect()方法中的套接字 – sfat 2011-05-21 06:08:06

+0

那麼,從我的角度來看,客戶端可以在與服務器同時打開更多套接字。所以出於某種原因服務器拒絕創建另一個連接。我相信你會遇到異常情況,將複製/粘貼到堆棧跟蹤的內容會很棒。無論如何,我的觀點是,除非你離開你的應用程序,否則每次在OnCreate上重新創建連接都是不好的。你應該有一個外部的單身人士。 – garzanti 2011-05-21 08:18:26

回答

6

Server
Client

我已修改2的源代碼文件。
現在它應該可以正常工作。如果BT在進入移動應用程序之前沒有打開(它會在一段時間內卡住太多),並且對於想要使用此客戶端/服務器的用戶,您應該查看onPause(), onResume(), onDestroy()的功能。

問題是我沒有正確使用套接字。

我希望它對那些想要用BT實現這樣的應用程序的人有用。

+1

太棒了!它很棒! – kinghomer 2012-05-04 10:49:41

相關問題