Java Code Examples for android.bluetooth.BluetoothManager

The following examples show how to use android.bluetooth.BluetoothManager. 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: android-midisuite   Source File: DeviceScanActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // Use this check to determine whether BLE is supported on the device.  Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
}
 
Example 2
Source Project: Bluefruit_LE_Connect_Android_V2   Source File: BleManager.java    License: MIT License 6 votes vote down vote up
public boolean start(Context context) {

        // Init Manager
        mManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);

        // Init Adapter
        if (mManager != null) {
            mAdapter = mManager.getAdapter();
        } else {
            mAdapter = null;
        }

        final boolean isEnabled = mAdapter != null && mAdapter.isEnabled();
        if (!isEnabled) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
        }

        return isEnabled;
    }
 
Example 3
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan);
    mHandler = new Handler();
    
    mLView = (ListView) findViewById(R.id.scan_device_lv);

    // 判断硬件是否支持蓝牙4.0
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }

    // 获取蓝牙适配器
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // 判断设备是否支持蓝牙
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }
}
 
Example 4
Source Project: beacons-android   Source File: BleService.java    License: Apache License 2.0 6 votes vote down vote up
private void initializeService() {
    if(D) Log.d(TAG, "initializeService");

    Beacons.initialize(this);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    IntentFilter localIntentFilter = new IntentFilter(ACTION_ITEM_STATE);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, localIntentFilter);

    // Bluetooth events are not received when using LocalBroadcastManager
    IntentFilter systemIntentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver, systemIntentFilter);

    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    if (null != bluetoothManager) {
        mAdvertisersManager = new AdvertisersManager(bluetoothManager, this);

        restoreSavedState();
    }
}
 
Example 5
private void set_current_values() {
    notes.setText("");
    activeBluetoothDevice = ActiveBluetoothDevice.first();
    if (Build.VERSION.SDK_INT >= 18) {
        mBluetoothManager = (BluetoothManager) safeGetContext().getSystemService(Context.BLUETOOTH_SERVICE);
    }
    setVersionName();
    //setCollectionMethod();
    setCurrentDevice();
    if (Home.get_follower()) {
        setConnectionStatusFollower();
    } else if (prefs.getString("dex_collection_method", "bogus").equals("WifiWixel")) {
        setConnectionStatusWifiWixel();
    } else {
        setConnectionStatus();
    }
    setSensorStatus();
    setTransmitterStatus();
    setNotes();
    futureDataCheck();

   /* if (notes.getText().length()==0) {
        notes.setText("Swipe for more status pages!");
    }*/
}
 
Example 6
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 7
@Override
public void onClick(View v) {

    String deviceType = sharedPreferences.getString(AppConstants.KEY_DEVICE_TYPES, AppConstants.DEVICE_TYPE_DEFAULT);

    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 8
public static boolean isConnectedToDevice(final String mac) {
    if (JoH.emptyString(mac)) {
        return false;
    }
    final BluetoothManager bluetoothManager = (BluetoothManager) xdrip.getAppContext().getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        return false;
    }
    boolean foundConnectedDevice = false;
    for (BluetoothDevice bluetoothDevice : bluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
        if (bluetoothDevice.getAddress().equalsIgnoreCase(mac)) {
            foundConnectedDevice = true;
            break;
        }
    }
    return foundConnectedDevice;
}
 
Example 9
/**
 * check that the bluetooth is enabled
 * @return true if the bluetooth is enable false if we ask to the user to enable it
 */
private boolean enableBluetoothAdapter(){
    final BluetoothManager bluetoothManager =
            ContextCompat.getSystemService(mCtx,BluetoothManager.class);
    if(bluetoothManager==null)
        throw new IllegalStateException("Bluetooth adapter is needed by this app!");
    //the adapter is !=null since we request in the manifest to have the bt capability
    final BluetoothAdapter btAdapter = bluetoothManager.getAdapter();

    // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
    // fire an intent to display a dialog asking the user to grant permission to enable it.
    if (!btAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        return false;
    }else
        return true;
}
 
Example 10
Source Project: nearby-beacons   Source File: EddystoneScannerService.java    License: MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    sRunning = true;

    mNotificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    BluetoothManager manager =
            (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    mBluetoothLeScanner = manager.getAdapter().getBluetoothLeScanner();

    mDetectedBeacons = new ArrayMap<>();

    startScanning();
}
 
Example 11
Source Project: android   Source File: BLEService.java    License: MIT License 6 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (null != intent) {
        mMAC = intent.getStringExtra(KEY_MAC);
    }
    if (TextUtils.isEmpty(mMAC)) {
        mMAC = MAC_BT5;
    }
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();

    if (null != mBluetoothAdapter) {
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mMAC);
        if (null != device) {
            mBluetoothGatt = device.connectGatt(this, false, mCallBack);
            mBluetoothGatt.connect();
            return START_STICKY;
        }
    }

    stopSelf();
    return START_NOT_STICKY;
}
 
Example 12
Source Project: xDrip   Source File: PebbleWatchSync.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void check_and_enable_bluetooth() {
    if (Build.VERSION.SDK_INT > 17) {
        try {
            final BluetoothManager bluetooth_manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (!bluetooth_manager.getAdapter().isEnabled()) {
                if (Pref.getBoolean("automatically_turn_bluetooth_on", true)) {
                    JoH.setBluetoothEnabled(getApplicationContext(), true);
                    //Toast.makeText(this, "Trying to turn Bluetooth on", Toast.LENGTH_LONG).show();
                    //} else {
                    //Toast.makeText(this, "Please turn Bluetooth on!", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            UserError.Log.e(TAG, "Error checking/enabling bluetooth: " + e);
        }
    }
}
 
Example 13
@Override
public void onCreate() {
    super.onCreate();

    Foreground.init(getApplication());
    Foreground.get().addListener(listener);

    foreground = true;
    scanSettings = new ScanSettings.Builder()
            .setReportDelay(0)
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();
    scanner = bluetoothAdapter.getBluetoothLeScanner();

    if (getForegroundMode()) startFG();
    handler = new Handler();
    handler.post(reStarter);
    bgScanHandler = new Handler();
}
 
Example 14
Source Project: blefun-androidthings   Source 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 15
Source Project: blefun-androidthings   Source File: ScanActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void prepareForScan() {
    if (isBleSupported()) {
        // Ensures Bluetooth is enabled on the device
        BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter btAdapter = btManager.getAdapter();
        if (btAdapter.isEnabled()) {
            // Prompt for runtime permission
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLeScan();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_LOCATION);
            }
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    } else {
        Toast.makeText(this, "BLE is not supported", Toast.LENGTH_LONG).show();
        finish();
    }
}
 
Example 16
public static boolean isConnectedToDevice(final String mac) {
    if (JoH.emptyString(mac)) {
        return false;
    }
    final BluetoothManager bluetoothManager = (BluetoothManager) xdrip.getAppContext().getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        return false;
    }
    boolean foundConnectedDevice = false;
    for (BluetoothDevice bluetoothDevice : bluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
        if (bluetoothDevice.getAddress().equalsIgnoreCase(mac)) {
            foundConnectedDevice = true;
            break;
        }
    }
    return foundConnectedDevice;
}
 
Example 17
Source Project: BlunoBasicDemo   Source File: BlunoLibrary.java    License: GNU General Public License v3.0 6 votes vote down vote up
boolean initiate()
{
	// Use this check to determine whether BLE is supported on the device.
	// Then you can
	// selectively disable BLE-related features.
	if (!mainContext.getPackageManager().hasSystemFeature(
			PackageManager.FEATURE_BLUETOOTH_LE)) {
		return false;
	}
	
	// Initializes a Bluetooth adapter. For API level 18 and above, get a
	// reference to
	// BluetoothAdapter through BluetoothManager.
	final BluetoothManager bluetoothManager = (BluetoothManager) mainContext.getSystemService(Context.BLUETOOTH_SERVICE);
	mBluetoothAdapter = bluetoothManager.getAdapter();

	// Checks if Bluetooth is supported on the device.
	if (mBluetoothAdapter == null) {
		return false;
	}
	return true;
}
 
Example 18
Source Project: microbit   Source File: DfuBaseService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes bluetooth adapter
 *
 * @return <code>true</code> if initialization was successful
 */
private boolean initialize() {
    // For API level 18 and above, get a reference to BluetoothAdapter through
    // BluetoothManager.
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        loge("Unable to initialize BluetoothManager.");
        return false;
    }

    mBluetoothAdapter = bluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        loge("Unable to obtain a BluetoothAdapter.");
        return false;
    }

    return true;
}
 
Example 19
boolean initiate()
{
	// Use this check to determine whether BLE is supported on the device.
	// Then you can
	// selectively disable BLE-related features.
	if (!mainContext.getPackageManager().hasSystemFeature(
			PackageManager.FEATURE_BLUETOOTH_LE)) {
		return false;
	}
	
	// Initializes a Bluetooth adapter. For API level 18 and above, get a
	// reference to
	// BluetoothAdapter through BluetoothManager.
	final BluetoothManager bluetoothManager = (BluetoothManager) mainContext.getSystemService(Context.BLUETOOTH_SERVICE);
	mBluetoothAdapter = bluetoothManager.getAdapter();

	// Checks if Bluetooth is supported on the device.
	if (mBluetoothAdapter == null) {
		return false;
	}
	return true;
}
 
Example 20
Source Project: ESeal   Source File: ACSUtility.java    License: Apache License 2.0 6 votes vote down vote up
public ACSUtility(Context context, IACSUtilityCallback cb) {
        // TODO Auto-generated constructor stub
        this.context = context;
        userCallback = cb;
        _lengthOfPackage = 10;
        bScanning = false;

        Log.d(TAG, "acsUtility 1");

        bluetoothManager =
                (BluetoothManager) context.getSystemService(context.BLUETOOTH_SERVICE);
        mBtAdapter = bluetoothManager.getAdapter();
        if (mBtAdapter == null) {
            Log.d(TAG, "error, mBtAdapter == null");
            return;
        }

        //after andrioid m, must request Permission on runtime
//        getPermissions(context);

        //context.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        Intent intent = new Intent();
        intent.setClass(context, ACSUtilityService.class);
        context.startService(intent);
        context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }
 
Example 21
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan);
    mHandler = new Handler();
    
    mLView = (ListView) findViewById(R.id.scan_device_lv);

    // 判断硬件是否支持蓝牙4.0
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }

    // 获取蓝牙适配器
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // 判断设备是否支持蓝牙
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }
}
 
Example 22
/**
 * Get references to system Bluetooth objects if we don't have them already.
 */
private void initialize() {
    if (mBluetoothLeAdvertiser == null) {
        BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager != null) {
            BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
            if (mBluetoothAdapter != null) {
                mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
            } else {
                Toast.makeText(this, getString(R.string.bt_null), Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, getString(R.string.bt_null), Toast.LENGTH_LONG).show();
        }
    }

}
 
Example 23
Source Project: android-beacon-library   Source File: CycledLeScanner.java    License: Apache License 2.0 6 votes vote down vote up
protected BluetoothAdapter getBluetoothAdapter() {
    try {
        if (mBluetoothAdapter == null) {
            // Initializes Bluetooth adapter.
            final BluetoothManager bluetoothManager =
                    (BluetoothManager) mContext.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = bluetoothManager.getAdapter();
            if (mBluetoothAdapter == null) {
                LogManager.w(TAG, "Failed to construct a BluetoothAdapter");
            }
        }
    }
    catch (SecurityException e) {
        // Thrown by Samsung Knox devices if bluetooth access denied for an app
        LogManager.e(TAG, "Cannot consruct bluetooth adapter.  Security Exception");
    }
    return mBluetoothAdapter;
}
 
Example 24
public synchronized void checkAndConnectToPuck(final Puck puck) {
    if (mConnectedCubes.contains(puck)
            || !puck.getServiceUUIDs().contains(GattServices.CUBE_SERVICE_UUID)) {
        return;
    }

    L.i("Found Cube Puck. Initiating gatt subscribe to " + puck);
    mConnectedCubes.add(puck);

    new SimpleAsyncTask<Void>(mCtx, null) {

        @Override
        protected Void onExecute() throws Exception {
            BluetoothAdapter adapter = ((BluetoothManager) mCtx.getSystemService
                    (Context.BLUETOOTH_SERVICE)).getAdapter();
            BluetoothDevice device = adapter.getRemoteDevice(puck.getAddress());
            mGattManager.queue(new GattSetNotificationOperation(
                    device,
                    GattServices.CUBE_SERVICE_UUID,
                    GattServices.CUBE_CHARACTERISTIC_DIRECTION_UUID,
                    GattServices.CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID));
            // Android BLE stack might have issues connecting to
            // multiple Gatt services right after another.
            // See: http://stackoverflow.com/questions/21237093/android-4-3-how-to-connect-to-multiple-bluetooth-low-energy-devices
            Thread.sleep(1000);
            return null;
        }
    }.execute();
}
 
Example 25
Source Project: PresencePublisher   Source File: MainActivity.java    License: MIT License 5 votes vote down vote up
private void checkBluetoothAndBatteryOptimizationAndStartWorker() {
    if (((Application) getApplication()).supportsBeacons()
            // make linter happy
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
            && ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED
            && !sharedPreferences.getStringSet(BEACON_LIST, Collections.emptySet()).isEmpty()) {
        BluetoothManager bluetoothManager = (BluetoothManager) 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()) {
                FragmentManager fm = getSupportFragmentManager();

                ConfirmationDialogFragment fragment = ConfirmationDialogFragment.getInstance(ok -> {
                    if (ok) {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, START_BLUETOOTH_REQUEST_CODE);
                    }
                }, R.string.bluetooth_dialog_title, R.string.bluetooth_dialog_message);
                fragment.show(fm, null);
                return;
            }
        }
    }
    checkBatteryOptimizationAndStartWorker();
}
 
Example 26
Source Project: bitgatt   Source File: GattUtils.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will fetch the bluetooth adapter or return null if it's not available
 *
 * @param context The android context
 * @return The bluetooth adapter or null
 */

public @Nullable
BluetoothAdapter getBluetoothAdapter(Context context) {
    BluetoothManager manager = getBluetoothManager(context);
    if (manager == null) {
        return null;
    }
    BluetoothAdapter adapter = manager.getAdapter();
    if (adapter == null) {
        return null;
    }
    return adapter;
}
 
Example 27
Source Project: bitgatt   Source File: GattUtils.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * In some operations, it is important for us to be able to determine if a particular perhiperhal
 * is actually connected to the phone at the ACL level as our access to the GATT is somewhat
 * limited.  We understand that some phones lie, saying that all of it's bonded devices are connected,
 * like the HTC One M9 on 5.0.2
 *
 * @param context The android context
 * @param device  The bluetooth device which we want to check it's status
 * @return True if the device is connected to the phone, false if not
 */

public boolean isPerhipheralCurrentlyConnectedToPhone(@Nullable Context context, @Nullable BluetoothDevice device) {
    if (context == null || device == null) {
        return false;
    }
    BluetoothManager mgr = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
    if (mgr != null) {
        List<BluetoothDevice> devices = mgr.getConnectedDevices(BluetoothProfile.GATT);
        return devices.contains(device);
    } else {
        return false;
    }
}
 
Example 28
Source Project: xDrip   Source File: BluetoothScan.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth_scan);

    ListView lv = (ListView)findViewById(android.R.id.list);

    final BluetoothManager bluetooth_manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

    bluetooth_adapter = bluetooth_manager.getAdapter();
    mHandler = new Handler();

    if (bluetooth_adapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_LONG).show();
        has_bluetooth = false;
        finish();
        return;
    } else {
        has_bluetooth = true;
    }
    if(bluetooth_manager == null) {
        Toast.makeText(this, "This device does not seem to support bluetooth", Toast.LENGTH_LONG).show();
    } else {
        if(!bluetooth_manager.getAdapter().isEnabled()) {
            Toast.makeText(this, "Bluetooth is turned off on this device currently", Toast.LENGTH_LONG).show();
        } else {
            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2){
                Toast.makeText(this, "The android version of this device is not compatible with Bluetooth Low Energy", Toast.LENGTH_LONG).show();
            }
        }
    }
    mLeDeviceListAdapter = new LeDeviceListAdapter();
    setListAdapter(mLeDeviceListAdapter);

}
 
Example 29
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan);
    mHandler = new Handler();
    
    mLView = (ListView) findViewById(R.id.scan_device_lv);

    // 判断硬件是否支持蓝牙4.0
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }

    // 获取蓝牙适配器
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // 判断设备是否支持蓝牙
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    
}
 
Example 30
private boolean isBluetoothEnabled() {
    if (!((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter().isEnabled()) {
        notifyAboutError(ErrorCode.BLUETOOTH_NOT_ENABLED);
        return false;
    }

    return true;
}