我需要一个应该一直运行的服务,直到它被我的活动明确停止,并且应该重新启动,即使它由于某些问题(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);
}
}
无论如何我可以优化它以连续运行吗?