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...)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With