Java Code Examples for android.bluetooth.BluetoothManager#getAdapter()

The following examples show how to use android.bluetooth.BluetoothManager#getAdapter() . 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: BLEService.java    From android with 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 2
Source File: DeviceScanActivity.java    From jessica with MIT License 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 3
Source File: ScanActivity.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan);

    if (DEBUG) {
        Log.d(TAG, "onCreate()");
        Log.d(TAG, "savedInstanceState : " + savedInstanceState);
    }

    mBLEScanner = new BLEScanner(this);
    mListAdapter = new ListAdapter<>(new ArrayList<>(), R.layout.list_scan_row, this);

    RecyclerView deviceList = findViewById(R.id.list_device);
    deviceList.setHasFixedSize(true);
    deviceList.setLayoutManager(new LinearLayoutManager(this));
    deviceList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    deviceList.setAdapter(mListAdapter);

    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager != null) {
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter.isEnabled()) {
            startScan();
        } else {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_ENABLE_BLUETOOTH);
        }
    }
}
 
Example 4
Source File: DeviceScanActivity.java    From android-BluetoothLeGatt with 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 5
Source File: ShareTest.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (device != null) {
        details.append("\nConnection state: " + " Device is not null");
        mConnectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    }

    Log.i(TAG, "Connection state: " + mConnectionState);
    details.append("\nConnection state: " + mConnectionState);
    if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
        ActiveBluetoothDevice btDevice = new Select().from(ActiveBluetoothDevice.class)
                .orderBy("_ID desc")
                .executeSingle();
        if (btDevice != null) {
            details.append("\nBT Device: " + btDevice.name);
            mDeviceName = btDevice.name;
            mDeviceAddress = btDevice.address;
            mBluetoothAdapter = mBluetoothManager.getAdapter();
            boolean newConnection = true;
            if(newConnection) {
                is_connected = connect(mDeviceAddress);
                details.append("\nConnecting...: ");
            }
        }
    }
}
 
Example 6
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager != null) {
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter != null) {
            if (device != null) {
                mConnectionState = STATE_DISCONNECTED;
                for (BluetoothDevice bluetoothDevice : mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
                    if (bluetoothDevice.getAddress().compareTo(device.getAddress()) == 0) {
                        mConnectionState = STATE_CONNECTED;
                    }
                }
            }

            Log.w(TAG, "Connection state: " + mConnectionState);
            if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
                ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
                if (btDevice != null) {
                    mDeviceName = btDevice.name;
                    mDeviceAddress = btDevice.address;
                    if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(mDeviceAddress) != null) {
                        connect(mDeviceAddress);
                        return;
                    }
                }
            } else if (mConnectionState == STATE_CONNECTED) { //WOOO, we are good to go, nothing to do here!
                Log.w(TAG, "Looks like we are already connected, going to read!");
                return;
            }
        }
    }
    setRetryTimer();
}
 
Example 7
Source File: BikeActivity.java    From android with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bike);

    tvLog = findViewById(R.id.tvLog);

    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();
    mBluetoothScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
 
Example 8
Source File: Utils.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
public static BluetoothAdapter getBluetoothAdapter(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager == null) {
            return null;
        }
        return bluetoothManager.getAdapter();
    }
    return BluetoothAdapter.getDefaultAdapter();
}
 
Example 9
Source File: BleUrlDeviceDiscoverer.java    From physical-web with Apache License 2.0 5 votes vote down vote up
public BleUrlDeviceDiscoverer(Context context) {
  mContext = context;
  final BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(
      Context.BLUETOOTH_SERVICE);
  mBluetoothAdapter = bluetoothManager.getAdapter();
  mScanFilterUuids = new ParcelUuid[]{URIBEACON_SERVICE_UUID, EDDYSTONE_URL_SERVICE_UUID};
}
 
Example 10
Source File: BLEServiceBase.java    From unity-bluetooth with MIT License 5 votes vote down vote up
public BLEServiceBase (final Activity activity) {
    mActivity = activity;
    mBtManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE);
    mBtAdapter = mBtManager.getAdapter();

    // Check enable bluetooth
    if ((mBtAdapter == null) || (!mBtAdapter.isEnabled())) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}
 
Example 11
Source File: SensorTagApplicationClass.java    From SensorTag-CC2650 with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {

    // 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_LONG)
                .show();
        mBleSupported = false;
    }

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

    // Checks if Bluetooth is supported on the device.
    if (mBtAdapter == null) {
        Toast.makeText(this, R.string.bt_not_supported, Toast.LENGTH_LONG).show();
        mBleSupported = false;
        return;
    }

    mFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, mFilter);

    if (!mBtAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        enableIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(enableIntent);
    }

    startBluetoothLeService();

    super.onCreate();

}
 
Example 12
Source File: UpdateService.java    From Android-nRF-Beacon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Initializes a reference to the local Bluetooth adapter.
 */
private void initialize() {
	final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
	mAdapter = bluetoothManager.getAdapter();
}
 
Example 13
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager != null) {
        if (device != null) {
            mConnectionState = STATE_DISCONNECTED;
            for (BluetoothDevice bluetoothDevice : mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
                if (bluetoothDevice.getAddress().compareTo(device.getAddress()) == 0) {
                    mConnectionState = STATE_CONNECTED;
                }
            }
        }
        Log.w(TAG, "Connection state: " + mConnectionState);
        if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
            ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
            if (btDevice != null) {
                mDeviceName = btDevice.name;
                mDeviceAddress = btDevice.address;
                mBluetoothAdapter = mBluetoothManager.getAdapter();
                if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(mDeviceAddress) != null) {
                    connect(mDeviceAddress);
                    return;
                } else {
                    Log.w(TAG, "Bluetooth is disabled or BT device cant be found");
                    setRetryTimer();
                    return;
                }
            } else {
                Log.w(TAG, "No bluetooth device to try and connect to");
                setRetryTimer();
                return;
            }
        } else if (mConnectionState == STATE_CONNECTED) {
            Log.w(TAG, "Looks like we are already connected, going to read!");
            attemptRead();
            return;
        } else {
            setRetryTimer();
            return;
        }
    } else {
        setRetryTimer();
        return;
    }
}
 
Example 14
Source File: Peripheral.java    From ble-test-peripheral-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_peripherals);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  mAdvStatus = (TextView) findViewById(R.id.textView_advertisingStatus);
  mConnectionStatus = (TextView) findViewById(R.id.textView_connectionStatus);
  mBluetoothDevices = new HashSet<>();
  mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
  mBluetoothAdapter = mBluetoothManager.getAdapter();

  // If we are not being restored from a previous state then create and add the fragment.
  if (savedInstanceState == null) {
    int peripheralIndex = getIntent().getIntExtra(Peripherals.EXTRA_PERIPHERAL_INDEX,
        /* default */ -1);
    if (peripheralIndex == 0) {
      mCurrentServiceFragment = new BatteryServiceFragment();
    } else if (peripheralIndex == 1) {
      mCurrentServiceFragment = new HeartRateServiceFragment();
    } else if (peripheralIndex == 2) {
      mCurrentServiceFragment = new HealthThermometerServiceFragment();
    } else {
      Log.wtf(TAG, "Service doesn't exist");
    }
    getFragmentManager()
        .beginTransaction()
        .add(R.id.fragment_container, mCurrentServiceFragment, CURRENT_FRAGMENT_TAG)
        .commit();
  } else {
    mCurrentServiceFragment = (ServiceFragment) getFragmentManager()
        .findFragmentByTag(CURRENT_FRAGMENT_TAG);
  }
  mBluetoothGattService = mCurrentServiceFragment.getBluetoothGattService();

  mAdvSettings = new AdvertiseSettings.Builder()
      .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
      .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
      .setConnectable(true)
      .build();
  mAdvData = new AdvertiseData.Builder()
      .setIncludeTxPowerLevel(true)
      .addServiceUuid(mCurrentServiceFragment.getServiceUUID())
      .build();
  mAdvScanResponse = new AdvertiseData.Builder()
      .setIncludeDeviceName(true)
      .build();
}
 
Example 15
Source File: AudioManagerAndroid.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the current Bluetooth headset state.
 * android.bluetooth.BluetoothAdapter.getProfileConnectionState() requires
 * the BLUETOOTH permission.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private boolean hasBluetoothHeadset() {
    if (!mHasBluetoothPermission) {
        Log.w(TAG, "hasBluetoothHeadset() requires BLUETOOTH permission");
        return false;
    }

    // To get a BluetoothAdapter representing the local Bluetooth adapter,
    // when running on JELLY_BEAN_MR1 (4.2) and below, call the static
    // getDefaultAdapter() method; when running on JELLY_BEAN_MR2 (4.3) and
    // higher, retrieve it through getSystemService(String) with
    // BLUETOOTH_SERVICE.
    BluetoothAdapter btAdapter = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        // Use BluetoothManager to get the BluetoothAdapter for
        // Android 4.3 and above.
        BluetoothManager btManager =
                (BluetoothManager) ContextUtils.getApplicationContext().getSystemService(
                        Context.BLUETOOTH_SERVICE);
        btAdapter = btManager.getAdapter();
    } else {
        // Use static method for Android 4.2 and below to get the
        // BluetoothAdapter.
        btAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    if (btAdapter == null) {
        // Bluetooth not supported on this platform.
        return false;
    }

    int profileConnectionState;
    profileConnectionState = btAdapter.getProfileConnectionState(
            android.bluetooth.BluetoothProfile.HEADSET);

    // Ensure that Bluetooth is enabled and that a device which supports the
    // headset and handsfree profile is connected.
    // TODO(henrika): it is possible that btAdapter.isEnabled() is
    // redundant. It might be sufficient to only check the profile state.
    return btAdapter.isEnabled()
            && profileConnectionState == android.bluetooth.BluetoothProfile.STATE_CONNECTED;
}
 
Example 16
Source File: MainActivity.java    From myo_AndoridEMG with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //ready
    graph = (LineGraph) findViewById(R.id.holo_graph_view);
    graphButton1 = (Button) findViewById(R.id.btn_emg1);
    graphButton2 = (Button) findViewById(R.id.btn_emg2);
    graphButton3 = (Button) findViewById(R.id.btn_emg3);
    graphButton4 = (Button) findViewById(R.id.btn_emg4);
    graphButton5 = (Button) findViewById(R.id.btn_emg5);
    graphButton6 = (Button) findViewById(R.id.btn_emg6);
    graphButton7 = (Button) findViewById(R.id.btn_emg7);
    graphButton8 = (Button) findViewById(R.id.btn_emg8);


    //set color
    graphButton1.setBackgroundColor(Color.argb(0x66, 0xff, 0, 0xff));
    graphButton2.setBackgroundColor(Color.argb(0x66, 0xff, 0x00, 0x00));
    graphButton3.setBackgroundColor(Color.argb(0x66, 0x66, 0x33, 0xff));
    graphButton4.setBackgroundColor(Color.argb(0x66, 0xff, 0x66, 0x33));
    graphButton5.setBackgroundColor(Color.argb(0x66, 0xff, 0x33, 0x66));
    graphButton6.setBackgroundColor(Color.argb(0x66, 0x00, 0x33, 0xff));
    graphButton7.setBackgroundColor(Color.argb(0x66, 0x00, 0x33, 0x33));
    graphButton8.setBackgroundColor(Color.argb(0x66, 0x66, 0xcc, 0x66));

    emgDataText = (TextView)findViewById(R.id.emgDataTextView);
    gestureText = (TextView)findViewById(R.id.gestureTextView);
    mHandler = new Handler();

    startNopModel();

    BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();

    Intent intent = getIntent();
    deviceName = intent.getStringExtra(ListActivity.TAG);

    if (deviceName != null) {
        // Ensures Bluetooth is available on the device and it is enabled. If not,
        // displays a dialog requesting user permission to enable Bluetooth.
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            // Scanning Time out by Handler.
            // The device scanning needs high energy.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBluetoothAdapter.stopLeScan(MainActivity.this);
                }
            }, SCAN_PERIOD);
            mBluetoothAdapter.startLeScan(this);
        }
    }
}
 
Example 17
Source File: P_AndroidBluetoothManager.java    From AsteroidOSSync with GNU General Public License v3.0 4 votes vote down vote up
@Override public final void resetManager(Context context)
{
    m_manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
    m_adaptor = m_manager.getAdapter();
}
 
Example 18
Source File: MyoConnector.java    From myolib with Apache License 2.0 4 votes vote down vote up
public MyoConnector(Context context) {
    mContext = context.getApplicationContext();
    BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
}
 
Example 19
Source File: DeviceActivity.java    From BLERW with Apache License 2.0 4 votes vote down vote up
private void init() {
	// BLE check
	if (!BleUtil.isBLESupported(this)) {
		Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT)
				.show();
		finish();
		return;
	}

	// BT check
	BluetoothManager manager = BleUtil.getManager(this);
	if (manager != null) {
		mBTAdapter = manager.getAdapter();
	}
	if (mBTAdapter == null) {
		Toast.makeText(this, R.string.bt_unavailable, Toast.LENGTH_SHORT)
				.show();
		finish();
		return;
	}

	// check BluetoothDevice
	if (mDevice == null) {
		mDevice = getBTDeviceExtra();
		if (mDevice == null) {
			finish();
			return;
		}
	}

	// button disable
	mReadManufacturerNameButton.setEnabled(false);
	mReadSerialNumberButton.setEnabled(false);
	mWriteAlertLevelButton.setEnabled(false);

	// connect to Gatt
	if ((mConnGatt == null)
			&& (mStatus == BluetoothProfile.STATE_DISCONNECTED)) {
		// try to connect
		mConnGatt = mDevice.connectGatt(this, false, mGattcallback);
		mStatus = BluetoothProfile.STATE_CONNECTING;
	} else {
		if (mConnGatt != null) {
			// re-connect and re-discover Services
			mConnGatt.connect();
			mConnGatt.discoverServices();
		} else {
			Log.e(TAG, "state error");
			finish();
			return;
		}
	}
	setProgressBarIndeterminateVisibility(true);
}
 
Example 20
Source File: BluetoothUtils.java    From AndroidBleManager with Apache License 2.0 4 votes vote down vote up
public BluetoothUtils(final Activity activity) {
    mActivity = activity;
    final BluetoothManager btManager = (BluetoothManager) mActivity.getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = btManager.getAdapter();
}