Wednesday, October 09, 2013

Android Tip - Checking for Bluetooth LE Support


Bluetooth Low Energy (LE) devices has been out for quite sometime. However, support for Bluetooth LE was not available until Android 4.3. Even so, support for Bluetooth LE is still dependent on the hardware that you have running the Android 4.3.  For instance, the first generation of Nexus 7 does not support Bluetooth LE, even if you have upgraded it to Android 4.3.

Bluetooth LE is based on the Bluetooth 4.0 Specification. It is also commonly known as Bluetooth Smart.

In order to test if you device supports Bluetooth LE, add the following permissions and uses-feature element in the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.learn2develop.checkforble"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <uses-permission android:name=
        "android.permission.BLUETOOTH"/>
    <uses-permission android:name=
        "android.permission.BLUETOOTH_ADMIN"/>
   
    <uses-feature android:name="android.hardware.bluetooth_le"
        android:required="false"/>
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=
                "net.learn2develop.checkforble.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name=
                    "android.intent.action.MAIN" />
                <category android:name=
                    "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>


In the onCreate() method of your activity, use the hasSystemFeature() method from the PackageManager class to check if Bluetooth LE is supported:

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String msg;
        //---check to determine whether BLE is supported on
        // the device---
        if (!getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_BLUETOOTH_LE)) {
            msg = "Bluetooth LE not supported on this device";
            finish();
        } else {
            msg = "Congrats! Bluetooth LE is supported on " +
                  "this device!";
        }
        Toast.makeText(this, msg,
                Toast.LENGTH_SHORT).show();
    }

No comments: