android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED源码实例Demo

下面列出了android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: JayPS-AndroidApp   文件: Ble.java
@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);
    }
 
@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;
    }
}
 
源代码3 项目: EasyBle   文件: BleReceiver.java
@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;
    }
}
 
源代码4 项目: EFRConnect-android   文件: MainMenuActivity.java
@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);
}
 
源代码5 项目: Android-nRF-Toolbox   文件: BleProfileService.java
@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;
    }
}
 
源代码6 项目: beacons-android   文件: BleService.java
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();
    }
}
 
源代码7 项目: blefun-androidthings   文件: GattServer.java
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();
    }
}
 
源代码8 项目: react-native-ble-manager   文件: BleManager.java
@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");
}
 
源代码9 项目: beacons-android   文件: BleService.java
@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;
    }
}
 
源代码10 项目: blessed-android   文件: BluetoothCentral.java
/**
 * 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);
    }
}
 
源代码11 项目: bitgatt   文件: BluetoothRadioStatusListenerTest.java
/**
 * 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();
}
 
源代码12 项目: sdl_java_suite   文件: MediaStreamingStatus.java
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);
}
 
源代码13 项目: EFRConnect-android   文件: BrowserActivity.java
@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();
    }
 
@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();

}
 
源代码15 项目: blue-pair   文件: BroadcastReceiverDelegator.java
/**
 * {@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;
    }
}
 
源代码16 项目: bitgatt   文件: BluetoothRadioStatusListener.java
/**
 * Will start listening to the global bluetooth adapter broadcasts
 */

void startListening() {
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    context.getApplicationContext().registerReceiver(receiver, filter);
}
 
/**
 * 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;
}
 
源代码18 项目: batteryhub   文件: ConnectivityReceiver.java
/**
 * 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;
    }
}
 
源代码19 项目: tap-android-sdk   文件: BluetoothManager.java
private void registerBluetoothState() {
    IntentFilter i = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    i.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    context.registerReceiver(broadcastReceiver, i);
}
 
源代码20 项目: neatle   文件: BaseScanner.java
private void registerStateReciever(Context context) {
    IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    context.registerReceiver(broadcastReceiver, intentFilter);
}