Java Code Examples for android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED

The following examples show how to use android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED . 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: JayPS-AndroidApp   File: Ble.java    License: MIT License 6 votes vote down vote up
@Override
    public void start(String ble_address1, String ble_address2, String ble_address3, Bus bus, IInjectionContainer container) {
        Log.d(TAG, "start");

        container.inject(this);
        _bus = bus;
        _bleStarted = true;

        // for later reconnections
        _ble_address1 = ble_address1;
        _ble_address2 = ble_address2;
        _ble_address3 = ble_address3;

//        String BLE_JAY_HRM1 = "1C:BA:8C:1F:58:1D";
//        String BLE_JAY_HRM2 = "E0:C7:9D:69:1E:57";
//        String BLE_JAY_CSC  = "EB:18:F4:AA:92:4E";
//        _ble_address1 = BLE_JAY_HRM1;_ble_address2 = BLE_JAY_HRM2;

        Log.d(TAG, "_ble_address1=" + _ble_address1 + " _ble_address2 = " + _ble_address2 + " _ble_address3 = " + _ble_address3);

        initialize();

        // Register for broadcasts on BluetoothAdapter state change
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        _context.registerReceiver(mReceiver, filter);
    }
 
Example 2
@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    if(action == BluetoothAdapter.ACTION_STATE_CHANGED) {

        int previousState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.ERROR);
        int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
        if(previousState == BluetoothAdapter.STATE_OFF || previousState == BluetoothAdapter.STATE_TURNING_OFF) {
            if(state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_TURNING_ON) {
                mCallaback.onBluetoothEnabled();
            } else if(state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_TURNING_OFF) {
                mCallaback.onBluetoothDisabled();
            }
        }
    }
    else {
        return;
    }
}
 
Example 3
Source Project: EasyBle   File: BleReceiver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (TextUtils.isEmpty(action)) {
        return;
    }
    switch (action) {
        case BluetoothAdapter.ACTION_STATE_CHANGED:
            for (BluetoothStateChangedListener l : listeners) {
                if (l != null) {
                    l.onBluetoothStateChanged();
                }
            }
            break;
    }
}
 
Example 4
@Override
protected void onResume() {
    super.onResume();
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter != null) {
        isBluetoothAdapterEnabled = bluetoothAdapter.isEnabled();
    } else {
        isBluetoothAdapterEnabled = false;
    }

    if (!isBluetoothAdapterEnabled) {
        showEnableBluetoothAdapterBar();
    }

    if (!isLocationEnabled()) {
        showLocationDisabledBar();
    } else {
        hideLocationDisabledBar();
    }

    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(bluetoothAdapterStateChangeListener, filter);
}
 
Example 5
@Override
public void onReceive(final Context context, final Intent intent) {
    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
    final ILogger logger = getBinder();

    final String stateString = "[Broadcast] Action received: " + BluetoothAdapter.ACTION_STATE_CHANGED + ", state changed to " + state2String(state);
    logger.log(Log.DEBUG, stateString);

    switch (state) {
        case BluetoothAdapter.STATE_ON:
            onBluetoothEnabled();
            break;
        case BluetoothAdapter.STATE_TURNING_OFF:
        case BluetoothAdapter.STATE_OFF:
            onBluetoothDisabled();
            break;
    }
}
 
Example 6
Source Project: beacons-android   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 7
Source Project: blefun-androidthings   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 8
@ReactMethod
public void start(ReadableMap options, Callback callback) {
	Log.d(LOG_TAG, "start");
	if (getBluetoothAdapter() == null) {
		Log.d(LOG_TAG, "No bluetooth support");
		callback.invoke("No bluetooth support");
		return;
	}
	forceLegacy = false;
	if (options.hasKey("forceLegacy")) {
		forceLegacy = options.getBoolean("forceLegacy");
	}

	if (Build.VERSION.SDK_INT >= LOLLIPOP && !forceLegacy) {
		scanManager = new LollipopScanManager(reactContext, this);
	} else {
		scanManager = new LegacyScanManager(reactContext, this);
	}

	IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
	filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
	context.registerReceiver(mReceiver, filter);
	callback.invoke();
	Log.d(LOG_TAG, "BleManager initialized");
}
 
Example 9
Source Project: beacons-android   File: BleService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (null == action) {
        return;
    }

    switch (action) {
        case BluetoothAdapter.ACTION_STATE_CHANGED:
            handleBluetoothStateChanged(intent);
            break;
        case ACTION_ITEM_STATE:
            handleItemState(intent);
            break;
    }
}
 
Example 10
Source Project: blessed-android   File: BluetoothCentral.java    License: MIT License 5 votes vote down vote up
/**
 * Construct a new BluetoothCentral object
 *
 * @param context                  Android application environment.
 * @param bluetoothCentralCallback the callback to call for updates
 * @param handler                  Handler to use for callbacks.
 */
public BluetoothCentral(Context context, BluetoothCentralCallback bluetoothCentralCallback, Handler handler) {
    if (context == null) {
        Timber.e("context is 'null', cannot create BluetoothCentral");
    }
    if (bluetoothCentralCallback == null) {
        Timber.e("callback is 'null', cannot create BluetoothCentral");
    }
    this.context = context;
    this.bluetoothCentralCallback = bluetoothCentralCallback;
    this.callBackHandler = (handler != null) ? handler : new Handler();
    this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.autoConnectScanSettings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
                .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
                .setReportDelay(0L)
                .build();
    } else {
        this.autoConnectScanSettings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                .setReportDelay(0L)
                .build();
    }
    setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    if (context != null) {
        context.registerReceiver(adapterStateReceiver, filter);
    }
}
 
Example 11
/**
 * Test typical case, bluetooth was off when app was started, user turns it on
 */
@Test
public void testBluetoothOnCallbackShouldHappenAfterDelay() throws InterruptedException {
    // assume not flapping at start
    // statusListener.setLastEvent(SystemClock.elapsedRealtimeNanos() - BluetoothRadioStatusListener.MIN_CALLBACK_DELAY);
    // assume BT was off
    statusListener.setCurrentState(BluetoothAdapter.STATE_OFF);
    final long startTime = SystemClock.elapsedRealtime();
    CountDownLatch cdl = new CountDownLatch(1);
    statusListener.setListener(new BluetoothRadioStatusListener.BluetoothOnListener() {
        @Override
        public void bluetoothOff() {
            fail();
        }

        @Override
        public void bluetoothOn() {
            long endTime = SystemClock.elapsedRealtime();
            assertTrue(endTime - startTime >= BluetoothRadioStatusListener.MIN_TURNING_ON_CALLBACK_DELAY);
            cdl.countDown();
        }

        @Override
        public void bluetoothTurningOff() {
            fail();
        }

        @Override
        public void bluetoothTurningOn() {
            fail();
        }
    });
    // bluetooth on intent
    Intent i = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
    i.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON);
    statusListener.receiver.onReceive(ctx, i);
    cdl.await(2, TimeUnit.SECONDS);
    statusListener.removeListener();
}
 
Example 12
private void setupBluetoothBroadcastReceiver(){
    String[] actions = new String[4];
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        actions[0] = BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED;
    }else{
        actions[0] = "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
    }
    actions[1] = BluetoothAdapter.ACTION_STATE_CHANGED;
    actions[2] = BluetoothDevice.ACTION_ACL_DISCONNECTED;
    actions[3] = BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED;

    listenForIntents(actions);
}
 
Example 13
@Override
    protected void onResume() {
        super.onResume();
        configureFontScale();

        scanningGradientContainer.setVisibility(View.VISIBLE);

        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(bluetoothAdapterStateChangeListener, filter);

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if(!scanning){
            setScanningButtonStart();
        }

        if (!bluetoothAdapter.isEnabled()) {
            finish();
        }

        if (bluetoothAdapter != null) {
            isBluetoothAdapterEnabled = bluetoothAdapter.isEnabled();
            if (boundService != null) {
                Log.d("OnResume", "Called");
//                boundService.clearGatt();
                boundService = null;

            }
            if (bluetoothBinding != null) {
                bluetoothBinding.unbind();
            }
        } else {
            isBluetoothAdapterEnabled = false;
        }
        updateCountOfConnectedDevices();
        devicesAdapter.notifyDataSetChanged();
    }
 
Example 14
@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 15
Source Project: blue-pair   File: BroadcastReceiverDelegator.java    License: MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Log.d(TAG, "Incoming intent : " + action);
    switch (action) {
        case BluetoothDevice.ACTION_FOUND :
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.d(TAG, "Device discovered! " + BluetoothController.deviceToString(device));
            listener.onDeviceDiscovered(device);
            break;
        case BluetoothAdapter.ACTION_DISCOVERY_FINISHED :
            // Discovery has ended.
            Log.d(TAG, "Discovery ended.");
            listener.onDeviceDiscoveryEnd();
            break;
        case BluetoothAdapter.ACTION_STATE_CHANGED :
            // Discovery state changed.
            Log.d(TAG, "Bluetooth state changed.");
            listener.onBluetoothStatusChanged();
            break;
        case BluetoothDevice.ACTION_BOND_STATE_CHANGED :
            // Pairing state has changed.
            Log.d(TAG, "Bluetooth bonding state changed.");
            listener.onDevicePairingEnded();
            break;
        default :
            // Does nothing.
            break;
    }
}
 
Example 16
/**
 * Will start listening to the global bluetooth adapter broadcasts
 */

void startListening() {
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    context.getApplicationContext().registerReceiver(receiver, filter);
}
 
Example 17
/**
 * Helper method that returns an intent filter for this receiver.
 * @return
 */
private static IntentFilter getIntentFilter() {
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    return filter;
}
 
Example 18
Source Project: batteryhub   File: ConnectivityReceiver.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Used to start update network status.
 *
 * @param context the context
 * @param intent  the intent
 */
@Override
public void onReceive(Context context, Intent intent) {
    int state;
    String action = intent.getAction();

    if (action == null) return;

    switch (action) {
        case ConnectivityManager.CONNECTIVITY_ACTION:
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getSystemService(
                            Context.CONNECTIVITY_SERVICE
                    );

            if (connectivityManager == null) return;

            NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();

            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();

            if (!isConnected) {
                EventBus.getDefault().post(new RefreshEvent("wifi", false));
                EventBus.getDefault().post(new RefreshEvent("mobile", false));
                return;
            }

            // Reset upload uploadAttempts counter on network state change
            CommunicationManager.uploadAttempts = 0;

            // Update Server Status
            new ServerStatusTask().execute(context);

            if (SettingsUtils.isDeviceRegistered(context)) {
                new CheckNewMessagesTask().execute(context);
            }

            if (CommunicationManager.isQueued && SettingsUtils.isServerUrlPresent(context)) {
                CommunicationManager manager = new CommunicationManager(context, true);
                manager.sendSamples();
                CommunicationManager.isQueued = false;
            }

            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                EventBus.getDefault().post(new RefreshEvent("wifi", true));
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                EventBus.getDefault().post(new RefreshEvent("mobile", true));
            }
            break;
        case BluetoothAdapter.ACTION_STATE_CHANGED:
            state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            if (state == BluetoothAdapter.STATE_ON) {
                EventBus.getDefault().post(new RefreshEvent("bluetooth", true));
            } else {
                EventBus.getDefault().post(new RefreshEvent("bluetooth", false));
            }
            break;
    }
}
 
Example 19
private void registerBluetoothState() {
    IntentFilter i = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    i.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    context.registerReceiver(broadcastReceiver, i);
}
 
Example 20
Source Project: neatle   File: BaseScanner.java    License: MIT License 4 votes vote down vote up
private void registerStateReciever(Context context) {
    IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    context.registerReceiver(broadcastReceiver, intentFilter);
}