cloud
cloud

Reputation: 159

Android Bluetooth from within Service

I have a service that theoretically can work without an Activity associated to it (as "services" are intended on the Android platform).

This service uses Bluetooth, in particular registers a Bluetooth Service with a given Name that listens for communications. Of course to work it has to have the Bluetooth active.

As also shown on the Bluetooth api docs I'm using the BluetoothAdapter.ACTION_REQUEST_ENABLE to prompt the user to enable Bluetooth in case it's not on already. This, though, is an activity, and therefore needs to be called from another activity, i.e.:

Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
InstanceOfAnActivity.startActivity(enableIntent);

What I would want to achieve is to have the service (which, for example, starts up at boot), completely decoupled from any Activity, and therefore wouldn't have the InstanceOfAnActivity to start up the pop-up instructing the user to turn on Bluetooth.

Now, I know that there's the (infamous) call to BluetoothAdapter.enable(), but as the doc says it shouldn't be called directly.

So, any tip/solution to this dilemma? (Maybe it's easy and I'm just missing something...)

Upvotes: 5

Views: 13463

Answers (2)

EarlMagnus
EarlMagnus

Reputation: 51

startActivity() is not strictly an Activity method - it is a Context method, inherited by Activity and Service. There is one thing to be aware of, though - as pointed out in the Service.startActivity() doc, "if this method is being called from outside of an Activity Context, then the Intent must include the FLAG_ACTIVITY_NEW_TASK launch flag".

Thus, with 'context' bound to the Service instance, the following should work:

Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(btIntent);

Upvotes: 5

CaseyB
CaseyB

Reputation: 25058

Here's what the doc says

Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.

Note that it doesn't say not to call BluetoothAdapter.enable() directly, it says only to call it if you've gotten the ok from the user. That means that you would need a configuration screen that asked the user if it was ok for your service to turn on bluetooth and that way they could have the control over that.

Upvotes: 1

Related Questions