Reputation: 1127
I have a background service in my app which is started by Widget. When User Starts service it's going to run until user stop it. And that can drain battery a lot if user forgets to stop it. I want to add some safety to switch. To stop service after some time like 5 or 10 minutes. What is the best way to do this?
Upvotes: 1
Views: 1224
Reputation: 6345
You can implement a Handler to stop service after specific delay:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: {
stopSelf();
}break;
}
}
}
And provide your delay below:
handler.sendEmptyMessageDelayed(1, 300000);//add your delay here
Upvotes: 0
Reputation: 15775
Note that unless your Service
is actively processing something or holding a wakelock it is not consuming more battery. A Service
can be in the "running" state but not doing anything. The Android framework is event driven, so unless you are still executing an onStartCommand()
or a background thread you spawned then you are not consuming CPU or battery. That being said, if you do need to kill off your Service
after a specific amount of time, use an alarm set via the AlarmManager
.
Upvotes: 1