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

The following examples show how to use android.bluetooth.BluetoothAdapter#enable() . These examples are extracted from open source projects. 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 Project: blefun-androidthings   File: GattServer.java    License: Apache License 2.0 6 votes vote down vote up
public void onCreate(Context context, GattServerListener listener) throws RuntimeException {
    mContext = context;
    mListener = listener;

    mBluetoothManager = (BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter();
    if (!checkBluetoothSupport(bluetoothAdapter)) {
        throw new RuntimeException("GATT server requires Bluetooth support");
    }

    // Register for system Bluetooth events
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    mContext.registerReceiver(mBluetoothReceiver, filter);
    if (!bluetoothAdapter.isEnabled()) {
        Log.d(TAG, "Bluetooth is currently disabled... enabling");
        bluetoothAdapter.enable();
    } else {
        Log.d(TAG, "Bluetooth enabled... starting services");
        startAdvertising();
        startServer();
    }
}
 
Example 2
@Override
public void handleClick() {
    if (mBluetoothEnableForTether)
        return;

    if (isTetheringOn()) {
        setTethering(false);
    } else {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
                mBluetoothEnableForTether = true;
                adapter.enable();
            } else if (adapter.getState() == BluetoothAdapter.STATE_ON) {
                setTethering(true);
            }
        }
    }
    refreshState();
}
 
Example 3
Source Project: react-native-obd2   File: OBD2Handler.java    License: MIT License 6 votes vote down vote up
public void ready() {

    // onStart
    final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    // onResume
    // get Bluetooth device
    mPreRequisites = btAdapter != null && btAdapter.isEnabled();
    if (!mPreRequisites) {
      mPreRequisites = btAdapter != null && btAdapter.enable();
    }

    if (!mPreRequisites) {
      sendDeviceStatus(EVENTNAME_BT_STATUS, "disabled");
    } else {
      sendDeviceStatus(EVENTNAME_BT_STATUS, "ready");
    }

    sendDeviceStatus(EVENTNAME_OBD_STATUS, "disconnected");
  }
 
Example 4
Source Project: SimpleSmsRemote   File: BluetoothUtils.java    License: 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 5
@Override
protected void onResume() {
    super.onResume();

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter != null) {
        if (!mBluetoothAdapter.isEnabled()) mBluetoothAdapter.enable();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

        if (mBluetoothLeScanner == null) {
            mBluetoothAdapter.enable();
            mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
        }
        startScan();
    }
}
 
Example 6
private void startBLScan() {
    if (!scanning) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) bluetoothAdapter.enable();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
            registerReceiver(broadcastReceiver, intentFilter);
            bluetoothAdapter.startDiscovery();
            scanning = true;
        }
    }
}
 
Example 7
Source Project: EasyBle   File: BleManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Turn on or off local bluetooth directly without showing users a request
 * dialog.
 * Note that a request dialog may still show when you call this method, due to
 * some special Android devices' system may have been modified by manufacturers
 *
 * @param enable enable or disable local bluetooth
 */
public static void toggleBluetooth(boolean enable) {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null) {
        return;
    }
    if (enable) {
        adapter.enable();
    } else {
        if (adapter.isEnabled()) {
            adapter.disable();
        }
    }
}
 
Example 8
@Override
public BLEError enable() {
    BluetoothAdapter adapter = getAdapter();
    if (adapter == null) {
        return BLEError.noAdapter;
    }
    adapter.enable();
    return BLEError.ok;
}
 
Example 9
public static boolean openBluetooth() {
    BluetoothAdapter adapter = getBluetoothAdapter();
    if (adapter != null) {
        return adapter.enable();
    }
    return false;
}
 
Example 10
Source Project: Aerlink-for-Android   File: BluetoothUtils.java    License: MIT License 5 votes vote down vote up
public static void restartBluetooth(BluetoothAdapter bluetoothAdapter) {
    try {
        if (bluetoothAdapter != null) {
            if (bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.disable();
            }
            bluetoothAdapter.enable();

            Log.d(LOG_TAG, "Disabling bluetooth");
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 11
Source Project: bridgefy-android-samples   File: MainActivity.java    License: MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    unbinder = ButterKnife.bind(this);
    deviceText.setText(Build.MANUFACTURER + " " + Build.MODEL);

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (isThingsDevice(this)) {
        // enabling bluetooth automatically
        bluetoothAdapter.enable();
    }

    Bridgefy.initialize(getApplicationContext(), "API_KEY", new RegistrationListener() {
        @Override
        public void onRegistrationSuccessful(BridgefyClient bridgefyClient) {
            // Important data can be fetched from the BridgefyClient object
            deviceId.setText(bridgefyClient.getUserUuid());

            // Once the registration process has been successful, we can start operations
            Bridgefy.start(messageListener, stateListener);
        }

        @Override
        public void onRegistrationFailed(int i, String e) {
            Log.e(TAG, e);
        }
    });

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}
 
Example 12
Source Project: bridgefy-android-samples   File: MainActivity.java    License: MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Configure the Toolbar
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle(getTitle());

    RecyclerView recyclerView = findViewById(R.id.peer_list);
    recyclerView.setAdapter(peersAdapter);


    if (isThingsDevice(this)) {
        //enabling bluetooth automatically
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.enable();
    }

    Bridgefy.initialize(getApplicationContext(), new RegistrationListener() {
        @Override
        public void onRegistrationSuccessful(BridgefyClient bridgefyClient) {
            // Start Bridgefy
            startBridgefy();
        }

        @Override
        public void onRegistrationFailed(int errorCode, String message) {
            Toast.makeText(getBaseContext(), getString(R.string.registration_error),
                    Toast.LENGTH_LONG).show();
        }
    });
}
 
Example 13
Source Project: bridgefy-android-samples   File: MainActivity.java    License: MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(toolbar);

    // load our username
    username = getSharedPreferences(Constants.PREFS_NAME, 0).getString(Constants.PREFS_USERNAME, null);

    if (BridgefyListener.isThingsDevice(this)) {
        //if this device is running Android Things, don't go through any UI interaction and
        //start right away
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //enabling bluetooth automatically
        bluetoothAdapter.enable();

        username = Build.MANUFACTURER + " " + Build.MODEL;
        // initialize the Bridgefy framework
        Bridgefy.initialize(getBaseContext(), registrationListener);
        setupList();

    } else {
        // check that we have permissions, otherwise fire the IntroActivity
        if ((ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
                (username == null)) {
            startActivity(new Intent(getBaseContext(), IntroActivity.class));
            finish();
        } else {
            // initialize the Bridgefy framework
            Bridgefy.initialize(getBaseContext(), registrationListener);
            setupList();
        }
    }
}
 
Example 14
private static void changeBluetoothState(Intent intent) {
    try {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        int labelResId;
        if (intent.hasExtra(AShortcut.EXTRA_ENABLE)) {
            if (intent.getBooleanExtra(AShortcut.EXTRA_ENABLE, false)) {
                btAdapter.enable();
                labelResId = R.string.bluetooth_on;
            } else {
                btAdapter.disable();
                labelResId = R.string.bluetooth_off;
            }
        } else {
            if (btAdapter.isEnabled()) {
                labelResId = R.string.bluetooth_off;
                btAdapter.disable();
            } else {
                btAdapter.enable();
                labelResId = R.string.bluetooth_on;
            }
        }
        if (intent.getBooleanExtra(AShortcut.EXTRA_SHOW_TOAST, false)) {
            Utils.postToast(mContext, labelResId);
        }
    } catch (Throwable t) {
        XposedBridge.log(t);
    }
}
 
Example 15
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_server);

    mLocalTimeView = (TextView) findViewById(R.id.text_time);

    // Devices with a display should not go to sleep
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter();
    // We can't continue without proper Bluetooth support
    if (!checkBluetoothSupport(bluetoothAdapter)) {
        finish();
    }

    // Register for system Bluetooth events
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBluetoothReceiver, filter);
    if (!bluetoothAdapter.isEnabled()) {
        Log.d(TAG, "Bluetooth is currently disabled...enabling");
        bluetoothAdapter.enable();
    } else {
        Log.d(TAG, "Bluetooth enabled...starting services");
        startAdvertising();
        startServer();
    }
}
 
Example 16
private static void switchBluetooth() {

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

        if (adapter.isEnabled()) {

            adapter.disable();

            MyApplication.getMainThreadHandler().post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "蓝牙已关闭", Toast.LENGTH_SHORT).show();
                }
            });

        } else {

            adapter.enable();
            MyApplication.getMainThreadHandler().post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "蓝牙已开启", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }
 
Example 17
Source Project: LibreTasks   File: SignalsActionService.java    License: Apache License 2.0 5 votes vote down vote up
/**
  * turn on the bluetooth. 
  */
 private void turnOnBluetooth() {
   BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
	mBluetoothAdapter.enable(); 
}
   ResultProcessor.process(this, intent, ResultProcessor.RESULT_SUCCESS,
       getString(R.string.bluetooth_turned_on));
 }
 
Example 18
Source Project: bitgatt   File: GattServerTests.java    License: Mozilla Public License 2.0 4 votes vote down vote up
@Test
public void btOffOnWillClearServicesAndThatGattServerIfStartedWillRetunrAfterToggle() throws InterruptedException {
    // should do nothing if already started
    final CountDownLatch cdl = new CountDownLatch(2);
    BluetoothAdapter adapter = new GattUtils().getBluetoothAdapter(mockContext);
    assertNotNull("adapter is null", adapter);
    AtomicBoolean isFirst = new AtomicBoolean(true);
    FitbitGatt.FitbitGattCallback cb = new NoOpGattCallback() {
        @Override
        public void onGattServerStarted(GattServerConnection serverConnection) {
            super.onGattServerStarted(serverConnection);
            if (isFirst.get()) {
                AddGattServerServiceTransaction transaction = new AddGattServerServiceTransaction(serverConnection, GattState.ADD_SERVICE_SUCCESS, liveData);
                serverConnection.runTx(transaction, result -> {
                    assertEquals(result.resultStatus, TransactionResult.TransactionResultStatus.SUCCESS);
                    adapter.disable();
                    isFirst.set(false);
                    cdl.countDown();
                });
            } else {
                BluetoothGattServer server = FitbitGatt.getInstance().getServer().getServer();
                List<BluetoothGattService> services = server.getServices();
                Assert.assertTrue(services.isEmpty());
                cdl.countDown();
            }
        }

        @Override
        public void onBluetoothOff() {
            super.onBluetoothOff();
            adapter.enable();
        }

    };
    FitbitGatt.getInstance().registerGattEventListener(cb);
    FitbitGatt.getInstance().startGattServer(mockContext);
    cdl.await(10, TimeUnit.SECONDS);
    if (cdl.getCount() != 0) {
        fail(String.format("Not all countdowns have been executed.Not Executed %d", cdl.getCount()));
    }
}
 
Example 19
public static void startBluetooth() {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!bluetoothAdapter.isEnabled()) {
        bluetoothAdapter.enable();
    }
}
 
Example 20
public void enableBluetooth() {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(bluetoothAdapter != null) {
        bluetoothAdapter.enable();
    }
}