Java Code Examples for android.bluetooth.BluetoothAdapter#isEnabled()

The following examples show how to use android.bluetooth.BluetoothAdapter#isEnabled() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LollipopScanner.java    From RxCentralBle with Apache License 2.0 7 votes vote down vote up
private void startScan(PublishSubject scanDataSubject) {
  BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  if (adapter != null && adapter.isEnabled()) {
    // Setting service uuid scan filter failing on Galaxy S6 on Android 7.
    // Other devices and versions of Android have additional issues with Scan Filters.
    // Manually filter on scan operation.  Add a dummy filter to avoid Android 8.1+ enforcement
    // of filters during background scanning.
    List<ScanFilter> filters = new ArrayList<>();
    ScanFilter.Builder scanFilterBuilder = new ScanFilter.Builder();
    filters.add(scanFilterBuilder.build());

    ScanSettings.Builder settingsBuilder = new ScanSettings.Builder();
    settingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);

    BluetoothLeScanner bleScanner = adapter.getBluetoothLeScanner();
    if (bleScanner != null) {
      bleScanner.startScan(filters, settingsBuilder.build(), scanCallback);
    } else {
      if (RxCentralLogger.isError()) {
        RxCentralLogger.error("startScan - BluetoothLeScanner is null!");
      }

      scanDataSubject.onError(new ConnectionError(SCAN_FAILED));
    }
  } else {
    if (RxCentralLogger.isError()) {
      if (adapter == null) {
        RxCentralLogger.error("startScan - Default Bluetooth Adapter is null!");
      } else {
        RxCentralLogger.error("startScan - Bluetooth Adapter is disabled.");
      }
    }

    scanDataSubject.onError(new ConnectionError(SCAN_FAILED));
  }

}
 
Example 2
Source File: BleUtils.java    From Bluefruit_LE_Connect_Android with MIT License 6 votes vote down vote up
public static int getBleStatus(Context context) {
    if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        return STATUS_BLE_NOT_AVAILABLE;
    }

    final BluetoothAdapter adapter = getBluetoothAdapter(context);
    // Checks if Bluetooth is supported on the device.
    if (adapter == null) {
        return STATUS_BLUETOOTH_NOT_AVAILABLE;
    }

    if (!adapter.isEnabled()) {
        return STATUS_BLUETOOTH_DISABLED;
    }

    return STATUS_BLE_ENABLED;
}
 
Example 3
Source File: EspMainActivity.java    From esp-idf-provisioning-android with Apache License 2.0 6 votes vote down vote up
private void addDeviceClick() {

        if (BuildConfig.isQrCodeSupported) {

            gotoQrCodeActivity();

        } else {

            if (deviceType.equals(AppConstants.DEVICE_TYPE_BLE) || deviceType.equals(AppConstants.DEVICE_TYPE_BOTH)) {

                final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
                BluetoothAdapter bleAdapter = bluetoothManager.getAdapter();

                if (!bleAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                } else {
                    startProvisioningFlow();
                }
            } else {
                startProvisioningFlow();
            }
        }
    }
 
Example 4
Source File: BluetoothManager.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 他の機器から探索可能になるように要求する
 * bluetoothに対応していないか無効になっている時はIllegalStateException例外を投げる
 * @param activity
 * @param duration 探索可能時間[秒]
 * @return 既に探索可能であればtrue
 * @throws IllegalStateException
 */
public static boolean requestDiscoverable(@NonNull final Activity activity, final int duration) throws IllegalStateException {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	if ((adapter == null) || !adapter.isEnabled()) {
		throw new IllegalStateException("bluetoothに対応していないか無効になっている");
	}
	if (adapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
		final Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, duration);
		activity.startActivity(intent);
	}
	return adapter.getScanMode() == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE;
}
 
Example 5
Source File: BluetoothManager.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 他の機器から探索可能になるように要求する
 * bluetoothに対応していないか無効になっている時はIllegalStateException例外を投げる
 * @param fragment
 * @param duration 0以下ならデフォルトの探索可能時間で120秒、 最大300秒まで設定できる
 * @return
 * @throws IllegalStateException
 */
public static boolean requestDiscoverable(@NonNull final Fragment fragment, final int duration) throws IllegalStateException {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	if ((adapter == null) || !adapter.isEnabled()) {
		throw new IllegalStateException("bluetoothに対応していないか無効になっている");
	}
	if (adapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
		final Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		if ((duration > 0) && (duration <= 300)) {
			intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, duration);
		}
		fragment.startActivity(intent);
	}
	return adapter.getScanMode() == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE;
}
 
Example 6
Source File: BluetoothUtils.java    From SimpleSmsRemote with MIT License 6 votes vote down vote up
/**
 * set bluetooth state
 *
 * @param enabled bluetooth state
 * @throws Exception
 */
public static void SetBluetoothState(boolean enabled) throws Exception {
    BluetoothAdapter bluetoothAdapter = getDefaultBluetoothHandle();

    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enabled && !isEnabled) {
        if (!bluetoothAdapter.enable())
            throw new Exception("enabling bluetooth failed");
    } else if (!enabled && isEnabled) {
        if (!bluetoothAdapter.disable())
            throw new Exception("disabling bluetooth failed");
    }
}
 
Example 7
Source File: BleManager.java    From EasyBle with Apache License 2.0 6 votes vote down vote up
/**
 * Turn on local bluetooth, calling the method will show users a request dialog
 * to grant or reject,so you can get the result from Activity#onActivityResult()
 *
 * @param activity    activity, note that to get the result whether users have granted
 *                    or rejected to enable bluetooth, you should handle the method
 *                    onActivityResult() of this activity
 * @param requestCode enable bluetooth request code
 */
public static void enableBluetooth(Activity activity, int requestCode) {
    if (activity == null || requestCode < 0) {
        return;
    }
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null && !adapter.isEnabled()) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activity.startActivityForResult(intent, requestCode);
    }
}
 
Example 8
Source File: GattServerActivity.java    From sample-bluetooth-le-gattserver with Apache License 2.0 6 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();

    BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter();
    if (bluetoothAdapter.isEnabled()) {
        stopServer();
        stopAdvertising();
    }

    unregisterReceiver(mBluetoothReceiver);
}
 
Example 9
Source File: HomeActivity.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
private void updateBlueToothStatus() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        mBtImg.setImageResource(R.drawable.bt_off);
    } else {
        if (mBluetoothAdapter.isEnabled()) {
            mBtImg.setImageResource(R.drawable.bt_on);
        } else {
            mBtImg.setImageResource(R.drawable.bt_off);
        }
    }
}
 
Example 10
Source File: DalvikBleService.java    From attach with GNU General Public License v3.0 6 votes vote down vote up
private void init() {
    Log.v(TAG, "DalvikBle, init");
    boolean fineloc = Util.verifyPermissions(Manifest.permission.ACCESS_FINE_LOCATION);
    if (!fineloc) {
        Log.v(TAG, "No permission to get fine location");
    }
    final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (!adapter.isEnabled()) {
        Log.v(TAG, "DalvikBle, init, adapter not enabled");
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        IntentHandler intentHandler = new IntentHandler() {
            @Override
            public void gotActivityResult (int requestCode, int resultCode, Intent intent) {
                if (requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_OK) {
                    scanner = adapter.getBluetoothLeScanner();
                }
            }
        };

        if (activity == null) {
            LOG.log(Level.WARNING, "Activity not found. This service is not allowed when "
                    + "running in background mode or from wearable");
            return;
        }
        Util.setOnActivityResultHandler(intentHandler);

        // A dialog will appear requesting user permission to enable Bluetooth
        activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

    } else {
        scanner = adapter.getBluetoothLeScanner();
    }

}
 
Example 11
Source File: MainActivity.java    From PodEmu with GNU General Public License v3.0 6 votes vote down vote up
public void start_stop_service(View v)
{


    if(serviceBound)
    {
        PodEmuLog.debug("MA: Stop service initiated...");
        stop_service(v);
    }
    else
    {
        BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();

        if( bt!=null && bluetoothEnabled && !bt.isEnabled() )
        {
            PodEmuLog.debug("MA: bt requested but not enabled. Not starting service.");
            requestBluetoothPermissions();
            return;
        }
        PodEmuLog.debug("MA: Start service initiated...");
        start_service();
    }
}
 
Example 12
Source File: TaskbarController.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
private Drawable getBluetoothDrawable() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if(adapter != null && adapter.isEnabled())
        return getDrawableForSysTray(R.drawable.tb_bluetooth);

    return null;
}
 
Example 13
Source File: BluetoothUtil.java    From Rumble with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isEnabled() {
    BluetoothAdapter adapter = BluetoothUtil.getBluetoothAdapter(RumbleApplication.getContext());
    if(adapter == null)
        return false;
    return adapter.isEnabled();
}
 
Example 14
Source File: SettingsActivity.java    From PodEmu with GNU General Public License v3.0 5 votes vote down vote up
public void selectBluetoothDevice(View v)
{
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    if( btAdapter != null && btAdapter.isEnabled() && btDevices.size() > 0 )
    {
        BluetoothDeviceDialogFragment bluetoothDeviceDialog = new BluetoothDeviceDialogFragment();
        bluetoothDeviceDialog.setBluetoothDevices(btDevices);
        bluetoothDeviceDialog.show(getSupportFragmentManager(), "bt_tag");
    }
    else
    {
        new AlertDialog.Builder(this)
                .setTitle("Warning")
                .setMessage("No paired devices found or bluetooth is disabled. Please go to bluetooth settings and pair device first. Please also ensure that bluetooth is enabled.")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // continue with action
                    }
                })

                /* Disabled BLE in v45

                .setNegativeButton("Scan BLE", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
                        {
                            BluetoothLEDeviceDialogFragment bluetoothLEDeviceDialog = new BluetoothLEDeviceDialogFragment();
                            bluetoothLEDeviceDialog.show(getSupportFragmentManager(), "ble_tag");
                        }
                        else
                        {
                            Toast.makeText(SettingsActivity.this, R.string.bleNotSupported, Toast.LENGTH_SHORT).show();
                        }

                    }
                })
                */

                .setIcon(android.R.drawable.ic_dialog_info)
                .show();
    }
}
 
Example 15
Source File: BeaconsFragment.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Checks whether the Bluetooth adapter is enabled.
 */
private boolean isBleEnabled() {
    final BluetoothManager bm = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
    final BluetoothAdapter ba = bm.getAdapter();
    return ba != null && ba.isEnabled();
}
 
Example 16
Source File: BluetoothUtils.java    From microbit with Apache License 2.0 5 votes vote down vote up
public static ConnectedDevice getPairedMicrobit(Context ctx) {
    SharedPreferences pairedDevicePref = ctx.getApplicationContext().getSharedPreferences(PREFERENCES_KEY,
            Context.MODE_MULTI_PROCESS);

    if(sConnectedDevice == null) {
        sConnectedDevice = new ConnectedDevice();
    }

    if(pairedDevicePref.contains(PREFERENCES_PAIREDDEV_KEY)) {
        boolean pairedMicrobitInSystemList = false;
        String pairedDeviceString = pairedDevicePref.getString(PREFERENCES_PAIREDDEV_KEY, null);
        Gson gson = new Gson();
        sConnectedDevice = gson.fromJson(pairedDeviceString, ConnectedDevice.class);
        //Check if the microbit is still paired with our mobile
        BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context
                .BLUETOOTH_SERVICE)).getAdapter();
        if(mBluetoothAdapter.isEnabled()) {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            for(BluetoothDevice bt : pairedDevices) {
                if(bt.getAddress().equals(sConnectedDevice.mAddress)) {
                    pairedMicrobitInSystemList = true;
                    break;
                }
            }
        } else {
            //Do not change the list until the Bluetooth is back ON again
            pairedMicrobitInSystemList = true;
        }

        if(!pairedMicrobitInSystemList) {
            Log.e("BluetoothUtils", "The last paired microbit is no longer in the system list. Hence removing it");
            //Return a NULL device & update preferences
            sConnectedDevice.mPattern = null;
            sConnectedDevice.mName = null;
            sConnectedDevice.mStatus = false;
            sConnectedDevice.mAddress = null;
            sConnectedDevice.mPairingCode = 0;
            sConnectedDevice.mfirmware_version = null;
            sConnectedDevice.mlast_connection_time = 0;

            setPairedMicroBit(ctx, null);
        }
    } else {
        sConnectedDevice.mPattern = null;
        sConnectedDevice.mName = null;
    }
    return sConnectedDevice;
}
 
Example 17
Source File: DefaultPreconditions.java    From neurosky-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isBluetoothEnabled(BluetoothAdapter bluetoothAdapter) {
  return (bluetoothAdapter != null && bluetoothAdapter.isEnabled());
}
 
Example 18
Source File: BluetoothManager.java    From libcommon with Apache License 2.0 4 votes vote down vote up
/**
 * 端末がBluetoothに対応しているが無効になっていれば有効にするように要求する
 * 前もってbluetoothAvailableで対応しているかどうかをチェックしておく
 * Bluetoothを有効にするように要求した時は#onActivityResultメソッドで結果を受け取る
 * 有効にできればRESULT_OK, ユーザーがキャンセルするなどして有効に出来なければRESULT_CANCELEDが返る
 * @param fragment
 * @param requestCode
 * @return true Bluetoothに対応していて既に有効になっている
 * @throws SecurityException パーミッションがなければSecurityExceptionが投げられる
 */
public static boolean requestBluetoothEnable(@NonNull final Fragment fragment, final int requestCode) throws SecurityException {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	if ((adapter != null) && !adapter.isEnabled()) {
		final Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		fragment.startActivityForResult(intent, requestCode);
	}
	return adapter != null && adapter.isEnabled();
}
 
Example 19
Source File: BluetoothManager.java    From libcommon with Apache License 2.0 4 votes vote down vote up
/**
 * 端末がBluetoothに対応しているが無効になっていれば有効にするように要求する
 * 前もってbluetoothAvailableで対応しているかどうかをチェックしておく
 * Bluetoothを有効にするように要求した時は#onActivityResultメソッドで結果を受け取る
 * 有効にできればRESULT_OK, ユーザーがキャンセルするなどして有効に出来なければRESULT_CANCELEDが返る
 * @param activity
 * @param requestCode
 * @return true Bluetoothに対応していて既に有効になっている
 * @throws SecurityException パーミッションがなければSecurityExceptionが投げられる
 */
public static boolean requestBluetoothEnable(@NonNull final Activity activity, final int requestCode) throws SecurityException {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	if ((adapter != null) && !adapter.isEnabled()) {
		final Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		activity.startActivityForResult(intent, requestCode);
	}
	return adapter != null && adapter.isEnabled();
}
 
Example 20
Source File: Utils.java    From mcumgr-android with Apache License 2.0 3 votes vote down vote up
/**
 * Checks whether Bluetooth is enabled.
 *
 * @return True if Bluetooth is enabled, false otherwise.
 */
public static boolean isBleEnabled() {
    final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    return adapter != null && adapter.isEnabled();
}