服务器内的计时器在设备重启

时间:2017-06-27 12:22:47

标签: android android-service android-broadcastreceiver android-timer

我正在使用广播接收器重启设备后启动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;
        }
    }
}

0 个答案:

没有答案