android.bluetooth.BluetoothAdapter Java Examples

The following examples show how to use android.bluetooth.BluetoothAdapter. 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: BluetoothManager.java    From Linphone4Android with GNU General Public License v3.0 9 votes vote down vote up
private void startBluetooth() {
	if (isBluetoothConnected) {
		Log.e("[Bluetooth] Already started, skipping...");
		return;
	}
	
	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	
	if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
		if (mProfileListener != null) {
			Log.w("[Bluetooth] Headset profile was already opened, let's close it");
			mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
		}
		
		mProfileListener = new BluetoothProfile.ServiceListener() {
			public void onServiceConnected(int profile, BluetoothProfile proxy) {
			    if (profile == BluetoothProfile.HEADSET) {
			        Log.d("[Bluetooth] Headset connected");
			        mBluetoothHeadset = (BluetoothHeadset) proxy;
			        isBluetoothConnected = true;
			    }
			}
			public void onServiceDisconnected(int profile) {
			    if (profile == BluetoothProfile.HEADSET) {
			        mBluetoothHeadset = null;
			        isBluetoothConnected = false;
			        Log.d("[Bluetooth] Headset disconnected");
			        LinphoneManager.getInstance().routeAudioToReceiver();
			    }
			}
		};
		boolean success = mBluetoothAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET);
		if (!success) {
			Log.e("[Bluetooth] getProfileProxy failed !");
		}
	} else {
		Log.w("[Bluetooth] Interface disabled on device");
	}
}
 
Example #2
Source File: DisplayActivity.java    From DataLogger with MIT License 6 votes vote down vote up
public void onClick(View v) {
    int state = SharedPreferencesHelper.getBluetoothStatus(DisplayActivity.this);
    switch (state) {
        case Constants.BLUETOOTH_STATE_DISABLED:
            startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
            break;
        case Constants.BLUETOOTH_STATE_ENABLED:
        case Constants.BLUETOOTH_STATE_CONNECTING:
        case Constants.BLUETOOTH_STATE_CONNECTED:
            boolean isMaster = (mDeviceLocation == Constants.DEVICE_LOCATION_HAND);
            if (isMaster) {
                Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(discoverableIntent);
            } else {
                Intent serverIntent = new Intent(DisplayActivity.this, BluetoothDeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            }
            break;
    }
}
 
Example #3
Source File: BluetoothServerConnectionHelper.java    From tilt-game-android with MIT License 6 votes vote down vote up
public void setDiscoverable() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null) {
        return;
    }

    // change name if necessary
    String originalName = adapter.getName();
    if (originalName.lastIndexOf(_deviceNamePostFix) != originalName.length() - _deviceNamePostFix.length()) {
        if (_connectionHelperListener != null) {
            _connectionHelperListener.onAdapterNameChange(originalName);
        }

        Log.d(TAG, "setDiscoverable: Bluetooth device name set to " + (originalName + _deviceNamePostFix));
        adapter.setName(originalName + _deviceNamePostFix);
    }

    // set discoverable if necessary
    if (adapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        _activity.startActivity(discoverableIntent);
    }
}
 
Example #4
Source File: BCLServiceServer.java    From unity-bluetooth with MIT License 6 votes vote down vote up
private void discoverableDevice() {

        boolean bonded = false;
        for (BluetoothDevice device : mPairedDevices) {
            if (mPairingAddress.equals(device.getAddress())) {
                bonded = true;
                break;
            }
        }

        if (!bonded) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            mActivity.startActivity(discoverableIntent);
        }

        mAcceptThread = new AcceptThread();
        mAcceptThread.start();
    }
 
Example #5
Source File: GattServer.java    From blefun-androidthings with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);

    switch (state) {
        case BluetoothAdapter.STATE_ON:
            startAdvertising();
            startServer();
            break;
        case BluetoothAdapter.STATE_OFF:
            stopServer();
            stopAdvertising();
            break;
        default:
            // Do nothing
            break;
    }
}
 
Example #6
Source File: P_AndroidBluetoothManager.java    From AsteroidOSSync with GNU General Public License v3.0 6 votes vote down vote up
@Override public final void stopLeScan(BluetoothAdapter.LeScanCallback callback)
{
    if (m_adaptor != null)
    {
        if (m_bleManager.getScanManager().isPostLollipopScan())
        {
            L_Util.stopNativeScan(m_adaptor);
        }
        else
        {
            m_adaptor.stopLeScan(callback);
        }
    }
    else
        m_bleManager.getLogger().e("Tried to stop scan (if it's even running), but the Bluetooth Adaptor is null!");
}
 
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: AndroidAudioManager.java    From linphone-android with GNU General Public License v3.0 6 votes vote down vote up
private void startBluetooth() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter != null) {
        Log.i("[Audio Manager] [Bluetooth] Adapter found");
        if (mAudioManager.isBluetoothScoAvailableOffCall()) {
            Log.i("[Audio Manager] [Bluetooth] SCO available off call, continue");
        } else {
            Log.w("[Audio Manager] [Bluetooth] SCO not available off call !");
        }

        mBluetoothReceiver = new BluetoothReceiver();
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        mContext.registerReceiver(mBluetoothReceiver, filter);

        bluetoothAdapterStateChanged();
    }
}
 
Example #9
Source File: DashBoardActivity.java    From Android-Bluetooth-Fingerprint with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dash_board);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

    Toolbar toolbar = (Toolbar) findViewById(R.id.dash_board_toolbar);
    setSupportActionBar(toolbar);

    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        showSnackBar("Bluetooth is not available");
        finish();
    }
}
 
Example #10
Source File: BluetoothIntegration.java    From redalert-android with Apache License 2.0 6 votes vote down vote up
public static boolean isBluetoothEnabled() {
    // Must call Looper.prepare() due to ICS bug
    // And we can't call the function from UI thread when we receive a push notification)
    // http://stackoverflow.com/questions/5920578/bluetoothadapter-getdefault-throwing-runtimeexception-while-not-in-activity

    if (Looper.myLooper() == null) {
        Looper.prepare();
    }

    // Get bluetooth adapter
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Null means device doesn't support Bluetooth
    if (bluetoothAdapter == null) {
        // No Bluetooth support
        return false;
    }
    else {
        // Check if it's enabled and return the result
        return bluetoothAdapter.isEnabled();
    }
}
 
Example #11
Source File: DeviceScanActivity.java    From IoT-Firstep with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

  //如果没开蓝牙,请求打开蓝牙
    if (!mBluetoothAdapter.isEnabled()) {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    // Initializes list view adapter.
    mAdapter = new LeDeviceListAdapter(this);
    mLView.setAdapter(mAdapter);
    mLView.setOnItemClickListener(this);
    scanLeDevice(true);
}
 
Example #12
Source File: HomeActivity.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();

    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mLocationManager.addGpsStatusListener(mGpsStatusListener);

    mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mReceiver, intentFilter);

    updateBlueToothStatus();
}
 
Example #13
Source File: AddBeaconChoicePreferenceDummy.java    From PresencePublisher with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public AddBeaconChoicePreferenceDummy(Context context, Fragment fragment) {
    super(context);
    setKey(DUMMY);
    setIcon(android.R.drawable.ic_menu_add);
    setTitle(R.string.add_beacon_title);
    setSummary(R.string.add_beacon_summary);
    setOnPreferenceClickListener(prefs -> {
        BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager == null) {
            HyperLog.w(TAG, "Unable to get bluetooth manager");
        } else {
            BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                fragment.startActivityForResult(enableBtIntent, ON_DEMAND_BLUETOOTH_REQUEST_CODE);
                return true;
            }
        }
        BeaconScanDialogFragment instance = getInstance(getContext(), this::onScanResult,
                getSharedPreferences().getStringSet(BEACON_LIST, Collections.emptySet()));
        instance.show(fragment.requireFragmentManager(), null);
        return true;
    });
}
 
Example #14
Source File: MediaStreamingStatus.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressLint("MissingPermission")
boolean isBluetoothActuallyAvailable(){
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if(adapter == null || !adapter.isEnabled() ){
        //False positive
        return false;
    }
    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ){
        int state = adapter.getProfileConnectionState(BluetoothProfile.A2DP);
        if(state != BluetoothAdapter.STATE_CONNECTING && state != BluetoothAdapter.STATE_CONNECTED){
            //False positive
            return false;
        }
    }

    return true;
}
 
Example #15
Source File: BleUtils.java    From Bluefruit_LE_Connect_Android_V2 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 #16
Source File: MainActivity.java    From retroband with Apache License 2.0 6 votes vote down vote up
/**
 * Initialization / Finalization
 */
private void initialize() {
	Logs.d(TAG, "# Activity - initialize()");
	mService.setupService(mActivityHandler);
	
	// If BT is not on, request that it be enabled.
	// RetroWatchService.setupBT() will then be called during onActivityResult
	if(!mService.isBluetoothEnabled()) {
		Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableIntent, Constants.REQUEST_ENABLE_BT);
	}
	
	// Load activity reports and display
	if(mRefreshTimer != null) {
		mRefreshTimer.cancel();
	}
	
	// Use below timer if you want scheduled job
	//mRefreshTimer = new Timer();
	//mRefreshTimer.schedule(new RefreshTimerTask(), 5*1000);
}
 
Example #17
Source File: MkrSciBleManager.java    From science-journal with Apache License 2.0 6 votes vote down vote up
public static void subscribe(
    Context context, String address, String characteristic, Listener listener) {
  synchronized (gattHandlers) {
    GattHandler gattHandler = gattHandlers.get(address);
    if (gattHandler == null) {
      BluetoothManager manager =
          (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
      if (manager == null) {
        return;
      }
      BluetoothAdapter adapter = manager.getAdapter();
      BluetoothDevice device = adapter.getRemoteDevice(address);
      gattHandler = new GattHandler();
      gattHandlers.put(address, gattHandler);
      device.connectGatt(context, true /* autoConnect */, gattHandler);
    }
    gattHandler.subscribe(characteristic, listener);
  }
}
 
Example #18
Source File: GrblBluetoothSerialService.java    From grblcontroller with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(){
    super.onCreate();
    mAdapter = BluetoothAdapter.getDefaultAdapter();

    mState = STATE_NONE;
    mNewState = mState;

    if(mAdapter == null){
        EventBus.getDefault().post(new UiToastEvent(getString(R.string.text_bluetooth_adapter_error), true, true));
        stopSelf();
    }else{
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1){
            startForeground(Constants.BLUETOOTH_SERVICE_NOTIFICATION_ID, this.getNotification(null));
        }

        serialBluetoothCommunicationHandler = new SerialBluetoothCommunicationHandler(this);
        EventBus.getDefault().register(this);
    }
}
 
Example #19
Source File: PairingActivity.java    From microbit with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all bonded devices and tries to unbond it.
 */
private void unPairDevice() {
    ConnectedDevice connectedDevice = BluetoothUtils.getPairedMicrobit(this);
    String addressToDelete = connectedDevice.mAddress;
    // Get the paired devices and put them in a Set
    BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    for(BluetoothDevice bt : pairedDevices) {
        logi("Paired device " + bt.getName());
        if(bt.getAddress().equals(addressToDelete)) {
            try {
                Method m = bt.getClass().getMethod("removeBond", (Class[]) null);
                m.invoke(bt, (Object[]) null);
            } catch(NoSuchMethodException | IllegalAccessException
                    | InvocationTargetException e) {
                Log.e(TAG, e.toString());
            }
        }
    }
}
 
Example #20
Source File: LinkDeviceFragment.java    From SmartOrnament with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated mEt_msgContenthod stub
    String action = intent.getAction();
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if (mDeviceList.contains(device)) {  //防止重复添加蓝牙设备
            return;
        }
        mArrayList.add(device.getName() + "\n" + device.getAddress());
        mDeviceList.add(device);
        adapter.notifyDataSetChanged();    //通知数据源更新,刷新蓝牙列表
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        //Toast.makeText(MainActivity.this, "搜索完成!", Toast.LENGTH_SHORT).show();
    }
}
 
Example #21
Source File: BaseScanner.java    From neatle with MIT License 6 votes vote down vote up
private void conditionalStart() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null) {
        NeatleLogger.e("Bluetooth LE scan failed to start. No bluetooth adapter found");
        return;
    }
    int adapterState = adapter.getState();
    if (adapterState != BluetoothAdapter.STATE_ON) {
        NeatleLogger.e("Bluetooth off, will start scanning when it turns on.");
        pause();
        return;
    }

    onStart(adapter, scanMode);
    doStarted = true;
    if (scanDuration > 0) {
        handler.postDelayed(pauseCallback, scanDuration);
    }
}
 
Example #22
Source File: G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
Example #23
Source File: TransportBrokerTest.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testSendPacket(){
	if (Looper.myLooper() == null) {
		Looper.prepare();
	}

	TransportBroker broker = new TransportBroker(mContext, SdlUnitTestContants.TEST_APP_ID,rsvp.getService());

	if(!DeviceUtil.isEmulator()){ // Cannot perform MBT operations in emulator
		assertTrue(broker.start());
	}
	BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	if(!DeviceUtil.isEmulator()){ // Cannot perform BT adapter operations in emulator
		assertNotNull(adapter);
		assertTrue(adapter.isEnabled());
	}
	//Not ideal, but not implementing callbacks just for unit tests
	int count = 0;
	while(broker.routerServiceMessenger == null && count<10){
		sleep();
		count++;
	}
	if(!DeviceUtil.isEmulator()){ // Cannot perform BT adapter operations in emulator
		assertNotNull(broker.routerServiceMessenger);
	}

	//assertFalse(broker.sendPacketToRouterService(null, 0, 0));
	//assertFalse(broker.sendPacketToRouterService(new byte[3], -1, 0));
	//assertFalse(broker.sendPacketToRouterService(new byte[3], 0, 4));
	//assertTrue(broker.sendPacketToRouterService(new byte[3],0, 3));

	broker.stop();

}
 
Example #24
Source File: BluetoothTetheringTile.java    From GravityBox with Apache License 2.0 5 votes vote down vote up
private void registerServiceListener() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null && adapter.getState() == BluetoothAdapter.STATE_ON &&
            mBluetoothPan.get() == null) {
        adapter.getProfileProxy(mContext, mProfileServiceListener,
                BT_PROFILE_PAN);
        if (DEBUG) log("Service listener registered");
    }
}
 
Example #25
Source File: BrowserActivity.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == BlUETOOTH_SETTINGS_REQUEST_CODE) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled() && bluetoothEnableDialog != null) {
            bluetoothEnableDialog.show();
        }
    }
}
 
Example #26
Source File: JoH.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static String getLocalBluetoothName() {
    try {
        final String name = BluetoothAdapter.getDefaultAdapter().getName();
        if (name == null) return "";
        return name;
    } catch (Exception e) {
        return "";
    }
}
 
Example #27
Source File: BluetoothWrapper.java    From phonegap-bluetooth-plugin with MIT License 5 votes vote down vote up
/**
 * Check whether Bluetooth is on or off.
 * 
 * @return Flag indicating if Bluetooth is enabled on this device.
 * @throws Exception When there is an error deducing adapter state.
 */
public boolean isEnabled() throws Exception
{
	try
	{
		return _adapter.getState() == BluetoothAdapter.STATE_ON;
	}
	catch(Exception e)
	{	
		throw e;
	}
}
 
Example #28
Source File: Neatle.java    From neatle with MIT License 5 votes vote down vote up
/**
 * Returns a {@link BluetoothDevice} based on the provided MAC address.
 *
 * @param mac the MAC address of the BTLE device
 * @return the created BT device.
 */
public static BluetoothDevice getDevice(@NonNull String mac) {
    String upperMac = mac.toUpperCase();
    if (isMacValid(upperMac)) {
        return BluetoothAdapter.getDefaultAdapter().getRemoteDevice(upperMac);
    }
    throw new UnsupportedOperationException("Device mac not recognized.");
}
 
Example #29
Source File: LollipopScannerTest.java    From RxCentralBle with Apache License 2.0 5 votes vote down vote up
@Test
public void scan_failed_bluetoothUnsupported() {
  when(BluetoothAdapter.getDefaultAdapter()).thenReturn(null);

  scanDataTestObserver = scanner.scan().test();

  scanDataTestObserver.assertError(
      throwable -> {
        ConnectionError error = (ConnectionError) throwable;
        return error != null && error.getCode() == ConnectionError.Code.SCAN_FAILED;
      });
}
 
Example #30
Source File: A2dpSinkActivity.java    From sample-bluetooth-audio with Apache License 2.0 5 votes vote down vote up
/**
 * Enable the current {@link BluetoothAdapter} to be discovered (available for pairing) for
 * the next {@link #DISCOVERABLE_TIMEOUT_MS} ms.
 */
private void enableDiscoverable() {
    Log.d(TAG, "Registering for discovery.");
    Intent discoverableIntent =
            new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
            DISCOVERABLE_TIMEOUT_MS);
    startActivityForResult(discoverableIntent, REQUEST_CODE_ENABLE_DISCOVERABLE);
}