2012-06-28 86 views
4

我想檢查在使用Android應用程序的設備中是否啓用了藍牙。 我使用了.isEnabled方法。但是有一個錯誤。我發現(通過註釋行)錯誤在.isEnabled方法中。你能幫我解決這個問題嗎?檢查是否使用Android應用程序啓用藍牙

final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); 

submitButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     String status = "Bluetooth"; 

     if(bluetooth != null) { 
      if (bluetooth.isEnabled()) { 
       String mydeviceaddress = bluetooth.getAddress(); 
       String mydevicename = bluetooth.getName(); 
       status = ("Address "+ mydeviceaddress + " Name" + mydevicename); 
       Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show(); 
      } else { 
       status = ("Bluetooth not enabled"); 
       Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show(); 
      } 
     } else { 
      Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

回答

6

試試這個。

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
if (bluetoothAdapter == null) { 
    // Device does not support Bluetooth 
} else { 
    if (!bluetoothAdapter.isEnabled()) { 
     // Bluetooth is not enabled 
    } 
} 
AndroidManifest.xml File添加

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

我剛試過。但是這也不起作用:( – Saku

+0

@Saku有什麼錯誤?更新你的文章,並把錯誤的詳細信息 – Bishan

+0

'強制關閉'出現由於模擬器不支持藍牙我試着在一個實際的選項卡。 t給出明確的例外或錯誤信息 – Saku

17

這工作最適合我:

/** 
* Check for Bluetooth. 
* @return True if Bluetooth is available. 
*/ 
public static boolean isBluetoothAvailable() { 
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    return (bluetoothAdapter != null && bluetoothAdapter.isEnabled()); 
} 
+0

感謝您以最佳方式分享它... #makesense – CoDe

+2

只有一件事,爲什麼該方法需要一個Context對象,真的使用它嗎? – hmartinezd

+1

@hmartinezd好眼睛,現在已經修好了。 –

0

爲什麼不乾脆:

... 
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled(); 
0

賈裏德Burrows的答案似乎是正確的一個,但是我不得不一個dd在開始工作之前添加一個。我必須檢查藍牙狀態。

public static boolean isBluetoothAvailable() { 
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

    return (bluetoothAdapter != null && 
      bluetoothAdapter.isEnabled() && 
      bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON); 
}