I’m a newbie in both Java and Android and I’m trying to figure out how to do the following action. Btw, I find that the official Google Android documentation is NOT for newbies and would like any referral to something a bit more… non-native programmer friendly.
Ok, here goes:
I would like to turn on/off Bluetooth automatically when I plug in/unplug the phone – pc or ac.
So, I have found the following components:
BatteryManager: Seems like using the ACTION_BATTERY_CHANGED intent is the way to go, and setting up a broadcast receiver for when this changes. Is it correct?
I’ve also found BluetoothAdapter and within that, there’s the enable() method. Which says: “do not use without explicit user action to turn on Bluetooth.” – is plugging in the phone a explicit user action? Is this the right thing for me to use? The same goes for disable(), of course.
Also, the BroadcastReceivers I’ve seen examples for in the Internet(s) only show me how to launch an intent – usually to open a new activity. I assume I can have the Broadcast Receiver launch a method in which I will turn bluetooth on and off? Can an intent be a method, and not just activity?
Any help would be appreciated!
Yes, that is one way to monitor things like when a charger has been connected (including plugging to a USB port with charge capability). You can also use
ACTION_POWER_CONNECTED.NO – most definitely not unless you create a pop-up asking for the user’s consent. To quote the docs for the
enable()method…When I plug my device to charge, 9 times out of 10 I don’t want it to do anything but charge. If I had your app installed on my phone and found out it was enabling Bluetooth silently and without my knowledge, your app would be un-installed straight away.
There are known security issues with Bluetooth and, depending on user settings, you could put somebody’s device at risk if it is enabled without their knowledge.
No, an
Intentis part of a messaging system. See Intents and Intent Filters. Yes, I know it’s not very ‘newbie-friendly’ but Android is a complex beast and if you really want to program successfully for it you’ve got to read this sort of stuff.