2013-08-23 127 views
2

我正在開發藍牙應用程序。在我的應用程序中,我有以下代碼。當藍牙關閉意味着我的else語句開關藍牙發現設備列表(它工作正常)否則如果語句將運行並獲取設備列表。藍牙發現不起作用

My problem is "if condition is runnning but it doesn't discover the devices" 

。任何人都可以提出解決方案。

if (btAdapter.isEnabled()) { 

     registerReceiver(ActionFoundReceiver, new IntentFilter(
       BluetoothDevice.ACTION_FOUND)); 
     btAdapter.startDiscovery(); 
    } else { 
     Intent i1 = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivity(i1); 

     new java.util.Timer().schedule(new java.util.TimerTask() { 
      @Override 
      public void run() { 
       registerReceiver(ActionFoundReceiver, new IntentFilter(
         BluetoothDevice.ACTION_FOUND)); 
       btAdapter.startDiscovery(); 
      } 
     }, 5000); 

    } 

//接收器檢測設備代碼

private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() { 

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

     String action = intent.getAction(); 

     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      BluetoothDevice device = intent 
        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      items += device.getName() + ","; 

     } 
     Toast.makeText(getApplicationContext(), items, Toast.LENGTH_LONG) 
       .show(); 
    } 

}; 

回答

1

我想,這裏正是你所需要的。

http://developer.android.com/guide/topics/wireless/bluetooth.html#FindingDevices

http://developer.android.com/guide/topics/wireless/bluetooth.html#DiscoveringDevices

關於啓用藍牙而不詢問用戶,這裏是什麼醫生說:

Bluetooth should never be enabled without direct user consent. If you 

want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app. 

但如果你真的想這樣做,有辦法:

BluetoothAdapter.enable()

您可以撥打這個不要求用戶

爲了使能()工作,您必須在Android清單文件

「android.permission.BLUETOOTH_ADMIN」

嘗試將其添加權限,

getApplicationContext().registerReceiver(receiver, 
        new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED)); 
getApplicationContext().registerReceiver(receiver, 
        new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); 
+0

感謝您的答覆......已經提到上面的鏈接...我的問題是在如果condition..in如果發現條件不存在的設備列表... – Aravin

+0

沒有發生一樣... 。 – Aravin