问题
As a requirement in Android OS phone, I am developing an app which will clean up a particular folder in a specified interval of time, say every 30 minutes.
I can run a service and clean up the folder every 30 mins. I have few questions over this,
1.Service has onStartCommand, which will be executed when the service starts, can I call a function here which has a Handler which runs every 30 minutes? Example
public int onStartCommand(Intent intent, int flags, int startId){
cleanUpData();
return START_REDELIVER_INTENT;
}
public void cleanUpData()
{
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// call the function again
cleanUpData();
}
}, "30 mins");
}
This code iterates the cleanUpData every 30 mins. a. Is this correct? b. Will this hamper the performance? c. Should I use a separate thread as mentioned in numerous tutorials? d. Should I use a service after-all? Or is there any other method?
- AlarmManager provides the scheduled repeated alarms, but this does not work when the phone is in sleep mode. I do not want to wake up the screen as it does not require any human interaction. Can I ignore AlarmManager? Or does AlarmManager has functionality to run the code even when the phone is in sleep mode and phone wake up is false?
Please suggest. Thanks in advance!
回答1:
you should use a separate thread for cleaning up the folder.I will not suggest you to use handler inside a service as it runs in the same process as app so a long running operation can make it unresponsive,instead of this use intentservice as it runs on its own thread. And for the device sleep problem fire an broadcast receiver and acquire custom wake up lock in this broadcast receiver and then invoke your service from here.
来源:https://stackoverflow.com/questions/26602630/file-cleaning-service