Example usage for android.bluetooth BluetoothManager getAdapter

List of usage examples for android.bluetooth BluetoothManager getAdapter

Introduction

In this page you can find the example usage for android.bluetooth BluetoothManager getAdapter.

Prototype

public BluetoothAdapter getAdapter() 

Source Link

Document

Get the default BLUETOOTH Adapter for this device.

Usage

From source file:com.example.android.bluetoothlegatt.ui.DeviceScanActivity.java

@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();/*from   www . ja v  a 2s. 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;
    }
}

From source file:com.artur.softwareproject.BluetoothConnectionList.java

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

    setContentView(R.layout.activity_bluetooth_connection);

    ListView bluetoothList;//from  w w w. ja  v a 2  s  . c o  m
    bluetoothList = (ListView) findViewById(R.id.bluetoothList);

    ListAdapter = new BluetoothConnectionListAdapter(this, bluetoothAddress, bluetoothName, bDevices);

    bluetoothList.setAdapter(ListAdapter);

    BluetoothManager bluetoothManager;
    bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

    bluetoothAdapter = bluetoothManager.getAdapter();

    mHandler = new Handler();

    File topLevelDir, jsonDir, objDir;

    //Creating the directory structure for the app.
    topLevelDir = new File(Environment.getExternalStorageDirectory() + "/ViSensor");

    jsonDir = new File(Environment.getExternalStorageDirectory() + "/ViSensor/Json");

    objDir = new File(Environment.getExternalStorageDirectory() + "/ViSensor/Obj");

    if (!topLevelDir.exists()) {
        if (!topLevelDir.mkdir()) {
            Log.d(TAG, "Creating top level directory failed.");
        }

        if (!jsonDir.exists()) {
            if (!jsonDir.mkdir()) {
                Log.d(TAG, "Creating json directory failed.");
            }
        }

        if (!objDir.exists()) {
            if (!objDir.mkdir()) {
                Log.d(TAG, "Creating obj directory failed.");
            }
        }
    } else if (!jsonDir.exists()) {
        if (!jsonDir.mkdir()) {
            Log.d(TAG, "Creating json directory failed.");
        }

        if (!objDir.exists()) {
            if (!objDir.mkdir()) {
                Log.d(TAG, "Creating obj directory failed.");
            }
        }
    } else if (!objDir.exists()) {
        if (!objDir.mkdir()) {
            Log.d(TAG, "Creating obj directory failed.");
        }
    }

    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

        final int REQUEST_ENABLE_BT = 1;

        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    int permissionCheckLocation = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);

    int permissionCheckWrite = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permissionCheckLocation != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 0);
    }

    if (permissionCheckWrite != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }

    scanLeDevice(true);
}

From source file:com.megster.cordova.rfduino.RFduinoPlugin.java

@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

    LOG.d(TAG, "action = " + action);

    if (bluetoothAdapter == null) {
        Activity activity = cordova.getActivity();
        BluetoothManager bluetoothManager = (BluetoothManager) activity
                .getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
    }/*  ww w. j av  a 2  s  .c o m*/

    boolean validAction = true;

    if (action.equals(DISCOVER)) {

        int scanSeconds = args.getInt(0);
        findLowEnergyDevices(callbackContext, scanSeconds);

    } else if (action.equals(LIST)) {

        listKnownDevices(callbackContext);

    } else if (action.equals(CONNECT)) {

        String uuid = args.getString(0);
        connect(callbackContext, uuid);

    } else if (action.equals(ON_DATA)) {

        registerOnDataCallback(callbackContext);

    } else if (action.equals(DISCONNECT)) {

        disconnect(callbackContext);

    } else if (action.equals(WRITE)) {

        byte[] data = args.getArrayBuffer(0);
        write(callbackContext, data);

    } else if (action.equals(IS_ENABLED)) {

        if (bluetoothAdapter.isEnabled()) {
            callbackContext.success();
        } else {
            callbackContext.error("Bluetooth is disabled.");
        }

    } else if (action.equals(IS_CONNECTED)) {

        if (activePeripheral != null && activePeripheral.isConnected()) {
            callbackContext.success();
        } else {
            callbackContext.error("Not connected.");
        }

    } else {

        validAction = false;

    }

    return validAction;
}

From source file:com.amobletool.bluetooth.le.downexample.ui.DeviceScanActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // ???ble ?,???
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();//www. j ava2s  .c o  m
    }

    // ? Bluetooth adapter, ?????(APIandroid4.3)
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
    mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

    // ???
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// API level  23(Android 6.0) 
        //???
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //??????
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)) {
                //                    showToast("Android 6.0???????Ble");
            }
            //??
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                    REQUEST_CODE_ACCESS_COARSE_LOCATION);
        }
    }
}

From source file:com.rosterloh.moodring.profile.BleProfileService.java

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS))
        throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key");

    final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI);
    mDeviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);

    Log.i(TAG, "Service started");

    // notify user about changing the state to CONNECTING
    final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE);
    broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING);
    LocalBroadcastManager.getInstance(BleProfileService.this).sendBroadcast(broadcast);

    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    final BluetoothAdapter adapter = bluetoothManager.getAdapter();
    final BluetoothDevice device = adapter.getRemoteDevice(mDeviceAddress);
    mDeviceName = device.getName();/*from www . j  a va 2  s. c o  m*/
    onServiceStarted();

    Log.v(TAG, "Connecting...");
    mBleManager.connect(BleProfileService.this, device);
    return START_REDELIVER_INTENT;
}

From source file:com.xiaocheng.xc_application.bluetoothutils.DeviceScanActivity.java

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

    //getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    //???/*ww w  . ja  v  a2 s  .  c  o m*/
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //??
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                /*MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION*/0);
        //?? ????
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
            Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
        }
    }

    // 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 || !mBluetoothAdapter.isEnabled()) {
        /* Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
         finish();
         return;*/
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

    }

    lv_bleList = (ListView) findViewById(R.id.lv_bleList);

    mDevListAdapter = new DeviceListAdapter();
    lv_bleList.setAdapter(mDevListAdapter);

    lv_bleList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mDevListAdapter.getCount() > 0) {

                BluetoothDevice device1 = mDevListAdapter.getItem(position);
                if (device1 == null)
                    return;
                Intent intent1 = new Intent();
                intent1.putExtra(EXTRAS_DEVICE_NAME, device1.getName());
                intent1.putExtra(EXTRAS_DEVICE_ADDRESS, device1.getAddress());
                if (mScanning) {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    mScanning = false;
                }

                // setResult  intent data Activity
                setResult(Activity.RESULT_OK, intent1);
                //? Activity
                finish();
                //                    startActivity(intent1);
            }
        }
    });
}

From source file:com.microchip.pcs.DeviceScanActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getActionBar().setTitle("MultiEVo"); //Display "BLE Device Scan" on the action bar
    mHandler = new Handler(); //Create Handler to stop scanning
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { //Check if BLE is supported
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); //Message that BLE not supported
        finish(); //End the app
    }//  w  ww.j a  v a 2s.com

    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); //Get the BluetoothManager
    mBluetoothAdapter = bluetoothManager.getAdapter(); //Get a reference to the BluetoothAdapter (radio)

    if (mBluetoothAdapter == null) { //Check if we got the BluetoothAdapter
        Toast.makeText(this, R.string.bluetooth_not_supported, Toast.LENGTH_SHORT).show(); //Message that Bluetooth not supported
        finish(); //End the app
    }
}

From source file:com.google.sample.beaconservice.MainActivityFragment.java

private void createScanner() {
    BluetoothManager btManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter btAdapter = btManager.getAdapter();
    if (btAdapter == null || !btAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, Constants.REQUEST_CODE_ENABLE_BLE);
    }/*from   w  ww. j  ava  2  s  .c  o  m*/
    if (btAdapter == null || !btAdapter.isEnabled()) {
        Log.e(TAG, "Can't enable Bluetooth");
        Toast.makeText(getActivity(), "Can't enable Bluetooth", Toast.LENGTH_SHORT).show();
        return;
    }
    scanner = btAdapter.getBluetoothLeScanner();
}

From source file:com.mbientlab.metawear.app.ModuleActivity.java

@SuppressWarnings("unchecked")
@Override//  w ww. jav  a2 s .co m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (!bluetoothManager.getAdapter().isEnabled()) {
        final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    }

    getApplicationContext().bindService(new Intent(this, MetaWearBleService.class), this,
            Context.BIND_AUTO_CREATE);

    if (savedInstanceState != null) {
        device = (BluetoothDevice) savedInstanceState.getParcelable(EXTRA_BLE_DEVICE);
        moduleFragment = (ModuleFragment) getSupportFragmentManager().getFragment(savedInstanceState,
                "mContent");

        tapType = savedInstanceState.getInt(Extra.TAP_TYPE);
        tapAxis = savedInstanceState.getInt(Extra.TAP_AXIS);
        shakeAxis = savedInstanceState.getInt(Extra.SHAKE_AXIS);
        dataRange = savedInstanceState.getInt(Extra.DATA_RANGE);
        samplingRate = savedInstanceState.getInt(Extra.SAMPLING_RATE);
        ffMovement = savedInstanceState.getBoolean(Extra.FF_MOVEMENT);
        newFirmware = savedInstanceState.getBoolean(Extra.NEW_FIRMWARE);
        samplingConfigBytes = savedInstanceState.getByteArray(Extra.SAMPLING_CONFIG_BYTES);
        polledData = (ArrayList<byte[]>) savedInstanceState.getSerializable(Extra.POLLED_DATA);
    }
}

From source file:ch.ethz.inf.vs.a1.fabischn.ble.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // TODO when bluetooth is off, concurrently the onCreate keeps running.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_LONG).show();
        finish();//from ww w.  j  a va  2 s . co  m
        return;
    }

    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // TODO onActivityResult, check if Cancelled or not, then continue or leave
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        // REQUEST_ENABLE_BT will be returned as requestCode from onActivityResult
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    // TODO change this if onActivity Result is used
    // Continues scanning if enabled, else toast and finish
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    // TODO lookup the correct idiom for this, look at onRequestPermissionsResult
    // We need this for Android 6.0+
    if (checkLocationPermission()) {

    } else {
        ActivityCompat.requestPermissions(this,
                new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, 1);
    }

    if (mBluetoothAdapter != null) {
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    }
    ScanFilter.Builder filterBuilder = new ScanFilter.Builder();
    mScanFilter = filterBuilder.setDeviceName("Smart Humigadget").build();
    ScanSettings.Builder settingsBuilder = new ScanSettings.Builder();
    mScanSettings = settingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            //                .setMatchMode(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
            //                .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
            .build();
    mScanFilters = new ArrayList<ScanFilter>();
    mScanFilters.add(mScanFilter);

}