Example usage for android.bluetooth BluetoothAdapter STATE_TURNING_OFF

List of usage examples for android.bluetooth BluetoothAdapter STATE_TURNING_OFF

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter STATE_TURNING_OFF.

Prototype

int STATE_TURNING_OFF

To view the source code for android.bluetooth BluetoothAdapter STATE_TURNING_OFF.

Click Source Link

Document

Indicates the local Bluetooth adapter is turning off.

Usage

From source file:Main.java

static public String state2String(int state) {
    final String ON = "STATE_ON";
    final String OFF = "STATE_OFF";
    final String TURNING_ON = "STATE_TURNING_ON";
    final String TURNING_OFF = "STATE_TURNING_OFF";

    switch (state) {
    case BluetoothAdapter.STATE_ON:
        return ON;
    case BluetoothAdapter.STATE_OFF:
        return OFF;
    case BluetoothAdapter.STATE_TURNING_ON:
        return TURNING_ON;
    case BluetoothAdapter.STATE_TURNING_OFF:
        return TURNING_OFF;
    default:/*from www.ja v a2s.c om*/
        return UNKNOWN;
    }
}

From source file:Main.java

public static String getStateString(int state) {
    switch (state) {
    case BluetoothAdapter.STATE_CONNECTED:
        return "Connected";
    case BluetoothAdapter.STATE_CONNECTING:
        return "Connecting";
    case BluetoothAdapter.STATE_DISCONNECTED:
        return "Disconnected";
    case BluetoothAdapter.STATE_DISCONNECTING:
        return "Disconnecting";
    case BluetoothAdapter.STATE_OFF:
        return "Off";
    case BluetoothAdapter.STATE_ON:
        return "On";
    case BluetoothAdapter.STATE_TURNING_OFF:
        return "Turning Off";
    case BluetoothAdapter.STATE_TURNING_ON:
        return "Turning On";
    default:/*from w  w  w  . ja  v a  2 s  .c  om*/
        return "Unknown";
    }
}

From source file:org.apache.cordova.plugin.BluetoothPlugin.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    logDbg("Action: " + action);

    if (ACTION_IS_SUPPORTED.equals(action)) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, m_bluetoothAdapter != null));
        return true;
    } else if (m_bluetoothAdapter == null) {
        String msg = "Bluetooth is not supported !";
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg));
        logErr(msg);/*from w  w  w.j a  v a 2s  .c  om*/
        return true;
    } else if (ACTION_ENABLE.equals(action)) {
        this.callback_enable = callbackContext;
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        if (!m_bluetoothAdapter.isEnabled()) {
            this.cordova.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
                    this.REQUEST_CODE_ENABLE);
        }
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_DISABLE.equals(action)) {
        PluginResult pluginResult;
        if (!m_bluetoothAdapter.disable()
                && !(m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF
                        || m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)) {
            pluginResult = new PluginResult(PluginResult.Status.ERROR);
        } else {
            pluginResult = new PluginResult(PluginResult.Status.OK);
        }
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_IS_ENABLED.equals(action)) {
        boolean b = m_bluetoothAdapter.isEnabled();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
        return true;
    } else if (ACTION_GETADDRESS.equals(action)) {
        String address = m_bluetoothAdapter.getAddress();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, address));
        return true;
    } else if (ACTION_GETNAME.equals(action)) {
        String name = m_bluetoothAdapter.getName();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, name));
        return true;
    } else if (ACTION_REQUEST_DISCOVERABLE.equals(action)) {
        final int duration = args.getInt(0);
        this.callback_discoverable = callbackContext;
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, duration);
        this.cordova.startActivityForResult(this, intent, this.REQUEST_CODE_DISCOVERABLE);
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_STARTDISCOVERY.equals(action)) {
        this.callback_discovery = callbackContext;
        m_discoveredDevices = new JSONArray();
        // be sure there are no ongoing discovery
        m_bluetoothAdapter.cancelDiscovery();
        if (!m_bluetoothAdapter.startDiscovery()) {
            String msg = "Unable to start discovery";
            logErr(msg);
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg));
        } else {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }
        return true;
    } else if (ACTION_CANCELDISCOVERY.equals(action)) {
        if (m_bluetoothAdapter.cancelDiscovery())
            callbackContext.success();
        else
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
        return true;
    } else if (ACTION_GETBONDEDDEVICES.equals(action)) {
        JSONArray bondedDevices = new JSONArray();
        Set<BluetoothDevice> bondSet = m_bluetoothAdapter.getBondedDevices();
        for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) {
            BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next();
            JSONObject deviceInfo = new JSONObject();
            deviceInfo.put("name", bluetoothDevice.getName());
            deviceInfo.put("address", bluetoothDevice.getAddress());
            deviceInfo.put("isBonded", true);
            bondedDevices.put(deviceInfo);
        }
        callbackContext.success(bondedDevices);
        return true;
    } else if (ACTION_FETCHUUIDS.equals(action)) {
        final String address = args.getString(0);
        this.callback_uuids = callbackContext;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            String msg = "Not supported, minimum SDK version is :" + Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
            logErr(msg);
            callbackContext.error(msg);
            return true;
        }
        try {
            logDbg("Listing UUIDs for : " + address);
            // Fetch UUIDs from bluetooth device
            BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address);
            // min api 15 !!!
            Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp", (Class[]) null);
            m.invoke(bluetoothDevice, (Object[]) null);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        } catch (Exception e) {
            logErr(e.toString() + " / " + e.getMessage());
            callbackContext.error(e.getMessage());
        }
        return true;
    } else if (ACTION_CONNECT.equals(action)) {
        final String address = args.getString(0);
        final String uuid = args.getString(1);
        final boolean secure = args.getBoolean(2);
        this.callback_connect = callbackContext;
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                BluetoothSocket socket = null;
                try {
                    logDbg("Connecting...");
                    // Cancel discovery because it will slow down the connection
                    if (m_bluetoothAdapter.isDiscovering())
                        m_bluetoothAdapter.cancelDiscovery();
                    BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address);
                    if (secure) {
                        socket = connectSecureHelper(bluetoothDevice, UUID.fromString(uuid));
                    } else {
                        socket = connectInsecureHelper(bluetoothDevice, UUID.fromString(uuid));
                    }
                } catch (Exception e) {
                    logErr(e.toString() + " / " + e.getMessage());
                    callback_connect.error(e.getMessage());
                }
                if (socket != null) {
                    logDbg("Connected");
                    m_sockets.add(socket);
                    int socketId = m_sockets.indexOf(socket);
                    callback_connect.sendPluginResult(new PluginResult(PluginResult.Status.OK, socketId));
                } else {
                    callback_connect.error(0);
                }
            }
        });
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_DISCONNECT.equals(action)) {
        final int socketId = args.getInt(0);
        try {
            BluetoothSocket socket = m_sockets.get(socketId);
            logDbg("Close socket");
            socket.close();
            logDbg("Delete socket from list");
            m_sockets.remove(socketId);
            for (int i = 0; i < m_readThreads.size(); i++) {
                if (m_readThreads.get(i).socketId == socketId) {
                    m_readThreads.remove(i);
                    break;
                }
            }
            callbackContext.success();
        } catch (Exception e) {
            logErr(e.toString() + " / " + e.getMessage());
            callbackContext.error(e.getMessage());
        }
        return true;
    } else if (ACTION_LISTEN.equals(action)) {
        final String name = args.getString(0);
        final String uuid = args.getString(1);
        final boolean secure = args.getBoolean(2);
        this.callback_listen = callbackContext;
        if (m_listenThread != null) {
            m_listenThread.cancel();
            m_listenThread = null;
        }
        m_listenThread = new ListenThread(this.cordova, name, UUID.fromString(uuid), secure);
        m_listenThread.start();
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_CANCEL_LISTENING.equals(action)) {
        if (m_listenThread != null) {
            m_listenThread.cancel();
        }
        m_listenThread = null;
        callbackContext.success();
        return true;
    } else if (ACTION_READ.equals(action)) {
        final int socketId = args.getInt(0);
        final int bufferSize = args.getInt(1);
        this.callback_read = callbackContext;
        ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize);
        readThread.start();
        m_readThreads.add(readThread);
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_WRITE.equals(action)) {
        final int socketId = args.getInt(0);
        final JSONArray jsonArray = args.getJSONArray(1);
        try {
            OutputStream outputStream = m_sockets.get(socketId).getOutputStream();
            byte[] buffer = new byte[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                buffer[i] = (byte) jsonArray.getInt(i);
            }
            outputStream.write(buffer);
            callbackContext.success();
        } catch (Exception e) {
            logErr(e.toString() + " / " + e.getMessage());
            callbackContext.error(e.getMessage());
        }
        return true;
    }

    return false;
}

From source file:org.apache.cordova.plugin.BluetoothPlugin2.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    logDbg("Action: " + action);

    if (ACTION_IS_SUPPORTED.equals(action)) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, m_bluetoothAdapter != null));
        return true;
    } else if (m_bluetoothAdapter == null) {
        String msg = "Bluetooth is not supported !";
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg));
        logErr(msg);/* www  . j a va  2 s. com*/
        return true;
    } else if (ACTION_ENABLE.equals(action)) {
        this.callback_enable = callbackContext;
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        if (!m_bluetoothAdapter.isEnabled()) {
            this.cordova.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
                    this.REQUEST_CODE_ENABLE);
        }
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_DISABLE.equals(action)) {
        PluginResult pluginResult;
        if (!m_bluetoothAdapter.disable()
                && !(m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF
                        || m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)) {
            pluginResult = new PluginResult(PluginResult.Status.ERROR);
        } else {
            pluginResult = new PluginResult(PluginResult.Status.OK);
        }
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_IS_ENABLED.equals(action)) {
        boolean b = m_bluetoothAdapter.isEnabled();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
        return true;
    } else if (ACTION_GETADDRESS.equals(action)) {
        String address = m_bluetoothAdapter.getAddress();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, address));
        return true;
    } else if (ACTION_GETNAME.equals(action)) {
        String name = m_bluetoothAdapter.getName();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, name));
        return true;
    } else if (ACTION_REQUEST_DISCOVERABLE.equals(action)) {
        final int duration = args.getInt(0);
        this.callback_discoverable = callbackContext;
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, duration);
        this.cordova.startActivityForResult(this, intent, this.REQUEST_CODE_DISCOVERABLE);
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_STARTDISCOVERY.equals(action)) {
        this.callback_discovery = callbackContext;
        m_discoveredDevices = new JSONArray();
        // be sure there are no ongoing discovery
        m_bluetoothAdapter.cancelDiscovery();
        if (!m_bluetoothAdapter.startDiscovery()) {
            String msg = "Unable to start discovery";
            logErr(msg);
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg));
        } else {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }
        return true;
    } else if (ACTION_CANCELDISCOVERY.equals(action)) {
        if (m_bluetoothAdapter.cancelDiscovery())
            callbackContext.success();
        else
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
        return true;
    } else if (ACTION_GETBONDEDDEVICES.equals(action)) {
        JSONArray bondedDevices = new JSONArray();
        Set<BluetoothDevice> bondSet = m_bluetoothAdapter.getBondedDevices();
        for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) {
            BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next();
            JSONObject deviceInfo = new JSONObject();
            deviceInfo.put("name", bluetoothDevice.getName());
            deviceInfo.put("address", bluetoothDevice.getAddress());
            deviceInfo.put("isBonded", true);
            bondedDevices.put(deviceInfo);
        }
        callbackContext.success(bondedDevices);
        return true;
    } else if (ACTION_FETCHUUIDS.equals(action)) {
        final String address = args.getString(0);
        this.callback_uuids = callbackContext;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            String msg = "Not supported, minimum SDK version is :" + Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
            logErr(msg);
            callbackContext.error(msg);
            return true;
        }
        try {
            logDbg("Listing UUIDs for : " + address);
            // Fetch UUIDs from bluetooth device
            BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address);
            // min api 15 !!!
            Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp", (Class[]) null);
            m.invoke(bluetoothDevice, (Object[]) null);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        } catch (Exception e) {
            logErr(e.toString() + " / " + e.getMessage());
            callbackContext.error(e.getMessage());
        }
        return true;
    } else if (ACTION_CONNECT.equals(action)) {
        final String address = args.getString(0);
        final String uuid = args.getString(1);
        final boolean secure = args.getBoolean(2);
        this.callback_connect = callbackContext;
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                BluetoothSocket socket = null;
                try {
                    logDbg("Connecting...");
                    // Cancel discovery because it will slow down the connection
                    if (m_bluetoothAdapter.isDiscovering())
                        m_bluetoothAdapter.cancelDiscovery();

                    //JWC adding
                    /*
                            
                    BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); //"74:45:8A:B2:4E:9A"); 
                    //Method m = device.getClass().getMethod("createInsecureRfcommSocket", 
                    //      new Class[] { int.class }); 
                    //socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1)); 
                    socket = device.createRfcommSocketToServiceRecord(java.util.UUID.fromString(uuid));
                    */
                    //////

                    System.out.println("BluetoothPlugin2.ACTION_CONNECT  address=" + address + ", uuid=" + uuid
                            + ", secure=" + secure);
                    BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); //"74:45:8A:B2:4E:9A"); 
                    socket = device.createInsecureRfcommSocketToServiceRecord(java.util.UUID.fromString(uuid));

                    // for others devices its works with:
                    // Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

                    // for galaxy tab 2 with:
                    //Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});

                    //socket = (BluetoothSocket) m.invoke(device, 1);

                    socket.connect();

                    /////JWC  READ

                    System.out.println("BluetoothPlugin2 trying to read right away...");
                    final int socketId = 0; //args.getInt(0);
                    final int bufferSize = 512; //args.getInt(1);
                    //this.callback_read = callbackContext;
                    ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize);
                    readThread.start();
                    m_readThreads.add(readThread);
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);

                    ///////////////

                    /* JWC removing
                    BluetoothDevice bluetoothDevice = 
                          m_bluetoothAdapter.getRemoteDevice(
                      address);
                    if (secure) {
                       socket = connectSecureHelper(
                             bluetoothDevice, 
                             UUID.fromString(uuid));
                    }
                    else {
                       socket = connectInsecureHelper(
                             bluetoothDevice, 
                             UUID.fromString(uuid));
                    }
                    */
                } catch (Exception e) {
                    logErr(e.toString() + " / " + e.getMessage());
                    callback_connect.error(e.getMessage());
                }
                if (socket != null) {
                    logDbg("Connected");
                    m_sockets.add(socket);
                    int socketId = m_sockets.indexOf(socket);
                    callback_connect.sendPluginResult(new PluginResult(PluginResult.Status.OK, socketId));
                } else {
                    callback_connect.error(0);
                }
            }
        });
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_DISCONNECT.equals(action)) {
        final int socketId = args.getInt(0);
        try {
            BluetoothSocket socket = m_sockets.get(socketId);
            logDbg("Close socket");
            socket.close();
            logDbg("Delete socket from list");
            m_sockets.remove(socketId);
            for (int i = 0; i < m_readThreads.size(); i++) {
                if (m_readThreads.get(i).socketId == socketId) {
                    m_readThreads.remove(i);
                    break;
                }
            }
            callbackContext.success();
        } catch (Exception e) {
            logErr(e.toString() + " / " + e.getMessage());
            callbackContext.error(e.getMessage());
        }
        return true;
    } else if (ACTION_LISTEN.equals(action)) {
        final String name = args.getString(0);
        final String uuid = args.getString(1);
        final boolean secure = args.getBoolean(2);
        System.out.println(
                "BluetoothPlugin2.ACTION_LISTEN  name=" + name + ", uuid=" + uuid + ", secure=" + secure);
        this.callback_listen = callbackContext;
        if (m_listenThread != null) {
            m_listenThread.cancel();
            m_listenThread = null;
        }
        m_listenThread = new ListenThread(this.cordova, name, UUID.fromString(uuid), secure);
        m_listenThread.start();
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_CANCEL_LISTENING.equals(action)) {
        if (m_listenThread != null) {
            m_listenThread.cancel();
        }
        m_listenThread = null;
        callbackContext.success();
        return true;
    } else if (ACTION_READ.equals(action)) {
        final int socketId = args.getInt(0);
        final int bufferSize = args.getInt(1);
        System.out.println("BluetoothPlugin2.ACTION_READ  socketId=" + socketId + ", bufferSize=" + bufferSize);
        this.callback_read = callbackContext;
        ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize);
        readThread.start();
        m_readThreads.add(readThread);
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    } else if (ACTION_WRITE.equals(action)) {
        final int socketId = args.getInt(0);
        final JSONArray jsonArray = args.getJSONArray(1);
        try {
            OutputStream outputStream = m_sockets.get(socketId).getOutputStream();
            byte[] buffer = new byte[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                buffer[i] = (byte) jsonArray.getInt(i);
            }
            outputStream.write(buffer);
            callbackContext.success();
        } catch (Exception e) {
            logErr(e.toString() + " / " + e.getMessage());
            callbackContext.error(e.getMessage());
        }
        return true;
    }

    return false;
}

From source file:pl.mrwojtek.sensrec.app.HeartRateDialog.java

public void onBluetoothAdapterState(int state) {
    switch (state) {
    case BluetoothAdapter.STATE_OFF:
        scanLeDevice(false);//from w ww  .ja  v  a2 s . c  o  m
        break;
    case BluetoothAdapter.STATE_TURNING_OFF:
        // Ignore for now
        break;
    case BluetoothAdapter.STATE_ON:
        scanLeDevice(true);
        break;
    case BluetoothAdapter.STATE_TURNING_ON:
        // Ignore for now
        break;
    }
}

From source file:com.piusvelte.taplock.client.core.TapLockService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
            if (state == BluetoothAdapter.STATE_ON) {
                if (mStartedBT) {
                    if (mUIInterface != null) {
                        try {
                            mUIInterface.setMessage("Bluetooth enabled");
                        } catch (RemoteException e) {
                            Log.e(TAG, e.getMessage());
                        }/*w  ww  .ja va2  s . c o m*/
                    }
                    if ((mQueueAddress != null) && (mQueueState != null))
                        requestWrite(mQueueAddress, mQueueState, mQueuePassphrase);
                    else if (mRequestDiscovery && !mBtAdapter.isDiscovering())
                        mBtAdapter.startDiscovery();
                    else if (mUIInterface != null) {
                        try {
                            mUIInterface.setBluetoothEnabled();
                        } catch (RemoteException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    }
                }
            } else if (state == BluetoothAdapter.STATE_TURNING_OFF) {
                if (mUIInterface != null) {
                    try {
                        mUIInterface.setMessage("Bluetooth disabled");
                    } catch (RemoteException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
                stopThreads();
            }
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                // connect if configured
                String address = device.getAddress();
                for (JSONObject deviceJObj : mDevices) {
                    try {
                        if (deviceJObj.getString(KEY_ADDRESS).equals(address)) {
                            // if queued
                            mDeviceFound = (mQueueAddress != null) && mQueueAddress.equals(address)
                                    && (mQueueState != null);
                            break;
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
            } else if (mRequestDiscovery && (mUIInterface != null)) {
                String unpairedDevice = TapLock
                        .createDevice(device.getName(), device.getAddress(), DEFAULT_PASSPHRASE).toString();
                try {
                    mUIInterface.setUnpairedDevice(unpairedDevice);
                } catch (RemoteException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            if (mDeviceFound) {
                requestWrite(mQueueAddress, mQueueState, mQueuePassphrase);
                mDeviceFound = false;
            } else if (mRequestDiscovery) {
                mRequestDiscovery = false;
                if (mUIInterface != null) {
                    try {
                        mUIInterface.setDiscoveryFinished();
                    } catch (RemoteException e) {
                        Log.e(TAG, e.toString());
                    }
                }
            }
        } else if (ACTION_TOGGLE.equals(action) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) {
            String address = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
            requestWrite(address, ACTION_TOGGLE, null);
        } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
            // create widget
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (intent.hasExtra(EXTRA_DEVICE_NAME)) {
                    // add a widget
                    String deviceName = intent.getStringExtra(EXTRA_DEVICE_NAME);
                    for (int i = 0, l = mDevices.size(); i < l; i++) {
                        String name = null;
                        try {
                            name = mDevices.get(i).getString(KEY_NAME);
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                        if ((name != null) && name.equals(deviceName)) {
                            JSONObject deviceJObj = mDevices.remove(i);
                            JSONArray widgetsJArr;
                            if (deviceJObj.has(KEY_WIDGETS)) {
                                try {
                                    widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS);
                                } catch (JSONException e) {
                                    widgetsJArr = new JSONArray();
                                }
                            } else
                                widgetsJArr = new JSONArray();
                            widgetsJArr.put(appWidgetId);
                            try {
                                deviceJObj.put(KEY_WIDGETS, widgetsJArr);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            mDevices.add(i, deviceJObj);
                            TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices);
                            break;
                        }
                    }
                }
                buildWidget(appWidgetId);
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) {
                int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
                if (appWidgetIds != null) {
                    for (int appWidgetId : appWidgetIds)
                        buildWidget(appWidgetId);
                }
            }
        } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
            int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            Log.d(TAG, "delete appWidgetId: " + appWidgetId);
            for (int i = 0, l = mDevices.size(); i < l; i++) {
                JSONObject deviceJObj = mDevices.get(i);
                if (deviceJObj.has(KEY_WIDGETS)) {
                    JSONArray widgetsJArr = null;
                    try {
                        widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (widgetsJArr != null) {
                        boolean wasUpdated = false;
                        JSONArray newWidgetsJArr = new JSONArray();
                        for (int widgetIdx = 0, wdigetsLen = widgetsJArr
                                .length(); widgetIdx < wdigetsLen; widgetIdx++) {
                            int widgetId;
                            try {
                                widgetId = widgetsJArr.getInt(widgetIdx);
                            } catch (JSONException e) {
                                widgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
                                e.printStackTrace();
                            }
                            Log.d(TAG, "eval widgetId: " + widgetId);
                            if ((widgetId != AppWidgetManager.INVALID_APPWIDGET_ID)
                                    && (widgetId == appWidgetId)) {
                                Log.d(TAG, "skip: " + widgetId);
                                wasUpdated = true;
                            } else {
                                Log.d(TAG, "include: " + widgetId);
                                newWidgetsJArr.put(widgetId);
                            }
                        }
                        if (wasUpdated) {
                            try {
                                deviceJObj.put(KEY_WIDGETS, newWidgetsJArr);
                                mDevices.remove(i);
                                mDevices.add(i, deviceJObj);
                                TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE),
                                        mDevices);
                                Log.d(TAG, "stored: " + deviceJObj.toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    JSONArray widgetsJArr = new JSONArray();
                    try {
                        deviceJObj.put(KEY_WIDGETS, widgetsJArr);
                        mDevices.remove(i);
                        mDevices.add(i, deviceJObj);
                        TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return START_STICKY;
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java

@Override
@RequiresPermission(allOf = { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, })
public Observable<Void> turnOff() {
    if (adapter == null) {
        return Observable.error(new ChangePowerStateException());
    }//from  w  w  w.ja  v a 2  s  .c o m

    final ReplaySubject<Void> turnOnMirror = ReplaySubject.createWithSize(1);
    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                    BluetoothAdapter.ERROR);
            final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            if (oldState == BluetoothAdapter.STATE_ON && newState == BluetoothAdapter.STATE_TURNING_OFF) {
                logger.info(LOG_TAG, "Bluetooth turning off");
            } else if (oldState == BluetoothAdapter.STATE_TURNING_OFF
                    && newState == BluetoothAdapter.STATE_OFF) {
                logger.info(LOG_TAG, "Bluetooth turned off");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onNext(null);
                turnOnMirror.onCompleted();
            } else {
                logger.info(LOG_TAG, "Bluetooth failed to turn off");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onError(new ChangePowerStateException());
            }
        }
    };
    applicationContext.registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    if (!adapter.disable()) {
        applicationContext.unregisterReceiver(receiver);
        return Observable.error(new ChangePowerStateException());
    }

    return turnOnMirror;
}

From source file:com.googlecode.android_scripting.facade.BluetoothFacade.java

@Rpc(description = "Gets the scan mode for the local dongle.\r\n" + "Return values:\r\n"
        + "\t-1 when Bluetooth is disabled.\r\n" + "\t0 if non discoverable and non connectable.\r\n"
        + "\r1 connectable non discoverable." + "\r3 connectable and discoverable.")
public int bluetoothGetScanMode() {
    if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF
            || mBluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
        return -1;
    }/* w w  w. j  ava 2  s. c om*/

    switch (mBluetoothAdapter.getScanMode()) {
    case BluetoothAdapter.SCAN_MODE_NONE:
        return 0;
    case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
        return 1;
    case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
        return 3;
    default:
        return mBluetoothAdapter.getScanMode() - 20;
    }
}

From source file:com.duy.pascal.interperter.libraries.android.connection.bluetooth.AndroidBluetoothLib.java

@SuppressWarnings("unused")
@PascalMethod(description = "Gets the scan mode for the local dongle.\r\n" + "Return values:\r\n"
        + "\t-1 when Bluetooth is disabled.\r\n" + "\t0 if non discoverable and non connectable.\r\n"
        + "\r1 connectable non discoverable." + "\r3 connectable and discoverable.")
public int bluetoothGetScanMode() {
    if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF
            || mBluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
        return -1;
    }//from  ww w.  ja  v  a  2s  . c o m

    switch (mBluetoothAdapter.getScanMode()) {
    case BluetoothAdapter.SCAN_MODE_NONE:
        return 0;
    case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
        return 1;
    case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
        return 3;
    default:
        return mBluetoothAdapter.getScanMode() - 20;
    }
}

From source file:com.commontime.plugin.LocationManager.java

private void initBluetoothListener() {

    //check access
    if (!hasBlueToothPermission()) {
        debugWarn("Cannot listen to Bluetooth service when BLUETOOTH permission is not added");
        return;/*from w w  w . j  a v  a 2  s  . c  o m*/
    }

    //check device support
    try {
        iBeaconManager.checkAvailability();
    } catch (Exception e) {
        //if device does not support iBeacons an error is thrown
        debugWarn("Cannot listen to Bluetooth service: " + e.getMessage());
        return;
    }

    if (broadcastReceiver != null) {
        debugWarn("Already listening to Bluetooth service, not adding again");
        return;
    }

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            // Only listen for Bluetooth server changes
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {

                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                        BluetoothAdapter.ERROR);

                debugLog("Bluetooth Service state changed from " + getStateDescription(oldState) + " to "
                        + getStateDescription(state));

                switch (state) {
                case BluetoothAdapter.ERROR:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusNotDetermined");
                    break;
                case BluetoothAdapter.STATE_OFF:
                case BluetoothAdapter.STATE_TURNING_OFF:
                    if (oldState == BluetoothAdapter.STATE_ON)
                        beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusDenied");
                    break;
                case BluetoothAdapter.STATE_ON:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusAuthorized");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    break;
                }
            }
        }

        private String getStateDescription(int state) {
            switch (state) {
            case BluetoothAdapter.ERROR:
                return "ERROR";
            case BluetoothAdapter.STATE_OFF:
                return "STATE_OFF";
            case BluetoothAdapter.STATE_TURNING_OFF:
                return "STATE_TURNING_OFF";
            case BluetoothAdapter.STATE_ON:
                return "STATE_ON";
            case BluetoothAdapter.STATE_TURNING_ON:
                return "STATE_TURNING_ON";
            }
            return "ERROR" + state;
        }
    };

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    cordova.getActivity().registerReceiver(broadcastReceiver, filter);
}