我有一个Android后台服务,它使用里面的计时器来安排一些任务。只要应用程序运行,它就可以正常工作。但是当我关闭应用程序时,服务仍在运行但计时器停止并且不再执行任务。 请提出一些解决方案。
服务:
public class UpdateExpectedService extends Service {
public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds
private Timer mTimer = null;
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
// If we get killed, after returning from here, restart
return START_STICKY;
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
// display toast
Toast.makeText(getApplicationContext(), getDateTime(),
Toast.LENGTH_SHORT).show();
Log.i("ABC", "ABC");
DatabaseHandler db = new DatabaseHandler(UpdateExpectedService.this);
db.addExpectedService( new ExpectedList("TEMP", "TEMP", new Date()));
}
});
}
private String getDateTime() {
// get date time in custom format
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
}