2011-10-06 130 views
50

我想檢查是否在任何Android設備上定期啓用藍牙。有沒有我可以用BroadcastReceiver來捕捉的意圖,還是有其他方法可以做到這一點?如何檢查藍牙是否以編程方式啓用?

+0

只是檢查出這個[鏈接](http://developer.android.com/guide/topics/wireless/bluetooth.html#SettingUp),並遵守所有的步。我希望這個幫助。 – Uttam

回答

124

你去那裏:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
if (mBluetoothAdapter == null) { 
    // Device does not support Bluetooth 
} else { 
    if (!mBluetoothAdapter.isEnabled()) { 
     // Bluetooth is not enable :) 
    } 
} 

隨着uses-permission

<uses-permission android:name="android.permission.BLUETOOTH" android:required="false" /> 
+0

感謝您的簡短答覆! – androidnoob

+7

如果需要藍牙許可才能進行此檢測,請不要忘記將其設置爲不需要: Murphy

+0

最佳方式http: //stackoverflow.com/a/21010026/2624806 :) – CoDe

6

在這裏,我有其他的選擇,因爲這個問題的答案。

首先在您的Manifest文件中添加以下行。

<uses-feature android:name="android.hardware.BLUETOOTH" android:required="false"/> 

現在,您要檢查藍牙支持能力的位置,請使用以下代碼。

boolean isBluetoothSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH); 
+0

它與「BluetoothAdapter.getDefaultAdapter()」有什麼不同? – CoDe

+1

我認爲android:require應該是false。因爲它只會在那些支持藍牙的設備上工作。 –

+1

這個錯字讓我哭了。我必須解決它。 – rekire

2

使用可以使用

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

用於檢查BT連接

mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED 

用於檢查BT斷開

mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_DISCONNECTED 
+0

問題不在於檢查是否連接了耳機,但是我正在查找這個,所以+1和謝謝:) – Alexandr

2

要檢查藍牙狀態,ON或OFF,編程:

BluetoothAdapter btAdapter = ((Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) 
      ?((BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter() 
       :(BluetoothAdapter.getDefaultAdapter())); 

     if(btAdapter==null){ 
     return; 
     } 
     if(btAdapter.getState()==BluetoothAdapter.STATE_ON){ 
      //Bluetooth is ON 
     } 

您還可以收聽意圖的行動:

BluetoothAdapter.ACTION_STATE_CHANGED

1

這是我如何與@ xjaphx的答案的幫助下做到了,稍作簡化版本:

private boolean getBlueToothOn(){ 
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); 
     return btAdapter != null && btAdapter.isEnabled(); 
    } 

<uses-permission android:name="android.permission.BLUETOOTH" /> 
4
public boolean isBluetoothEnabled() 
    { 
     BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     return mBluetoothAdapter.isEnabled(); 

    } 

在manifest文件權限:藍牙

<uses-permission android:name="android.permission.BLUETOOTH" /> 
相關問題