I have built an app for Android Wear that needs to measure the motion (accelerometer) sensors continuously for an hour or so for data collection purposes. During operation, I have had problems with the device going into ambient mode (or sleep) and slowing down (or shutting off) the sensors.
As a result, I am using the following command to lock the screen on and it seems to work. But it also seems wasteful, since I dont actually need the screen on, just the sensors running.
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Allow going to sleep
CUrrently, I have the onSensorsChanged() method in the main activity. I am willing to put it in a service, but from what I understand that won't help if it is still in the main UI thread. I could put it in its own thread, but I'm not sure that that will present Ambient Mode from slowing the sensors.
1) Is there way to prevent ambient mode? Or if detected to turn it off?
2) If the sensors are in their own service/thread, can I let the activity go to sleep and still maintain sensor collection at full rate?
3) If the sensors are in their own service/thread, can I still send data over the dataapi to the phone?
1) Use a wake lock. To keep the device from going into ambient, you can use code like the following:
PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.acquire(duration);
TAG is a string to indicate the component holding the wake lock, and
duration is measured in milliseconds.
I assume I don't need to warn you about the adverse battery effects of keeping the device from going into ambient. An average Wear device may or may not last for the solid hour you're proposing.
2) Yes. This is kind of the definition of a
Service, "an application component representing either an application's desire to perform a longer-running operation while not interacting with the user" (from https://developer.android.com/reference/android/app/Service.html).
3) Yes. I do this in a number of apps; there's no requirement that Data API calls need to be on the UI thread.