2012-12-11 29 views
2

我已經使用BluetoothChat示例在我的應用程序中構建藍牙連接。應用程序正確連接,並正確存儲所有配對的設備,但丟失的連接未正確報告。BluetoothChat示例,無法識別丟失的連接

我的手機連接的設備由一個小電池供電,閒置約30秒後關閉。我想讓我的應用程序在該設備關閉時通知用戶。我認爲這將包含在BluetoothChat示例中,但我不認爲它是。

private class ConnectThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final BluetoothDevice mmDevice; 
    private String mSocketType; 

    public ConnectThread(BluetoothDevice device, boolean secure) { 

     mmDevice = device; 
     BluetoothSocket tmp = null; 
     mSocketType = secure ? "Secure" : "Insecure"; 

     try { 
      if (secure) { 
       tmp = device.createRfcommSocketToServiceRecord(MY_UUID 
         ); 
      } else { 
       tmp = device.createInsecureRfcommSocketToServiceRecord(
         MY_UUID); 
      } 
     } catch (IOException e) { 
      Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e); 
     } 
     mmSocket = tmp; 
    } 

    public void run() { 
     //Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType); 
     setName("ConnectThread" + mSocketType); 

     // Always cancel discovery because it will slow down a connection 
     mAdapter.cancelDiscovery(); 

     // Make a connection to the BluetoothSocket 
     try { 
      // This is a blocking call and will only return on a 
      // successful connection or an exception 
      mmSocket.connect(); 
     } catch (IOException e) { 
      // Close the socket 
      try { 
       mmSocket.close(); 
      } catch (IOException e2) { 
       Log.e(TAG, "unable to close() " + mSocketType + 
         " socket during connection failure", e2); 
      } 
      connectionFailed(); 
      return; 
     } 

     // Reset the ConnectThread because we're done 
     synchronized (BluetoothService.this) { 
      mConnectThread = null; 
     } 

     // Start the connected thread 
     connected(mmSocket, mmDevice, mSocketType); 
    } 

    public void cancel() { 
     RelayAPIModel.bluetoothConnected = false; 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { 
      Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e); 
     } 
    } 
} 

的ConnectedThread低於:

/** 
* This thread runs during a connection with a remote device. 
* It handles all incoming and outgoing transmissions. 
*/ 
private class ConnectedThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final InputStream mmInStream; 
    private final BufferedReader mmInBuffer; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket, String socketType) { 
     Log.d(TAG, "create ConnectedThread: " + socketType); 
     mmSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     // Get the BluetoothSocket input and output streams 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
     } catch (IOException e) { 
      Log.e(TAG, "temp sockets not created", e); 
     } 

     RelayAPIModel.bluetoothConnected = true; 
     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
     mmInBuffer = new BufferedReader(new InputStreamReader(mmInStream)); 
    } 

    public void run(int length) { 
     buffer = new byte[1024]; 


     // Keep listening to the InputStream while connected 
     //while (true) { 
      try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer, 0, length); 

       // Send the obtained bytes to the UI Activity 
       mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
      } catch (IOException e) { 

       Message msg = mHandler.obtainMessage(MainMenu.MESSAGE_TOAST); 
       Bundle bundle = new Bundle(); 
       bundle.putString(TOAST, "Device has disconnected from the Bluetooth Module."); 
       msg.setData(bundle); 
       mHandler.sendMessage(msg); 
       Log.e(TAG, "disconnected a", e); 
       connectionLost(); 

       // Start the service over to restart listening mode 
       BluetoothService.this.start(); 
       //break; 
      } 
     // } 
    } 

    /** 
    * Write to the connected OutStream. 
    * @param buffer The bytes to write 
    */ 
    public void write(byte[] buffer) { 
     try { 
      mmOutStream.write(buffer); 

      // Share the sent message back to the UI Activity 
      mHandler.obtainMessage(MainMenu.MESSAGE_WRITE, -1, -1, buffer) 
        .sendToTarget(); 
     } catch (IOException e) { 
      Log.e(TAG, "Exception during write", e); 
     } 
    } 

    public void cancel() { 
     RelayAPIModel.bluetoothConnected = false; 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { 
      Log.e(TAG, "close() of connect socket failed", e); 
     } 
    } 
} 

我也有這個功能connectionLost,如果一個異常在ConnectedThread抓到應該叫,但例外似乎從來沒有被抓住。

private void connectionLost() { 
    // Send a failure message back to the Activity 
    Message msg = mHandler.obtainMessage(MainMenu.MESSAGE_TOAST); 
    RelayAPIModel.bluetoothConnected = false; 
    Bundle bundle = new Bundle(); 
    bundle.putString(TOAST, "Device connection was lost"); 
    msg.setData(bundle); 
    mHandler.sendMessage(msg); 
    Log.i("Here.", "Connection Lost"); 
    // Start the service over to restart listening mode 
    BluetoothService.this.start(); 
} 

回答

3

在這裏,你在你的廣播接收機,覆蓋onRecieve獲得斷開意圖爲您的藍牙連接。

private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 

     if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { 
      //disconnect request 
     } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { 
      //disconnected, do what you want to notify user here, toast, or dialog, etc. 
     } 
    } 
} 
+0

非常感謝,但是我的所有藍牙功能都可以在我的所有活動中使用。從我可以在'BroadcastReceiver'上找到的我用'Intent'過濾器調用'this.registerReceiver(mReceiver,filter)',但這不適用於一個簡單的類。你有什麼想法,我會如何做一個簡單的類反對一個活動? – JuiCe

+0

我只是把一個接收器放在每一個活動中,謝謝你的幫助。 – JuiCe

+1

@JuiCe沒問題。儘管你說的是有效的,但並不是推薦的做事方式。從技術上講,您應該只在您的應用程序中註冊一個廣播接收器實例。然後發佈runnables/async任務和/或從單個類運行方法來影響您的整體應用程序。同樣,當你完成後(即應用程序關閉),你應該註銷你的接收器以釋放內存並避免未處理的回調,除非希望的效果是讓你的應用程序在後臺運行。無論如何,上述是一個單獨的討論/問題,而不是直接關係到這個問題和答案。 – logray