Example usage for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED

List of usage examples for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED.

Prototype

String ACTION_STATE_CHANGED

To view the source code for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED.

Click Source Link

Document

Broadcast Action: The state of the local Bluetooth adapter has been changed.

Usage

From source file:com.orange.beaconme_sdk.ble.control.BLEDeviceManager.java

private BLEDeviceManager(Context context) {
    this.context = context.getApplicationContext();
    launchService();//from   www .ja va  2 s.  c o m
    context.registerReceiver(bluetoothBroadcastReceiver,
            new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}

From source file:com.manuelmazzuola.speedtogglebluetooth.service.MonitorSpeed.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    running = Boolean.TRUE;//from w w w  .j  a  v  a2 s  .c  o  m

    lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    provider = lm.NETWORK_PROVIDER;
    oldLocation = lm.getLastKnownLocation(provider);

    IntentFilter filters = new IntentFilter();
    // When to turn off bluetooth
    filters.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    // When hold bluetooth on
    filters.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    // When user directly turn on or off bluetooth
    filters.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

    registerReceiver(bluetoothListener, filters);
    lm.requestLocationUpdates(provider, 45 * 1000, 0f, this);

    Intent stopIntent = new Intent(this, MainActivity.class);
    stopIntent.putExtra("close", "close");
    PendingIntent stopPendingIntent = PendingIntent.getActivity(this, 0, stopIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder note = new NotificationCompat.Builder(getApplicationContext())
            .setContentTitle(DEFAULT_TITLE).setContentText(DEFAULT_MESSAGE)
            .setDefaults(Notification.DEFAULT_VIBRATE).setAutoCancel(true).setContentIntent(stopPendingIntent)
            .setSmallIcon(R.drawable.ic_action_bluetooth);

    note.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;

    Notification notification = note.build();
    notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;

    startForeground(intentId, note.build());

    return START_NOT_STICKY;
}

From source file:org.physical_web.physicalweb.PhysicalWebBroadcastService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    fetchBroadcastData(intent);//from   www . j  a  v  a  2s  . com
    if (mDisplayUrl == null) {
        stopSelf();
        return START_STICKY;
    }
    Log.d(TAG, "SERVICE onStartCommand");
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);

    Log.d(TAG, mDisplayUrl);
    byte[] encodedUrl = AdvertiseDataUtils.encodeUri(mDisplayUrl);
    if (hasValidUrlLength(encodedUrl.length) && checkAndHandleAsciiUrl(mDisplayUrl)) {
        // Set the url if we can
        Log.d(TAG, "valid length");
        mShareUrl = encodedUrl;
        broadcastUrl();
    } else {
        Log.d(TAG, "needs shortening");
        UrlShortenerClient.ShortenUrlCallback urlSetter = new UrlShortenerClient.ShortenUrlCallback() {
            @Override
            public void onUrlShortened(String newUrl) {
                Log.d(TAG, "shortening success");
                mShareUrl = AdvertiseDataUtils.encodeUri(newUrl);
                broadcastUrl();
            }

            @Override
            public void onError(String oldUrl) {
                Toast.makeText(getApplicationContext(), getString(R.string.shorten_error), Toast.LENGTH_LONG)
                        .show();
                stopSelf();
            }
        };
        UrlShortenerClient shortenerClient = UrlShortenerClient.getInstance(this);

        if (mDisplayUrl.contains("goo.gl")) {
            // find the site URL and reshorten it since
            // goo.gl will not reshorten other goo.gl links
            fetchAndShorten(shortenerClient, urlSetter);
        } else {
            shortenerClient.shortenUrl(mDisplayUrl, urlSetter, TAG);
        }
    }
    return START_STICKY;
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java

@RequiresPermission(Manifest.permission.BLUETOOTH)
public NativeBluetoothStack(@NonNull Context applicationContext, @NonNull ErrorListener errorListener,
        @NonNull LoggerFacade logger) {//  w ww  .  java 2s .  c o m
    this.applicationContext = applicationContext;
    this.errorListener = errorListener;
    this.logger = logger;

    this.bluetoothManager = (BluetoothManager) applicationContext.getSystemService(Context.BLUETOOTH_SERVICE);
    this.adapter = bluetoothManager.getAdapter();
    if (adapter != null) {
        final BroadcastReceiver powerStateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                if (newState == BluetoothAdapter.STATE_ON) {
                    enabled.onNext(true);
                } else if (newState == BluetoothAdapter.STATE_OFF || newState == BluetoothAdapter.ERROR) {
                    enabled.onNext(false);
                }
            }
        };
        applicationContext.registerReceiver(powerStateReceiver,
                new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
        enabled.onNext(adapter.isEnabled());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final BroadcastReceiver pairingReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    final Intent broadcast = new Intent(ACTION_PAIRING_REQUEST);
                    broadcast.putExtra(GattPeripheral.EXTRA_NAME, device.getName());
                    broadcast.putExtra(GattPeripheral.EXTRA_ADDRESS, device.getAddress());
                    LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
                }
            };
            applicationContext.registerReceiver(pairingReceiver,
                    new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST));
        }
    } else {
        logger.warn(LOG_TAG, "Host device has no bluetooth hardware!");
        enabled.onNext(false);
    }
}

From source file:in.ac.dtu.curo.CuroMainActivity.java

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

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();//from www.  j  a va  2  s .  co  m

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
    mUiHandler = new Handler(new UiHandlerCallback());

    initDevicePicker();
    registerReceiver(mBtStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

}

From source file:com.google.android.apps.forscience.whistlepunk.devicemanager.ManageDevicesActivity.java

private void registerBtReceiverIfNecessary() {
    if (mBtReceiver == null) {
        mBtReceiver = new BroadcastReceiver() {
            @Override//w w w.j  a  v  a2  s  .  c  o m
            public void onReceive(Context context, Intent intent) {
                setFragment();
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBtReceiver, filter);
    }
}

From source file:com.mattprecious.notisync.service.PrimaryService.java

@Override
public void onCreate() {
    super.onCreate();

    broadcastManager = LocalBroadcastManager.getInstance(this);

    running = true;/*from w w w.j av a2 s.com*/
    broadcastManager.sendBroadcast(new Intent(ServiceActions.ACTION_SERVICE_STARTED));

    if (bluetoothAdapter == null) {
        stopSelf();
        return;
    }

    dbAdapter = new DbAdapter(this);

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = buildRunningNotification();
    startForeground(NOTIFICATION_ID_RUNNING, notification);

    handler = new PrimaryHandler(this);

    broadcastManager.registerReceiver(updateDevicesReceiver, new IntentFilter(ACTION_UPDATE_DEVICES));
    broadcastManager.registerReceiver(timerReceiver, new IntentFilter(ServiceActions.ACTION_UPDATE_TIMER));
    broadcastManager.registerReceiver(sendMessageReceiver, new IntentFilter(ACTION_SEND_MESSAGE));
    broadcastManager.registerReceiver(devToolsSendMessageReceiver,
            new IntentFilter(DevToolsActivity.ACTION_SEND_MESSAGE));

    registerReceiver(reconnectReceiver, new IntentFilter(ACTION_RECONNECT));
    registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    registerReceiver(smsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
    registerReceiver(phoneReceiver, new IntentFilter("android.intent.action.PHONE_STATE"));

    updateTimer();
}

From source file:io.v.android.impl.google.discovery.plugins.ble.Driver.java

/**
 * Create a new BLE driver for Android.//from w  w w.ja v  a  2 s  .c  om
 *
 * @param vContext Vanadium context.
 */
public Driver(VContext vContext) {
    mContext = V.getAndroidContext(vContext);
    if (mContext == null) {
        throw new IllegalStateException("AndroidContext not available");
    }
    mServices = new HashMap<>();

    BluetoothManager manager = ((BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE));
    mBluetoothAdapter = manager.getAdapter();
    if (mBluetoothAdapter == null) {
        Log.w(TAG, "BluetoothAdapter not available");
        return;
    }

    if (ContextCompat.checkSelfPermission(mContext,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(mContext,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.w(TAG, "ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION not granted, "
                + "Bluetooth discovery will not be happening");
        return;
    }

    mContext.registerReceiver(new BluetoothAdapterStatusReceiver(),
            new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    if (!mBluetoothAdapter.isEnabled()) {
        // Prompt user to turn on Bluetooth.
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(enableBtIntent);
        return;
    }
    resume();
}

From source file:org.jonblack.bluetrack.activities.LiveTrackingFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    Log.d(TAG, "onActivityCreated");

    super.onActivityCreated(savedInstanceState);

    PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Bluetrack");

    // Restore state
    if (savedInstanceState != null) {
        mSessionId = savedInstanceState.getLong("sessionId");
        mTracking = savedInstanceState.getBoolean("tracking");

        Log.v(TAG, String.format("Restoring state: mSessionId=%d mTracking=%s", mSessionId, mTracking));

        if (mTracking) {
            // This should get the loader that was already created.
            getLoaderManager().initLoader(0, null, this);
        }/*from w  w  w  .  ja  v  a2  s .  c  o  m*/
    }

    // Register broadcast receiver for bluetooth status changes
    getActivity().registerReceiver(this.mBtStateChangedReceiver,
            new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

    // Configure the ListView adapter, which will connect to the database.
    mAdapter = new LiveTrackingCursorAdapter(getActivity(), null, 0);
    setListAdapter(mAdapter);
}

From source file:com.molidt.easyandroid.bluetooth.BluetoothFragmentV4.java

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

    if (!isInit) {
        initPlugin(_activity);//from w w  w  .  ja v a  2 s  . c o m
    }

    _Handler = new Handler();

    //if UUID is null,using the package name to setting the default UUID
    if (BLUETOOTH_UUID == null) {
        BLUETOOTH_UUID = UUID.fromString(_activity.getPackageName());
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    _activity.registerReceiver(mFoundReceiver, filter);

    if (isSupportBLE) {
        Intent gattServiceIntent = new Intent(_activity, BluetoothLeService.class);
        _activity.bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }
}