Search code examples
javaandroidcordovabluetoothcordova-plugins

How can I write an android cordova plugin that will return 1 if bluetooth is on and 0 otherwise?


I'm currently reading through the cordova documentation and found the basic outline is as follows:

package org.apache.cordova.plugin;

import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class Echo extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("echo")) {
            String message = args.getString(0); 
            this.echo(message, callbackContext);
            return true;
        }
        return false;
    }

    private void echo(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) { 
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}

This makes a lot of sense, and I understand how Java code can be executed and dispatch information back to the calling javascript.

However, I don't see how I can access the api within android that tells me whether bluetooth is turned on or off. Would I have to import android packages? Is there documentation on this topic?

Thanks for any help


Solution

  • Yes you will need to import BluetoothManager and BluetoothAdapter.

    Something like this:

    import android.bluetooth.BluetoothManager;
    import android.bluetooth.BluetoothAdapter;
    
    ...
    
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    private BluetoothAdapter mBluetoothAdapter;
    
    ...
    
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
        // BLUETOOTH is NOT SUPPORTED
        //use PackageManager.FEATURE_BLUETOOTH_LE if you need bluetooth low energy
        return false;
    } else {
        mBluetoothAdapter = bluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            // BLUETOOTH is NOT AVAILABLE
            return false;
        } else {
            if (mBluetoothAdapter.isEnabled())
                // BLUETOOTH is TURNED ON
                return true;
            else 
                // BLUETOOTH is TURNED OFF
                return false;
        }
    }
    

    You can read about it more: