Example usage for android.bluetooth BluetoothAdapter STATE_OFF

List of usage examples for android.bluetooth BluetoothAdapter STATE_OFF

Introduction

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

Prototype

int STATE_OFF

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

Click Source Link

Document

Indicates the local Bluetooth adapter is off.

Usage

From source file:de.unifreiburg.es.iLitIt.LighterBluetoothService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (mBluetoothChangeReceiver == null) {
        mBluetoothChangeReceiver = new BroadcastReceiver() {
            @Override//from   w  w  w.  jav  a  2 s.  c o  m
            public void onReceive(Context context, Intent intent) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

                switch (state) {
                case BluetoothAdapter.STATE_ON:
                    onStartCommand(null, 0, 0);
                    break;
                case BluetoothAdapter.STATE_OFF:
                    break;
                default:
                    break;
                }
            }
        };

        IntentFilter mif = new IntentFilter();
        mif.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBluetoothChangeReceiver, mif);
    }

    if (mSmartWatchAnnotationReceiver == null) {
        mSmartWatchAnnotationReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (mEventList == null)
                    return;

                String via = intent.getStringExtra("ess.imu_logger.libs.data_save.extra.annotationVia");
                mEventList.add(new CigaretteEvent(new Date(), via == null ? "intent" : via, null));
            }
        };

        // create watch ui intent listener
        IntentFilter filter = new IntentFilter("ess.imu_logger.libs.data_save.annotate");
        registerReceiver(mSmartWatchAnnotationReceiver, filter);
    }

    // For API level 18 and above, get a reference to BluetoothAdapter through
    // BluetoothManager.
    //if (serviceIsInitialized)
    //    return START_STICKY;

    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager == null) {
        Log.e(TAG, "Unable to initialize BluetoothManager.");
        return START_NOT_STICKY;
    }

    mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
        return START_NOT_STICKY;
    }

    // for DEBUGGING only
    // PreferenceManager.getDefaultSharedPreferences(this).edit().clear().apply();

    /** check if we are already bound to a device, if not start scanning for one */
    mBluetoothDeviceAddress = PreferenceManager.getDefaultSharedPreferences(this).getString(KEY_DEVICEADDR,
            null);
    mLastBatteryVoltage = PreferenceManager.getDefaultSharedPreferences(this).getFloat(KEY_BATVOLTAGE, 0.0f);
    mBatteryEmpty = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(KEY_BATEMTPY, false);

    super.onStartCommand(intent, flags, startId);

    /** load the stored events */
    if (mEventList == null) {
        mEventList = CigAnnotationWriter.readCigaretteList(this);

        mEventList.register(rCigAnnotationWriter);
        mEventList.register(rCigIntentBroadcaster);

    }

    /** set-up the location service, we need this to run here, since we need to
     *access the location whenever there is a chang to the cigarette model. */
    mLocationClient = new LocationClient(this, mLocationHandler, mLocationHandler);
    mEventList.register(new DelayedObserver(1000, mLocationHandler));

    /** start to scan for LE devices in the area */
    mHandler = new Handler(Looper.getMainLooper());
    mHandler.post(rStartLEScan);

    /** create a notification on a pending connection */
    PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
    mNotification = (new NotificationCompat.Builder(this)).setContentText("downloading cigarette events")
            .setContentTitle("iLitIt").setSmallIcon(R.drawable.ic_cigarette_black).setProgress(0, 0, true)
            .setAutoCancel(true).setContentIntent(i).build();

    mLowBatteryWarning = (new NotificationCompat.Builder(this)).setContentTitle("iLitIt - battery low")
            .setContentText("replace battery as soons as possible").setSmallIcon(R.drawable.ic_launcher)
            .build();

    return START_STICKY;
}

From source file:co.aurasphere.bluepair.bluetooth.BluetoothController.java

/**
 * Called when the Bluetooth status changed.
 *//*from   www.  j  a v  a  2s  .co  m*/
public void onBluetoothStatusChanged() {
    // Does anything only if a device discovery has been scheduled.
    if (bluetoothDiscoveryScheduled) {

        int bluetoothState = bluetooth.getState();
        switch (bluetoothState) {
        case BluetoothAdapter.STATE_ON:
            // Bluetooth is ON.
            Log.d(TAG, "Bluetooth succesfully enabled, starting discovery");
            startDiscovery();
            // Resets the flag since this discovery has been performed.
            bluetoothDiscoveryScheduled = false;
            break;
        case BluetoothAdapter.STATE_OFF:
            // Bluetooth is OFF.
            Log.d(TAG, "Error while turning Bluetooth on.");
            Toast.makeText(context, "Error while turning Bluetooth on.", Toast.LENGTH_SHORT);
            // Resets the flag since this discovery has been performed.
            bluetoothDiscoveryScheduled = false;
            break;
        default:
            // Bluetooth is turning ON or OFF. Ignore.
            break;
        }
    }
}

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);// w w w .ja v a 2s  .co m
        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);/* w  w w  . j a v a 2s.c o  m*/
        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  .j a  v a2  s . c  om*/
        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:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java

@Override
@RequiresPermission(allOf = { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, })
public Observable<Void> turnOn() {
    if (adapter == null) {
        return Observable.error(new ChangePowerStateException());
    }//from   www .j  a v  a 2s  . co  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_OFF && newState == BluetoothAdapter.STATE_TURNING_ON) {
                logger.info(LOG_TAG, "Bluetooth turning on");
            } else if (oldState == BluetoothAdapter.STATE_TURNING_ON && newState == BluetoothAdapter.STATE_ON) {
                logger.info(LOG_TAG, "Bluetooth turned on");

                applicationContext.unregisterReceiver(this);

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

                applicationContext.unregisterReceiver(this);

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

    return turnOnMirror;
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

/** Called when the activity is first created. */
@Override//from  w  w  w .  ja va 2  s .c  o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    fixScreenOrientation();

    DoCommand dc = new DoCommand(getApplication());

    Log.i("SUTAgentAndroid", dc.prgVersion);
    dc.FixDataLocalPermissions();

    // Get configuration settings from "ini" file
    File dir = getFilesDir();
    File iniFile = new File(dir, "SUTAgent.ini");
    String sIniFile = iniFile.getAbsolutePath();

    String lc = dc.GetIniData("General", "LogCommands", sIniFile);
    if (lc != "" && Integer.parseInt(lc) == 1) {
        SUTAgentAndroid.LogCommands = true;
    }
    SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
    SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
    SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
    SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
    SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile);
    SUTAgentAndroid.Abi = android.os.Build.CPU_ABI;
    log(dc, "onCreate");

    dc.SetTestRoot(SUTAgentAndroid.sTestRoot);

    Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot);

    tv = (TextView) this.findViewById(R.id.Textview01);

    if (getLocalIpAddress() == null)
        setUpNetwork(sIniFile);

    String macAddress = "Unknown";
    if (android.os.Build.VERSION.SDK_INT > 8) {
        try {
            NetworkInterface iface = NetworkInterface
                    .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]);
            if (iface != null) {
                byte[] mac = iface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    Formatter f = new Formatter(sb);
                    for (int i = 0; i < mac.length; i++) {
                        f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : "");
                    }
                    macAddress = sUniqueID = sb.toString();
                }
            }
        } catch (UnknownHostException ex) {
        } catch (SocketException ex) {
        }
    } else {
        // Fall back to getting info from wifiman on older versions of Android,
        // which don't support the NetworkInterface interface
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifi = wifiMan.getConnectionInfo();
            if (wifi != null)
                macAddress = wifi.getMacAddress();
            if (macAddress != null)
                sUniqueID = macAddress;
        }
    }

    if (sUniqueID == null) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if ((ba != null) && (ba.isEnabled() != true)) {
            ba.enable();
            while (ba.getState() != BluetoothAdapter.STATE_ON) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sUniqueID = ba.getAddress();

            ba.disable();
            while (ba.getState() != BluetoothAdapter.STATE_OFF) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (ba != null) {
                sUniqueID = ba.getAddress();
                sUniqueID.toLowerCase();
            }
        }
    }

    if (sUniqueID == null) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mTelephonyMgr != null) {
            sUniqueID = mTelephonyMgr.getDeviceId();
            if (sUniqueID == null) {
                sUniqueID = "0011223344556677";
            }
        }
    }

    String hwid = getHWID(this);

    sLocalIPAddr = getLocalIpAddress();
    Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...",
            Toast.LENGTH_LONG).show();

    String sConfig = dc.prgVersion + lineSep;
    sConfig += "Test Root: " + sTestRoot + lineSep;
    sConfig += "Unique ID: " + sUniqueID + lineSep;
    sConfig += "HWID: " + hwid + lineSep;
    sConfig += "ABI: " + Abi + lineSep;
    sConfig += "OS Info" + lineSep;
    sConfig += "\t" + dc.GetOSInfo() + lineSep;
    sConfig += "Screen Info" + lineSep;
    int[] xy = dc.GetScreenXY();
    sConfig += "\t Width: " + xy[0] + lineSep;
    sConfig += "\t Height: " + xy[1] + lineSep;
    sConfig += "Memory Info" + lineSep;
    sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
    sConfig += "Network Info" + lineSep;
    sConfig += "\tMac Address: " + macAddress + lineSep;
    sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;

    displayStatus(sConfig);

    sRegString = "NAME=" + sUniqueID;
    sRegString += "&IPADDR=" + sLocalIPAddr;
    sRegString += "&CMDPORT=" + 20701;
    sRegString += "&DATAPORT=" + 20700;
    sRegString += "&OS=Android-" + dc.GetOSInfo();
    sRegString += "&SCRNWIDTH=" + xy[0];
    sRegString += "&SCRNHEIGHT=" + xy[1];
    sRegString += "&BPP=8";
    sRegString += "&MEMORY=" + dc.GetMemoryConfig();
    sRegString += "&HARDWARE=" + HardwareID;
    sRegString += "&POOL=" + Pool;
    sRegString += "&ABI=" + Abi;

    String sTemp = Uri.encode(sRegString, "=&");
    sRegString = "register " + sTemp;

    pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot());

    if (!bNetworkingStarted) {
        Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
        thread.start();
        bNetworkingStarted = true;

        Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd");
        thread2.start();
    }

    monitorBatteryState();

    // If we are returning from an update let'em know we're back
    Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd");
    thread3.start();

    final Button goButton = (Button) findViewById(R.id.Button01);
    goButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:com.nbplus.iotapp.service.IoTService.java

public void handleMessage(Message msg) {
    if (msg == null) {
        return;//from   w w w. ja va2s.  c o m
    }
    Log.d(TAG, "handle message msg.what = " + msg.what);
    switch (msg.what) {
    // when using iot gateway
    case IoTServiceCommand.IOT_GATEWAY_CONNECTED: {
        Log.d(TAG, "IoTServiceCommand.IOT_GATEWAY_CONNECTED received...");
        mIoTGatewayWorkerMessengerRef = new WeakReference<>(msg.replyTo);
        // TODO : test handler
        if (mIoTGatewayWorkerMessengerRef != null) {
            try {
                Messenger workerMessenger = mIoTGatewayWorkerMessengerRef.get();
                if (workerMessenger != null) {
                    Message testMsg = new Message();
                    msg.what = IoTServiceCommand.IOT_GATEWAY_DISCONNECTED;
                    Log.d(TAG, "test IoTServiceCommand.IOT_GATEWAY_DISCONNECTED");
                    workerMessenger.send(testMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        break;
    }
    case IoTServiceCommand.SCANNING_START: {
        Bundle extras = msg.getData();
        if (extras == null) {
            Log.w(TAG, "Scanning bundle data is not found !!!");
            return;
        }
        boolean isPeriodic = extras.getBoolean(IoTServiceCommand.KEY_DATA);
        Log.d(TAG, "IoTServiceCommand.SCANNING_START called. periodic = " + isPeriodic);
        if (mUseIoTGateway) {

        } else {
            if (mBluetoothLeService != null && mServiceStatus == IoTServiceStatus.RUNNING) {
                mIsBleScanPeriodic = isPeriodic;
                mBluetoothLeService.scanLeDevicePeriodically(true, isPeriodic);
            }
        }
        break;
    }
    case IoTServiceCommand.SCANNING_STOP: {
        Bundle extras = msg.getData();
        if (extras == null) {
            Log.w(TAG, "Scanning bundle data is not found !!!");
            return;
        }
        //boolean isPeriodic = extras.getBoolean(IoTServiceCommand.KEY_DATA);
        Log.d(TAG, "IoTServiceCommand.SCANNING_STOP called.");
        if (mUseIoTGateway) {

        } else {
            if (mBluetoothLeService != null && mServiceStatus == IoTServiceStatus.RUNNING) {
                mIsBleScanPeriodic = false;
                mBluetoothLeService.scanLeDevicePeriodically(false, false);
            }
        }
        break;
    }
    case HANDLER_MESSAGE_CONNECTIVITY_CHANGED:
        final boolean isConnected = NetworkUtils.isConnected(this);
        Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED received isConnected = " + isConnected);
        if (mLastConnectionStatus == isConnected) {
            Log.d(TAG, "mLastConnectionStatus == isConnected do not anything.");
            return;
        }

        mLastConnectionStatus = isConnected;
        if (mLastConnectionStatus) {
            Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED network is connected !!!");
            // TODO : re-connect
            if (mServiceStatus == IoTServiceStatus.STOPPED) {

            }
        } else {
            Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED network is disconnected !!!");
        }
        break;
    case HANDLER_MESSAGE_BT_STATE_CHANGED:
        Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED received !!!");
        final int state = msg.arg1;
        if ((mLastConnectionStatus && state == BluetoothAdapter.STATE_ON)
                || (!mLastConnectionStatus && state == BluetoothAdapter.STATE_OFF)) {
            return;
        }

        mLastConnectionStatus = (state == BluetoothAdapter.STATE_ON) ? true : false;
        if (mLastConnectionStatus) {
            Log.d(TAG, "HANDLER_MESSAGE_BT_STATE_CHANGED bluetooth is enabled !!!");

            if (mServiceStatus != IoTServiceStatus.RUNNING) {
                final Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
                if (!bindService(gattServiceIntent, mBluetoothServiceConnection, BIND_AUTO_CREATE)) {
                    Log.e(TAG, ">> bind BluetoothServiceConnection failed.... !!!");
                }
            }
        } else {
            Log.d(TAG, "HANDLER_MESSAGE_BT_STATE_CHANGED bluetooth is disabled !!!");
            mErrorCodes = IoTResultCodes.BLUETOOTH_NOT_ENABLED;
            unbindService(mBluetoothServiceConnection);

            mServiceStatus = IoTServiceStatus.STOPPED;
            mHandler.removeMessages(HANDLER_MESSAGE_CONNECTION_NOT_RESPOND);
            mConnectedDeviceList.clear();
            mRequestHandleMap.clear();

            sendServiceStatusNotification();
        }
        break;
    case IoTServiceCommand.REGISTER_SERVICE: {
        Bundle b = msg.getData();
        if (msg.replyTo == null || b == null) {
            Log.e(TAG, "Invalid register args...");
            break;
        }

        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        if (!StringUtils.isEmptyString(msgId)) {
            Log.d(TAG, "msgId == " + msgId);
            String[] strArrays = msgId.split("_");
            if (strArrays.length == 2) {
                mRegisteredAppMessenger = new WeakReference<>(msg.replyTo);
                sendResultToApplication(msg.replyTo, msgId, null, msg.what, IoTResultCodes.SUCCESS);

                // ??  ??  ? ? .
                sendServiceStatusNotification();
            } else {
                Log.e(TAG, "Invalid register args...");
                sendResultToApplication(msg.replyTo, msgId, null, msg.what,
                        IoTResultCodes.INVALID_REQUEST_ARGUMENTS);
                break;
            }
        } else {
            Log.e(TAG, "Invalid register args...");
            sendResultToApplication(msg.replyTo, "", null, msg.what, IoTResultCodes.INVALID_REQUEST_ARGUMENTS);
            break;
        }

        break;
    }
    case IoTServiceCommand.UNREGISTER_SERVICE: {
        Bundle b = msg.getData();
        if (b == null) {
            Log.e(TAG, "Invalid register args...");
            break;
        }

        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        if (!StringUtils.isEmptyString(msgId)) {
            String[] strArrays = msgId.split("_");
            if (strArrays.length == 2) {
                Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null
                        : mRegisteredAppMessenger.get();
                if (clientMessenger != null) {
                    sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.SUCCESS);
                    mRegisteredAppMessenger = null;
                } else {
                    //??
                }
            } else {
                Log.e(TAG, "Invalid register args...");
                break;
            }
        } else {
            Log.e(TAG, "Invalid un-register args...");
        }
        break;
    }

    case IoTServiceCommand.GET_DEVICE_LIST: {
        if (mUseIoTGateway) {
            // TODO
        } else {
            mBluetoothLeService.scanLeDevice(false);
            mBluetoothLeService.scanLeDevicePeriodically(true, mIsBleScanPeriodic);
        }
        break;
    }

    case IoTServiceCommand.DEVICE_DISCONNECT_ALL: {
        Bundle b = msg.getData();
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);

        if (mConnectedDeviceList.size() > 0) {
            mIsDisconnectAllState = true;
            ioTHandleData.setMsgId(msgId);
            ioTHandleData.setRequestCommand(msg.what);

            String connectedDeviceId = mConnectedDeviceList.get(0);
            if (mUseIoTGateway) {
                // TODO

            } else {
                if (mBluetoothLeService != null) {
                    mBluetoothLeService.disconnect(connectedDeviceId);
                } else {
                    Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null
                            : mRegisteredAppMessenger.get();
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.FAILED);
                }
            }
        } else {
            Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null
                    : mRegisteredAppMessenger.get();
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.SUCCESS);
        }
        break;
    }

    case IoTServiceCommand.DEVICE_CONNECT: {
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();

        if (ioTHandleData == null) {
            sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED);
            Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
            return;
        }

        if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) {
            Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = "
                    + ioTHandleData.getRequestCommand());
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.FAILED);
            return;
        }

        if (mUseIoTGateway) {
        } else {
            if (mBluetoothLeService == null) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_CONNECT : mBluetoothLeService or ioTHandleData is null");
                return;
            }
            if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_DISCONNECT : is not bt device... mUseIoTGateway == false");
                return;
            }

            if (ioTHandleData.isKeepAliveDevice()) {
                if (mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) {
                    Log.d(TAG, "Keep alive device is already connected.. id = " + ioTHandleData.getDeviceId());
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.SUCCESS);

                    // send to IoT interface module
                    Message connectedMsg = new Message();
                    connectedMsg.what = IoTServiceCommand.DEVICE_CONNECTED;
                    Bundle extras = new Bundle();
                    extras.putString(IoTServiceCommand.KEY_DEVICE_UUID, ioTHandleData.getDeviceId());
                    connectedMsg.setData(extras);

                    sendNotificationToApplication(connectedMsg);
                    return;
                }
            }

            if (mBluetoothLeService.connect(ioTHandleData.getDeviceId())) {
                ioTHandleData.setMsgId(msgId);
                ioTHandleData.setRequestCommand(msg.what);

                mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData);
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.SUCCESS);
                // ?... connect  ?  .
                Message notRespondMsg = new Message();
                notRespondMsg.what = HANDLER_MESSAGE_CONNECTION_NOT_RESPOND;
                Bundle extras = new Bundle();
                extras.putParcelable(IoTServiceCommand.KEY_DATA, ioTHandleData);
                notRespondMsg.setData(extras);
                mHandler.sendMessageDelayed(notRespondMsg, CONNECTION_NOT_RESPOND_WAIT_TIME);
            } else {
                Log.w(TAG, "mBluetoothLeService.connect() return false");
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
            }
        }
        break;
    }

    case HANDLER_MESSAGE_CONNECTION_NOT_RESPOND: {
        Log.d(TAG, "HANDLER_MESSAGE_CONNECTION_NOT_RESPOND ...");
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        if (mBluetoothLeService != null) {
            mBluetoothLeService.disconnect(ioTHandleData.getDeviceId());
        }
        mRequestHandleMap.remove(ioTHandleData.getDeviceId());
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();
        sendResultToApplication(clientMessenger, ioTHandleData.getMsgId(), ioTHandleData.getDeviceId(),
                IoTServiceCommand.DEVICE_CONNECT, IoTResultCodes.DEVICE_CONNECTION_NOT_RESPOND);
        break;
    }

    case IoTServiceCommand.DEVICE_DISCONNECT: {
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();

        if (ioTHandleData == null) {
            sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED);
            Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
            return;
        }

        if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) {
            Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = "
                    + ioTHandleData.getRequestCommand());
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.FAILED);
            return;
        }

        if (mUseIoTGateway) {
        } else {
            if (mBluetoothLeService == null) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_DISCONNECT : mBluetoothLeService or ioTHandleData is null");
                return;
            }
            if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_DISCONNECT : is not bt device... mUseIoTGateway == false");
                return;
            }

            if (mConnectedDeviceList.contains(ioTHandleData.getDeviceId())
                    || mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) {
                ioTHandleData.setMsgId(msgId);
                ioTHandleData.setRequestCommand(msg.what);

                mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData);
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.SUCCESS);
                mBluetoothLeService.disconnect(ioTHandleData.getDeviceId());
            } else {
                Log.w(TAG, "mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) is false");
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
            }
        }
        break;
    }

    case IoTServiceCommand.DEVICE_READ_DATA:
    case IoTServiceCommand.DEVICE_WRITE_DATA:
    case IoTServiceCommand.DEVICE_SET_NOTIFICATION: {
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();

        if (ioTHandleData == null) {
            sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED);
            Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
            return;
        }

        if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) {
            Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = "
                    + ioTHandleData.getRequestCommand());
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.FAILED);
            return;
        }

        if (mUseIoTGateway) {
        } else {
            if (mBluetoothLeService == null) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
                return;
            }

            if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG, "case READ_WRITE_SETNOTI : is not bt device... mUseIoTGateway == false");
                return;
            }

            if (mConnectedDeviceList.contains(ioTHandleData.getDeviceId())
                    || mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) {
                ioTHandleData.setMsgId(msgId);
                ioTHandleData.setRequestCommand(msg.what);

                boolean result = true;
                switch (msg.what) {
                case IoTServiceCommand.DEVICE_READ_DATA:
                    result = mBluetoothLeService.readCharacteristic(ioTHandleData.getDeviceId(),
                            ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid());
                    break;
                case IoTServiceCommand.DEVICE_WRITE_DATA:
                    result = mBluetoothLeService.writeRemoteCharacteristic(ioTHandleData.getDeviceId(),
                            ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid(),
                            ioTHandleData.getValue());
                    break;
                case IoTServiceCommand.DEVICE_SET_NOTIFICATION:
                    result = mBluetoothLeService.setCharacteristicNotification(ioTHandleData.getDeviceId(),
                            ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid(), true);
                    break;
                }

                if (result) {
                    mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData);
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.SUCCESS);
                } else {
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.FAILED);
                }
            } else {
                Log.w(TAG, "mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) is false");
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
            }
        }
        break;
    }

    }
}

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());
    }/*ww w.j  a  v  a  2  s .  co 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;
    }/*from w ww .  j av  a  2 s  .  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;
    }
}