Android Bluetooth from the service

I have a service that can theoretically work without an action associated with it (since the β€œservices” are for the Android platform).

This service uses Bluetooth, in particular, registers a Bluetooth service with the given name, which listens to messages. Of course, for it to work, it must have active Bluetooth.

As also shown in the api docs bluetooth, I use BluetoothAdapter.ACTION_REQUEST_ENABLEto prompt the user to turn on bluetooth if it is not already on. This, however, is an activity and therefore must be called from another action, that is:

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

What I would like to achieve is to have a service (which, for example, starts at boot) that is completely separate from any Activity, and therefore will not have InstanceOfAnActivityBluetooth turned on to start a pop-up briefing.

Now I know that there is a (notorious) call BluetoothAdapter.enable(), but since the document says that it cannot be called directly.

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

+3
source share
2 answers

startActivity() - , Activity Service. , , , Service.startActivity() ", , FLAG_ACTIVITY_NEW_TASK".

, "", , :

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

doc

Bluetooth . Bluetooth , ACTION_REQUEST_ENABLE Intent, , Bluetooth. enable() , , "power manager".

, BluetoothAdapter.enable(), , . , , , Bluetooth, .

+2

Source: https://habr.com/ru/post/1736212/


All Articles