2012-03-25 89 views
1

當前我正嘗試設置一個應用程序讓兩個設備通過藍牙進行通信。更改藍牙可發現性時不發送廣播

我有一個屏幕顯示單個Button。點擊這個按鈕可以讓設備發現並禁用按鈕。當設備不再可被發現時,該按鈕應該被再次啓用。

就像在Dev Guide中建議的那樣,我註冊BroadcastReceiver,當可發現性結束時通知。

問題:

有時候,我不要當設備不再發現接收任何廣播。另一方面,我通常在進入可發現性時發送2個廣播。 Discoverability正常工作,由LogCat和設備在120秒內看到我的手機(HTC Desire HD)證明。

這是logcat的紀錄展示在立即得到2個廣播開始可發現後:

03-25 23:01:47.557: INFO/System.out(16905): --------broadcast received------------- 
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): current scan mode: 21 
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): previous scan mode: 23 
03-25 23:01:47.557: INFO/System.out(16905): --------broadcast received------------- 
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): current scan mode: 23 
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): previous scan mode: 21 

我的代碼開始可發現如下:

private void becomeVisible() { 

    Intent discoverableIntent = new Intent(
      BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
    startActivityForResult(discoverableIntent, 
      CODE_REQUEST_MAKE_DISCOVERABLE); 

} 

BroadcastReceiver看起來是這樣的:

private final BroadcastReceiver discoverableModeChangedReceiver = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     System.out.println("--------broadcast received-------------"); 
     int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, 
       0); 
     int scanModePrevious = intent.getIntExtra(
       BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, 0); 
     Log.d(TAG, "current scan mode: " + scanMode); 
     Log.d(TAG, "previous scan mode: " + scanModePrevious); 

     if (scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { 
      // show button 
      findViewById(R.id.btn_become_visible).setEnabled(false); 
     } else { 
      // hide button 
      findViewById(R.id.btn_become_visible).setEnabled(true); 
     } 
    } 
}; 

回答

2

您必須註冊操作第一個:

IntentFilter intent = new IntentFilter(); 
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); 
registerReceiver(discoverableModeChangedReceiver, intent); 
+0

接收方已註冊。你知道這是否只是我的手機上的問題(慾望高清)? – 2012-07-15 20:38:07