问题
I want to create a service in Android which will initially ask user if they want to start Bluetooth and set the Bluetooth discovery.
My question is:
Can I launch in the service following activities?
if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 0); } // Set Phone Discoverable for 300 seconds. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600); startActivity(discoverableIntent);
I want to set discoverabilty of the phone on for lifetime of application. Is it possible?
I want to access empty space available on SD card. How should i do it?
Thanks in advance.
回答1:
1) You cannot use that particular code because you cannot call startActivity()
from a service. You would need to use the following code to enable the Bluetooth:
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapter.enable();
The documentation says
boolean enable()
Turn on the local Bluetooth adapter—do not use without explicit user action to turn on Bluetooth.
So you need to be sure to prompt the user first. Also you cannot set the device to be discoverable in the service because the only way to do that is with the startActivity()
so you would need to do that part in some kind of a configuration Activity.
2) No, having a Bluetooth device be discoverable opens it up to a multitude of security concerns, so not only is it not possible, it's a bad idea.
3) If you want to write to the SDCard you just need to add the WRITE_EXTERNAL_STORAGE
permission to your manifest file and then you can use standard Java File IO.
来源:https://stackoverflow.com/questions/2585332/creating-service-with-bluetooth-activation-in-android