cz.cvut.sedekpav.cordova.bleplugin.BLEPlugin.java Source code

Java tutorial

Introduction

Here is the source code for cz.cvut.sedekpav.cordova.bleplugin.BLEPlugin.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.cvut.sedekpav.cordova.bleplugin;

import android.bluetooth.BluetoothDevice;
import java.util.List;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Root
 */
public class BLEPlugin extends CordovaPlugin {

    public static final String ACTION_LIST_DEVICES = "listDevices";

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        try {
            if (ACTION_LIST_DEVICES.equals(action)) {
                JSONObject arg_object = args.getJSONObject(0);
                BLE ble = new BLE(cordova.getActivity());
                /*            Intent calIntent = new Intent(Intent.ACTION_EDIT)
                 .setType("vnd.android.cursor.item/event")
                 .putExtra("beginTime", arg_object.getLong("startTimeMillis"))
                 .putExtra("endTime", arg_object.getLong("endTimeMillis"))
                 .putExtra("title", arg_object.getString("title"))
                 .putExtra("description", arg_object.getString("description"))
                 .putExtra("eventLocation", arg_object.getString("eventLocation"));
                 this.cordova.getActivity().startActivity(calIntent);*/
                List<BluetoothDevice> devs = ble.listBluetoothDevices();

                JSONArray jArray = new JSONArray();
                for (BluetoothDevice dev : devs) {
                    JSONObject json = new JSONObject();
                    json.put("address", dev.getAddress().toString());
                    json.put("name", dev.getName());
                    jArray.put(json);
                }

                callbackContext.success(jArray);
                return true;
            }
            callbackContext.error("Invalid action");
            return false;
        } catch (Exception e) {
            System.err.println("Exception: " + e.getMessage());
            callbackContext.error(e.getMessage());
            return false;
        }
    }
}