2013-02-04 16 views
0

這是我正在嘗試使用的代碼。你能告訴我這是什麼問題嗎?如何在android簡單代碼上自動啓用藍牙基礎?

我的代碼:

public void onStart() { 
    super.onStart(); 
    if(D) Log.e(TAG, "++ ON START ++"); 
     BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
      if (!mBluetoothAdapter.isEnabled()) { 

      }else{ 
       mBluetoothAdapter.enable(); 
      } ; 
    } { 
     if (mChatService == null) setupChat(); 

} 

回答

0

您有什麼問題?我的猜測是你需要將BLUETOOTH和BLUETOOTH_ADMIN權限都添加到你的應用程序中。

注意首選的解決方案是使用的意圖,提示用戶要啓用藍牙:

 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivity(enableIntent); 

還要注意的是調用enable是異步的,它會立即返回,並在啓用藍牙背景。因此藍牙可能實際上並未啓用,它可能仍在準備中。另請參見the Android guidelines on Bluetooth

編輯添加禁用/等待/啓用/等待示例代碼

這是請求藍牙關閉,然後等待它打開示例代碼。它必須運行在一個單獨的線程和而不是在UI線程中。可以將其封裝在Runnable類中,如果它成功完成,則將(最好是volatile)標誌設置爲true。

備註:此示例代碼在某些較舊的設備上存在問題,這些設備不允許從用戶應用程序調用diable/enable。

  BluetoothAdapter.getDefaultAdapter().disable(); 
      while (BluetoothAdapter.getDefaultAdapter().isEnabled()) 
      { 
       try 
       { 
        Thread.sleep(100L); 
       } 
       catch (InterruptedException ie) 
       { 
        // unexpected interruption while disabling Bluetooth 
        Thread.currentThread().interrupt(); // restore interrupted flag 
        return; 
       } 
      } 
      // disabled, re-enabling Bluetooth 
      BluetoothAdapter.getDefaultAdapter().enable(); 
      while (!BluetoothAdapter.getDefaultAdapter().isEnabled()) 
      { 
       try 
       { 
        Thread.sleep(100L); 
       } 
       catch (InterruptedException ie) 
       { 
        // unexpected interruption while enabling bluetooth 
        Thread.currentThread().interrupt(); // restore interrupted flag 
        return; 
       } 
      } 
+0

如何在藍牙自動開啓,而不要求用戶基礎上的簡單的代碼? –

+0

@DanielTang正如我所說的,確保你的清單中有'BLUETOOTH'和'BLUETOOTH_ADMIN'權限,那麼你可以調用'mBluetoothAdapter.enable()',但是如果你想立即使用藍牙,你需要等到'mBluetoothAdapter.isEnabled()'爲真,可能需要幾秒鐘。 –

+0

我確定我有BLUETOOTH和BLUETOOTH_ADMIN權限。你的意思是我可以取消mBluetoothAdapter.isEnabled()來啓用藍牙非常快速? –

0
public class MainActivity extends Activity 
{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
     if (mBluetoothAdapter.isEnabled()) { 
      mBluetoothAdapter.disable(); 
     } 
     else(!mBluetoothAdapter.isEnabled()) { 
      mBluetoothAdapter.enable(); 
     } 
    } 
}