Android Wear: measuring sensors and preventing ambient mode / sleep

假装没事ソ 提交于 2019-12-25 09:50:38

问题


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. Questions: 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? Thanks.


回答1:


1) Use a wake lock. To keep the CPU awake but let the screen go dim, 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);

where 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.



来源:https://stackoverflow.com/questions/39058837/android-wear-measuring-sensors-and-preventing-ambient-mode-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!