Android中定时器实现的方式对比

   在android中经常需要定时循环执行某一段代码,大家首先想到的是Timer,在一般的场合下,Timer和TimerTask可以完全胜任,但是在有些情况下,Timer就不能很好的完成定时循环任务,如与服务器保持长连接,使用轮询方式。当应用程序关闭掉后Timer也将会被kill掉。不过,我们有更好的方式去实现,如使用AlarmClock定时。

  下面对常用的3中定时方式进行比较。

  1.使用Timer和TimerTask完成。

   new Timer().schedule(new TimerTask() {

           @Override 

           public void run() {

              // do some task

               Log.i("TAG","这是普通方式的TimerTask");

           }

       },0,3000);

  这是常规的实现方式,对于大多数人的选择都会采用这种方式实现定时任务。这种实现方式的生命周期和Acticity的生命周期一样,当Activity销毁后,该定时任务也会结束。即退出该应用时,定时任务结束。

2.在Service中开启线程来实现定时器。

 private void serviceTimerTask(){

        mythread =  new Thread(new Runnable() {

            @Override

            public void run() {

                while (true){

                    try {

                        Thread.sleep(3000);

                       // do other task

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }

        });

        mythread.start();

    }

该方法在onCreate()方法中调用,在Service中中断该线程。该定时器的生命周期和Service的生命周期一样,当Service销毁时,该定时任务结束。当退出该应用时,Service不会立即销毁,定时任务不会立即结束。

3.使用系统的AlarmManager来实现定时任务。

  设置定时任务

private void sendRepeatBroadcast(Context context){

        Intent intent = new Intent();

        intent.setAction("com.whhx.ydscience");

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);                                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),3000,pendingIntent);

        updateReceiver = new UpdateReceiver();

        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("com.whhx.ydscience");

        registerReceiver(updateReceiver,intentFilter);

 }

   在广播接收类中完成定时任务。

    public static class UpdateReceiver extends BroadcastReceiver {

        @Override

        public void onReceive(Context context, Intent intent) {

            Log.d("TAG","这是调用系统时钟实现的TimerTask");

        }

    }

  

通过该方式实现的定时器任务,当应用退出后,该定时器任务也不会结束,唯一的结束方法就是通过代码去结束。

private void cancleUpdateBroadcast(Context context){

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);

        Intent intent = new Intent(context,UpdateReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

        alarmManager.cancel(pendingIntent);

    }


  在使用AlarmManager来设置定时器时,在调用方法setRepeating()方法时会传入四个参数,这些参数的含义如下:

  type:这个参数可以设置4种类型

      ELAPSED_REALTIME:当系统进入休眠状态时,这种类型的时钟不会唤醒系统。直到系统下次被唤醒才会传递它,该闹钟所使用的是绝对时间,从系统启动开始计时的,可以通过调用SystemClock.elapsedRealtime()获得。系统值是3。

      ELAPSED_REALTIME_WAKEUP:当系统进入休眠状态,这种类型的闹钟可以唤醒。系统值是2。

      RTC:当系统进入休眠状态时,这种类型的时钟不会唤醒系统。直到系统下次被唤醒才会传递它。该闹钟所使用的是相对时间。可以调用System.currentTimeMillis()获得。系统值是 1。

     RTC_WAKEUP:当系统进入休眠状态时,这种类型的时钟会唤醒系统。系统值是0。设为该模式下除了基本的定时器功能外,还会发出警报声,例如响铃、震动。


     trrggerAtTime  第一次运行等待的时间,也就是执行延迟时间,单位是毫秒。


     interval  表示执行的间隔时间,单位是毫秒。在设置间隔时间时,系统默认为至少60秒,设置少于60秒时,按照60秒为间隔时间,当大于60秒时,按照设置的时间为间隔时间。


    operation   一个PendingIntent对象,表示到时间后要执行的操作。PendingIntent与Intent类似,可以封装Activity、BroadcastReceiver和Service。但与Intent不同的是,PendingIntent可以脱离应用程序而存在。


对比了以上三种定时器方式,选择合适的定时器要根据执行任务的生命周期而定。

   (1)当定时任务同Activity生命周期共存亡,那就使用Timer和TimerTask结合。

   (2)  当定时器的任务同Service生命周期供存亡,使用Service中开启线程完成。

   (3) 完成心跳程序保持长连接,使用AlarmManager去完成定时任务。

  补充:也可以使用Handler去完成定时任务,代码如下:

    模式1:一直循环执行。

   private void handlerExecuteTimerTask(){

        mycircleHandler = new Handler();

        runnable =  new Runnable() {

            @Override

            public void run() {

                Log.d("TAG","这是Handler中一直执行的TimerTask");

                mycircleHandler.postDelayed(this,3000);

            }

        };

        mycircleHandler.postDelayed(runnable,50);

    }


   当结束循环时调用

             mycircleHandler.removeCallbacks(runnable);

    模式二:仅执行一次。

     private void onlyExecuteTimerTask(){

        onlyHandler = new Handler();

        onlyHandler.postDelayed(new Runnable() {

            @Override

            public void run() {

                Log.d("TAG","这是Handler中执行一次的TimerTask");

                onlyHandler.removeCallbacks(this);

            }

        },50);

    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值