Wakelock implementation in a service

[亡魂溺海] 提交于 2020-01-06 01:54:38

问题


I have a service that executes in 2 phones. They communicate with each other using sockets and execute some script (which may take 1-2 minutes approx.) and exchange files (using HTTP Post) between them.

I want this execution to continue, even when the screen is off, i.e acquire a Wakelock. I saw this link, but I'm not sure where to incorporate this in my code(as the device may sleep in the mid of execution). Any guidance is highly appreciated. Thank you.


回答1:


I m using same app for 2 phones. In onCreate() it starts a service listening on a port. Clicking a button in phone1, does a HTTP Post of a file to phone2 and the communication keeps going on(as phone 2 also listens on a port initially).

Well, your primary objective seems to be to cause the owner of phone2 to attack you with a scimitar, since the phone2 will run out of battery.

That being said, your HTTP daemon will need to be in a service, where you acquire and release a WakeLock (and presumably a WifiLock, since what you want won't work over most mobile data connections).

WakefulIntentService is not useful here, because it is designed for sensible scenarios, where we need to keep a WakeLock acquired only for a brief period of time, to complete some specific task. In your case, you need to keep your WakeLock acquired indefinitely, as you have no idea when work might need to be done.

I m not sure where to incorporate this in my code.

In the service, presumably. You will probably acquire the WakeLock in onCreate() of the service and release it in onDestroy() of the service. If you wish to avoid a scimitar-related demise, you will make sure that the user has plenty of control over exactly when this service is running, and therefore have plenty of control over when this WakeLock is in force.




回答2:


Why not implement that functionality with a service? See here. I'm not very experienced in android development but have worked recently in a project where a functionality similar to that was implemented using services.



来源:https://stackoverflow.com/questions/13359111/wakelock-implementation-in-a-service

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