Ash*_*lix 1 service android timer timertask
我需要一个应该始终运行的服务,直到我的活动显式停止它,并且即使由于某些问题(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);
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以优化它以持续运行吗?
每秒运行听起来相当多,但是有没有理由不使用AlarmManager来触发IntentService?然后系统将负责可靠地触发您的服务.你是否可以实现可靠的1秒重击,我不知道.由于Mark在另一个答案中提到的原因,似乎是一个坏主意.
| 归档时间: |
|
| 查看次数: |
1964 次 |
| 最近记录: |