我正在使用广播接收器在设备重新启动后启动一个 android 服务和一个活动。内部服务我使用如下计时器。但启动服务后,计时器无法正常工作。定时器连续触发,没有任何时间间隔。我在计时器内使用了以下日志,它连续打印,没有任何时间间隔。
D/timer test: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
大约 1 分钟后计时器再次正常工作。(具有相关的时间间隔)我想正常工作计时器,我该如何解决这个问题?
广播接收器
public class BootReceiver extends BroadcastReceiver {
private Intent ServiceIntent;
@Override
public void onReceive(Context context, Intent intent) {
ServiceIntent = new Intent(context, MyService.class);
context.startService(ServiceIntent);
Toast.makeText(context, "Boot Receiver", Toast.LENGTH_LONG).show();
Intent intentx = new Intent(context, MainActivity.class);
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentx);
}
}
服务
public class MyService extends Service {
private Timer timer;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("timer test", "*********************" + " Service Started " + "*********************");
if (null != timer) {
timer.cancel();
timer.purge();
timer = null;
}
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.d("timer test", "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}, 5 * 1000, 10 * 1000);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != timer) {
timer.cancel();
timer.purge();
timer = null;
}
}
}