Example usage for android.bluetooth BluetoothAdapter isEnabled

List of usage examples for android.bluetooth BluetoothAdapter isEnabled

Introduction

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

Prototype

@RequiresPermission(Manifest.permission.BLUETOOTH)
public boolean isEnabled() 

Source Link

Document

Return true if Bluetooth is currently enabled and ready for use.

Usage

From source file:com.bluewatcher.activity.BlueWatcherActivity.java

private boolean isBluetoothEnabled() {
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

    if (bluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_LONG).show();
        finish();//from www  .ja  v a  2s  .  c  o  m
    }

    boolean enabled = true;
    if (!bluetoothAdapter.isEnabled()) {
        enabled = false;
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH);
    }
    return enabled;
}

From source file:cordova.plugins.Diagnostic.java

public boolean isBluetoothEnabled() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean result = mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
    return result;
}

From source file:com.sonymobile.dronecontrol.activity.MainActivity.java

private boolean verifyBluetooth() {
    boolean result = false;
    final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter == null) {
        // Device does not support Bluetooth
    } else if (btAdapter.isEnabled()) {
        result = true;/*  ww w  . j  av a 2s .co m*/
    } else {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Bluetooth").setMessage(R.string.DG_TURN_ON_BT)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        btAdapter.enable();
                        dialog.dismiss();
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }
    return result;
}

From source file:com.trigger_context.Main_Service.java

private boolean testConditions(String mac) {
    SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE);
    Map<String, ?> cond_map = conditions.getAll();
    Set<String> key_set = cond_map.keySet();
    boolean takeAction = true;
    if (key_set.contains("bluetooth")) {
        // checking the current state against the state set by the user
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        takeAction = new Boolean(bluetoothAdapter.isEnabled())
                .equals(conditions.getString("bluetooth", "false"));
    }//www. j a  v a2s.c  o  m
    if (takeAction && key_set.contains("wifi")) {
        final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        takeAction = new Boolean(wm.isWifiEnabled()) == conditions.getBoolean("wifi", false);
    }

    if (takeAction && key_set.contains("gps")) {
        final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        takeAction = new Boolean(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                .equals(conditions.getString("gps", "false"));
    }
    if (takeAction && key_set.contains("sms")) {
        final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
        Cursor c = getContentResolver().query(SMS_INBOX, null, "read = 0", null, null);
        if (c != null) {
            int unreadMessagesCount = c.getCount();
            c.close();
            takeAction = new Boolean(unreadMessagesCount > 0).equals(conditions.getString("sms", "false"));
        } else {
            takeAction = false;
        }
    }

    // "NOT TESTED" head set, missed call, accelerometer, proximity, gyro,
    // orientation
    if (takeAction && key_set.contains("headset")) {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        takeAction = am.isMusicActive() == conditions.getBoolean("headset", false);
        // am.isWiredHeadsetOn() is deprecated

    }
    /*
     * if(takeAction && key_set.contains("missedCall")) { final String[]
     * projection = null; final String selection = null; final String[]
     * selectionArgs = null; final String sortOrder =
     * android.provider.CallLog.Calls.DATE + " DESC"; Cursor cursor = null;
     * try{ cursor = getApplicationContext().getContentResolver().query(
     * Uri.parse("content://call_log/calls"), projection, selection,
     * selectionArgs, sortOrder); while (cursor.moveToNext()) { String
     * callLogID =
     * cursor.getString(cursor.getColumnIndex(android.provider.CallLog
     * .Calls._ID)); String callNumber =
     * cursor.getString(cursor.getColumnIndex
     * (android.provider.CallLog.Calls.NUMBER)); String callDate =
     * cursor.getString
     * (cursor.getColumnIndex(android.provider.CallLog.Calls.DATE)); String
     * callType =
     * cursor.getString(cursor.getColumnIndex(android.provider.CallLog
     * .Calls.TYPE)); String isCallNew =
     * cursor.getString(cursor.getColumnIndex
     * (android.provider.CallLog.Calls.NEW)); if(Integer.parseInt(callType)
     * == android.provider.CallLog.Calls.MISSED_CALL_TYPE &&
     * Integer.parseInt(isCallNew) > 0){
     * 
     * } } }catch(Exception ex){ }finally{ cursor.close(); }
     * 
     * }
     */
    return takeAction;
}

From source file:net.emilymaier.movebot.MoveBotActivity.java

@Override
@SuppressWarnings({ "deprecation", "unchecked" })
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from w w  w. ja v  a 2s.  c  om

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    Units.initialize(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    runs = new ArrayList<>();
    try {
        FileInputStream fis = openFileInput("runs.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        runs = (ArrayList<Run>) ois.readObject();
        ois.close();
        fis.close();
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        throw new RuntimeException("IOException", e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("ClassNotFoundException", e);
    }

    font = Typeface.createFromAsset(getAssets(), "fonts/led_real.ttf");
    pager = (ViewPager) findViewById(R.id.pager);
    adapter = new MainPagerAdapter(getSupportFragmentManager());
    runsFragment = new RunsFragment();
    heartFragment = new HeartFragment(this);
    developerFragment = new DeveloperFragment();
    controlFragment = new ControlFragment();
    mapFragment = SupportMapFragment.newInstance();
    pager.setAdapter(adapter);
    updateDeveloperMode();
    gpsInfoTimer = new Timer();
    gpsInfoTimer.schedule(new GpsInfoTask(), 2 * 1000);
    mapFragment.getMapAsync(this);

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter != null) {
        if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
        }
    }
}

From source file:com.t2.biofeedback.BioFeedbackService.java

/**
 * Sends a JSON encoded string containing the status of the bluetooth system and devices
 *    name: name of paired bluetooth device
 *  address: BT address of paired bluetooth device
 *  enabled: whether or not the device is enabled by the user
 *  //from  w ww .ja  v a2s .co  m
 *  Note that a special name (system) is reserved for the bluetooth system in general
 *  (to tell whether or not bluetooth is enabled by the user
 * 
 * 
 * @param context
 */
private void sendDeviceList() {

    boolean bluetoothEnabled = false;
    // First see if bluetooth is enabled
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        Log.e(TAG, "Device does not support Bluetooth");
        return;
    }

    if (mBluetoothAdapter.isEnabled()) {
        bluetoothEnabled = true;
    }

    JSONArray jsonArray = new JSONArray();
    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "system");
        jsonObject.put("address", "");
        jsonObject.put("enabled", bluetoothEnabled);
        jsonObject.put("connectionStatus", 0); // Don't care for this one

        jsonArray.put(jsonObject);

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }

    if (deviceManager != null) {

        BioFeedbackDevice[] bondedDevices = deviceManager.getBondedDevices();
        BioFeedbackDevice[] enabledDevices = deviceManager.getEnabledDevices();
        for (BioFeedbackDevice d : bondedDevices) {
            // See if it's enabled
            boolean enabled = false;
            int connectionStatus = CONN_IDLE; // Default

            for (BioFeedbackDevice dEnabled : enabledDevices) {
                if (d.getAddress().equalsIgnoreCase(dEnabled.getAddress())) {
                    enabled = true;
                    if (d.isConencted()) {
                        connectionStatus = CONN_CONNECTED;
                    } else if (d.isConnecting()) {
                        connectionStatus = CONN_CONNECTING;
                    } else {
                        connectionStatus = CONN_PAIRED;
                    }
                }
            }

            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", d.getName());
                jsonObject.put("address", d.getAddress());
                jsonObject.put("enabled", enabled);
                jsonObject.put("connectionStatus", connectionStatus);

                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                Log.e(TAG, e.toString());
            }
        }
        Log.d(TAG, "JSON paired devices = " + jsonArray.toString());

        // TOTO: we should probably change this from broadcast to use the ipc messaging channels
        Intent i = new Intent();
        i.setAction("com.t2.biofeedback.service.status.BROADCAST");
        i.putExtra(EXTRA_MESSAGE_TYPE, BroadcastMessage.Type.STATUS);
        i.putExtra(EXTRA_MESSAGE_ID, "STATUS_PAIRED_DEVICES");
        i.putExtra(EXTRA_TIMESTAMP, System.currentTimeMillis());
        i.putExtra(EXTRA_ADDRESS, jsonArray.toString());
        sendBroadcast(i);
    } else {
        Log.e(TAG, "NEW no device manager");
    }
}

From source file:org.envirocar.app.activity.MainActivity.java

protected void updateStartStopButton() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null && adapter.isEnabled()) { // was requirementsFulfilled
        createStartStopUtil().updateStartStopButtonOnServiceStateChange(navDrawerItems[START_STOP_MEASUREMENT]);
    } else {/* ww  w. j a v  a  2 s  .  c om*/
        createStartStopUtil().defineButtonContents(navDrawerItems[START_STOP_MEASUREMENT], false,
                R.drawable.not_available, getString(R.string.pref_bluetooth_disabled),
                getString(R.string.menu_start));
    }

    navDrawerAdapter.notifyDataSetChanged();
}

From source file:org.apache.cordova.sipkita.BluetoothPrinter.java

void listBT(CallbackContext callbackContext) {
    BluetoothAdapter mBluetoothAdapter = null;
    String errMsg = null;/*w w  w .j  av  a 2 s  .c o m*/
    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothPort = BluetoothPort.getInstance();
        if (mBluetoothAdapter == null) {
            errMsg = "No bluetooth adapter available";
            Log.e(LOG_TAG, errMsg);
            callbackContext.error(errMsg);
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            this.cordova.getActivity().startActivityForResult(enableBluetooth, 2);
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            JSONArray json = new JSONArray();
            for (BluetoothDevice device : pairedDevices) {
                json.put(device.getName());
            }
            callbackContext.success(json);
        } else {
            callbackContext.error("No Bluetooth Device Found");
        }
        //         Log.d(LOG_TAG, "Bluetooth Device Found: " + mmDevice.getName());
    } catch (Exception e) {
        errMsg = e.getMessage();
        Log.e(LOG_TAG, errMsg);
        e.printStackTrace();
        callbackContext.error(errMsg);
    }
}

From source file:com.buddi.client.dfu.DfuActivity.java

private boolean isBLEEnabled() {
    final BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    final BluetoothAdapter adapter = manager.getAdapter();
    return adapter != null && adapter.isEnabled();
}

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

private void addDevice() {
    // Get a set of currently paired devices
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter.isEnabled()) {
        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
        // launch dialog to select device
        if (pairedDevices.size() > 0) {
            int p = 0;
            final String[] pairedDeviceNames = new String[pairedDevices.size()];
            final String[] pairedDeviceAddresses = new String[pairedDevices.size()];
            for (BluetoothDevice device : pairedDevices) {
                pairedDeviceNames[p] = device.getName();
                pairedDeviceAddresses[p++] = device.getAddress();
            }//from   w  w  w  .  ja v a 2 s  .  c  om
            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                    .setItems(pairedDeviceNames, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            addNewDevice(pairedDeviceNames[which], pairedDeviceAddresses[which]);
                        }

                    })
                    .setPositiveButton(getString(R.string.btn_bt_scan), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (mServiceInterface != null) {
                                try {
                                    mServiceInterface.requestDiscovery();
                                    mProgressDialog = new ProgressDialog(TapLockSettings.this);
                                    mProgressDialog.setMessage(getString(R.string.msg_scanning));
                                    mProgressDialog.setCancelable(true);
                                    mProgressDialog.show();
                                } catch (RemoteException e) {
                                    Log.e(TAG, e.toString());
                                }
                            }
                        }
                    }).create();
            mDialog.show();
        } else {
            if (mServiceInterface != null) {
                try {
                    mServiceInterface.requestDiscovery();
                    mProgressDialog = new ProgressDialog(this);
                    mProgressDialog.setMessage(getString(R.string.msg_scanning));
                    mProgressDialog.setCancelable(true);
                    mProgressDialog.show();
                } catch (RemoteException e) {
                    Log.e(TAG, e.toString());
                }
            }
        }
    } else {
        mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.ttl_enablebt)
                .setMessage(R.string.msg_enablebt)
                .setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mServiceInterface != null) {
                            try {
                                mServiceInterface.enableBluetooth();
                            } catch (RemoteException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                }).create();
        mDialog.show();
    }
}