Example usage for android.content Context BLUETOOTH_SERVICE

List of usage examples for android.content Context BLUETOOTH_SERVICE

Introduction

In this page you can find the example usage for android.content Context BLUETOOTH_SERVICE.

Prototype

String BLUETOOTH_SERVICE

To view the source code for android.content Context BLUETOOTH_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.bluetooth.BluetoothManager for using Bluetooth.

Usage

From source file:com.perples.recosample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mLayout = findViewById(R.id.mainLayout);

    //If a user device turns off bluetooth, request to turn it on.
    //?  ?? ./* w  w w .j  av a  2 s .co  m*/
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
    }

    /**
     * In order to use RECO SDK for Android API 23 (Marshmallow) or higher,
     * the location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is required.
     * Please refer to the following permission guide and sample code provided by Google.
     *
     * ? API 23 ()?? , ?? RECO SDK  
     *   (ACCESS_COARSE_LOCATION ? ACCESS_FINE_LOCATION)?  .
     *  ? , ?  ?  ?.
     *
     * http://www.google.com/design/spec/patterns/permissions.html
     * https://github.com/googlesamples/android-RuntimePermissions
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.i("MainActivity",
                    "The location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is not granted.");
            this.requestLocationPermission();
        } else {
            Log.i("MainActivity",
                    "The location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is already granted.");
        }
    }
}

From source file:fr.bmartel.android.notti.service.bluetooth.BluetoothCustomManager.java

@SuppressLint("NewApi")
public void init(Context context) {

    // Initializes Bluetooth adapter.
    final BluetoothManager bluetoothManager = (BluetoothManager) context
            .getSystemService(Context.BLUETOOTH_SERVICE);

    mBluetoothAdapter = bluetoothManager.getAdapter();

    //init message handler
    mHandler = null;//from w  w w  .j  a v  a2  s.  c  om
    mHandler = new Handler();

    scanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, final byte[] scanRecord) {

            if (device.getAddress() != null && device.getName() != null
                    && !scanningList.containsKey(device.getAddress())) {

                scanningList.put(device.getAddress(), device);

                try {
                    JSONObject object = new JSONObject();
                    object.put("address", device.getAddress());
                    object.put("deviceName", device.getName());

                    ArrayList<String> deviceInfo = new ArrayList<>();
                    deviceInfo.add(object.toString());

                    broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED, deviceInfo);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}

From source file:com.tkjelectronics.balancingrobotfullsizeandroid.app.BalancingRobotFullSizeActivity.java

@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_balancing_robot_full_size);

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Get local Bluetooth adapter
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
        mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
    else//w  w w.  j  a v a  2s.co m
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        showToast("Bluetooth is not available", Toast.LENGTH_LONG);
        finish();
        return;
    }

    // Create the adapter that will return a fragment for each of the primary sections of the app.
    mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mViewPagerAdapter);

    // Bind the underline indicator to the adapter
    mUnderlinePageIndicator = (UnderlinePageIndicator) findViewById(R.id.indicator);
    mUnderlinePageIndicator.setViewPager(mViewPager);
    mUnderlinePageIndicator.setFades(false);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mUnderlinePageIndicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            if (D)
                Log.d(TAG, "ViewPager position: " + position);
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mViewPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(actionBar.newTab().setText(mViewPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Keep the screen on while the user is riding the robot
}

From source file:com.mikroe.hexiwear_android.DeviceScanActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listitem_device);

    mHandler = new Handler();
    mDeviceAddresses = new ArrayList<String>();
    mScanTitle = (TextView) findViewById(R.id.scanTitle);
    mDeviceAddresses.add(KWARP_ADDRESS);
    mDeviceAddresses.add(KWARP_ADDRESS_TWO);

    // 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();/*from   w w w.ja v a2s.  c o  m*/
    }

    // 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;
    }

    // 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 (!mBluetoothAdapter.isEnabled()) {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    //checkNotificationEnabled();

    LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
    ComponentName name = startService(new Intent(DeviceScanActivity.this, NotificationService.class));

    registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

    scanLeDevice(true);

    Intent gattServiceIntent = new Intent(DeviceScanActivity.this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}

From source file:mobilelecture.cdp12_app.RecoRangingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reco_ranging);

    // /*from  w  w  w .  j av  a2 s .  com*/

    //If a user device turns off bluetooth, request to turn it on.
    //?  ?? .
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
    }

    /**
     * In order to use RECO SDK for Android API 23 (Marshmallow) or higher,
     * the location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is required.
     * Please refer to the following permission guide and sample code provided by Google.
     *
     * ? API 23 ()?? , ?? RECO SDK  
     *   (ACCESS_COARSE_LOCATION ? ACCESS_FINE_LOCATION)?  .
     *  ? , ?  ?  ?.
     *
     * http://www.google.com/design/spec/patterns/permissions.html
     * https://github.com/googlesamples/android-RuntimePermissions
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.i("RecoRangingActivity",
                    "The location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is not granted.");
            this.requestLocationPermission();
        } else {
            Log.i("RecoRangingActivity",
                    "The location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is already granted.");
        }
    }

    // ??

    //mRecoManager will be created here. (Refer to the RECOActivity.onCreate())
    //mRecoManager ?  ??. RECOActivity.onCreate()  .

    //Set RECORangingListener (Required)
    //RECORangingListener  . ()
    mRecoManager.setRangingListener(this);

    /**
     * Bind RECOBeaconManager with RECOServiceConnectListener, which is implemented in RECOActivity
     * You SHOULD call this method to use monitoring/ranging methods successfully.
     * After binding, onServiceConenct() callback method is called.
     * So, please start monitoring/ranging AFTER the CALLBACK is called.
     *
     * RECOServiceConnectListener  RECOBeaconManager bind . RECOServiceConnectListener RECOActivity? ? .
     * monitoring ? ranging ?  , ?  "" ? .
     * bind?, onServiceConnect()   ?.    ? monitoring / ranging ?  ?.
     */
    mRecoManager.bind(this);
}

From source file:com.lauszus.launchpadflightcontrollerandroid.app.LaunchPadFlightControllerActivity.java

@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch_pad_flight_controller);

    // Get local Bluetooth adapter
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
        mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
    else//from   www.  ja  va 2  s  .  com
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        showToast("Bluetooth is not available", Toast.LENGTH_LONG);
        finish();
        return;
    }

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

    // Create the adapter that will return a fragment for each of the primary sections of the app.
    mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mViewPagerAdapter);

    TabLayout mTabLayout = (TabLayout) findViewById(R.id.tabs);
    mTabLayout.setupWithViewPager(mViewPager);
    mTabLayout.setOnTabSelectedListener(this);
    mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    mTabLayout.setTabMode(TabLayout.MODE_FIXED);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Keep the screen on
}

From source file:org.uribeacon.sample.UriBeaconScanActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.uribeacon_scan_layout);

    mSwipeWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget);
    mSwipeWidget.setOnRefreshListener(this);

    // Initializes list view adapter.
    mLeDeviceListAdapter = new DeviceListAdapter(getLayoutInflater());
    setListAdapter(mLeDeviceListAdapter);

    // 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();//www. j a va2  s.c o  m
    }

    // Initializes a Bluetooth adapter. For API version 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();
    }
}

From source file:com.github.akinaru.roboticbuttonpusher.bluetooth.BluetoothCustomManager.java

@SuppressLint("NewApi")
public void init(Context context) {

    // Initializes Bluetooth adapter.
    final BluetoothManager bluetoothManager = (BluetoothManager) context
            .getSystemService(Context.BLUETOOTH_SERVICE);

    mBluetoothAdapter = bluetoothManager.getAdapter();

    //init message handler
    mHandler = null;/*from ww  w.  ja  v  a  2s  . co m*/
    mHandler = new Handler();

    scanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, final byte[] scanRecord) {

            if (device.getAddress() != null && device.getName() != null) {

                dispatchBtDevices(device, rssi, scanRecord);
            }
        }
    };
}

From source file:pl.mrwojtek.sensrec.app.HeartRateDialog.java

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    handler = new Handler(getContext().getMainLooper());
    adapter = new DevicesAdapter();

    SensorsRecorder recorder = RecordingService.getRecorder(getActivity());
    SortedMap<Integer, BleRecorder> bleRecorders = recorder.getBleRecorders();
    for (Map.Entry<Integer, BleRecorder> r : bleRecorders.entrySet()) {
        adapter.add(r.getValue());//ww w.  j  ava2  s. com
    }

    final BluetoothManager bluetoothManager = (BluetoothManager) getContext()
            .getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();
    if (!bluetoothAdapter.isEnabled()) {
        Log.w(TAG, "Bluetooth adapter not enabled");
        requestEnableBluetooth();
    } else {
        scanLeDevice(true);
    }
}

From source file:io.v.android.libs.discovery.ble.BlePlugin.java

public BlePlugin(Context androidContext) {
    this.androidContext = androidContext;
    cachedDevices = new DeviceCache(Duration.standardMinutes(1));
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
        return;/*from  w ww .  j a  v a 2 s .co m*/
    }

    if (!hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
            && !hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
        return;
    }
    isEnabled = true;
    bluetoothLeAdvertise = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
    bluetoothLeScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
    BluetoothManager manager = (BluetoothManager) androidContext.getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothGattServer = manager.openGattServer(androidContext, new BluetoothGattServerCallback() {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            super.onConnectionStateChange(device, status, newState);
        }

        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
                BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
            byte[] total = characteristic.getValue();
            byte[] res = {};
            // Only send MTU - 1 bytes. The first byte of all packets is the op code.
            if (offset < total.length) {
                int finalByte = offset + MTU - 1;
                if (finalByte > total.length) {
                    finalByte = total.length;
                }
                res = Arrays.copyOfRange(total, offset, finalByte);
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, res);
            } else {
                // This should probably be an error, but a bug in the paypal/gatt code causes an
                // infinite loop if this returns an error rather than the empty value.
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, res);
            }
        }
    });
}