Wakelock implementation in a service

2019-08-03 22:02发布

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.

2条回答
beautiful°
2楼-- · 2019-08-03 22:09

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.

查看更多
唯我独甜
3楼-- · 2019-08-03 22:23

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.

查看更多
登录 后发表回答