我需要一个应该一直运行的服务,直到它被我的 Activity 明确停止,并且即使它由于某些问题而停止(START_STICKY
标志)也应该重新启动。此服务应使用 TimerTask
连续执行某些操作(每隔几秒)。我最终得到了以下代码。
public class SomeService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
TimerTask timerTask;
final Handler handler = new Handler();
Timer timer = new Timer();
@Override
public void onCreate() {
// code to execute when the service is first created
super.onCreate();
}
@Override
public void onDestroy() {
// code to execute when the service is shutting down
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startid) {
// code to execute when the service is starting up
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//KEEP RUNNING SOME ERRANDS HERE
}
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 100L, 1700L);
}
}
无论如何我可以优化它以连续运行吗?
最佳答案
每秒运行一次听起来很过分,但是您有什么理由不使用 AlarmManager 来触发 IntentService 吗?然后系统将负责可靠地触发您的服务。你是否能实现可靠的 1 秒重新触发,我不知道。由于马克在另一个答案中提到的原因,这似乎是个坏主意。
关于android - 使用持续执行的 TimerTask 优化服务运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7436649/