Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...)

like image 721
cloud Avatar asked Mar 09 '10 22:03

cloud


Video Answer


1 Answers

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);
like image 153
EarlMagnus Avatar answered Sep 30 '22 08:09

EarlMagnus