android 定时任务的几种实现方式

android里有时需要定时循环执行某段代码,或者需要在某个时间点执行某段代码,这个需求大家第一时间会想到Timer对象,没错,不过我们还有更好的选择。


一、Timer 实现定时任务

Timer timer;
void onCreate(){
  ...... 
TimerTask task = new TimerTask(){    
public void run(){    
 // 在此处添加执行的代码    
}    
};    
timer = new Timer();  
timer.schedule(task, 1000);//开启定时器,delay 1s后执行task  
}
void onDestroy(){
......
timer.cancel();//销毁定时器
}

二、Handler实现定时任务

1.隔一段时间后执行某个操作,循环执行:

void onCreate(){    
     ......
     Handler handler = new Handler();  
     Runnable runnable = new Runnable(){  
         @Override  
         public void run() {  
             // TODO Auto-generated method stub  
             // 在此处添加执行的代码  
             handler.postDelayed(this, 50);// 50ms后执行this,即runable  
         }   
     };   
     handler.postDelayed(runnable, 50);// 打开定时器,50ms后执行runnable操作  
}
void onDestroy(){ 
    ......
    handler.removeCallbacks(this);// 关闭定时器处理  
}

2.隔一段时间后执行某个操作一次,执行完后,不再执行:

void onCreate(){ 
......
Handler handler = new Handler();              
        Runnable runnable = new Runnable(){    
        @Override  
        public void run() {  
                        // TODO Auto-generated method stub               
                        // 在此处添加执行的代码  
<span style="white-space:pre">			</span>doSomeThing();
                        handler.removeCallbacks(this); //移除定时任务                                
               }                    
        };  
        handler.postDelayed(runnable, 50);// 打开定时器,50ms后执行runnable  
}

三、AlarmManager实现精确定时操作

我们使用Timer或者handler的时候会发现,delay时间并没有那么准。如果我们需要一个严格准时的定时操作,那么就要用到AlarmManager,AlarmManager对象配合Intent使用,可以定时的开启一个Activity,发送一个BroadCast,或者开启一个Service.
下面的代码详细的介绍了两种定时方式的使用:
(1)在指定时长后执行某项操作

// 以下的代码是<<足球即时比分>>中的代码片段.

<span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 0, 0);"><strong>static</strong></span> AlarmManagerUtil<span style="color: rgb(0, 153, 0);">{</span>
        <span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 0, 0);"><strong>static</strong></span> AlarmManager getAlarmManager<span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 51, 153);"><strong>Context</strong></span> ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(0, 153, 0);">{</span>
		<span style="color: rgb(0, 0, 0);"><strong>return</strong></span> <span style="color: rgb(0, 153, 0);">(</span>AlarmManager<span style="color: rgb(0, 153, 0);">)</span> ctx.<span style="color: rgb(0, 102, 51);">getSystemService</span><span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 51, 153);"><strong>Context</strong></span>.<span style="color: rgb(0, 102, 51);">ALARM_SERVICE</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	<span style="color: rgb(0, 153, 0);">}</span>
 
	<span style="color: rgb(0, 128, 0);"><strong><em>/**
	 * 指定时间后进行更新赛事信息(有如闹钟的设置)
	 * 注意: Receiver记得在manifest.xml中注册
         * 
	 * @param ctx
	 */</em></strong></span>
	<span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 0, 0);"><strong>static</strong></span> <span style="color: rgb(0, 102, 0);"><strong>void</strong></span> sendUpdateBroadcast<span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 51, 153);"><strong>Context</strong></span> ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(0, 153, 0);">{</span>
	    Log.<span style="color: rgb(0, 102, 51);">i</span><span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 0, 255);">"score"</span>, <span style="color: rgb(0, 0, 255);">"send to start update broadcase,delay time :"</span>+<span style="color: rgb(204, 102, 204);">60000</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
 
	    larmManager am = getAlarmManager<span style="color: rgb(0, 153, 0);">(</span>ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
            <span style="color: rgb(102, 102, 102);"><em>// 60秒后将产生广播,触发UpdateReceiver的执行,这个方法才是真正的更新数据的操作主要代码</em></span>
	    Intent i = <span style="color: rgb(0, 0, 0);"><strong>new</strong></span> Intent<span style="color: rgb(0, 153, 0);">(</span>ctx, UpdateReceiver.<span style="color: rgb(0, 0, 0);"><strong>class</strong></span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span> 
	    PendingIntent pendingIntent = PendingIntent.<span style="color: rgb(0, 102, 51);">getBroadcast</span><span style="color: rgb(0, 153, 0);">(</span>ctx, <span style="color: rgb(204, 102, 204);">0</span>, i, <span style="color: rgb(204, 102, 204);">0</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	    am.<span style="color: rgb(0, 102, 51);">set</span><span style="color: rgb(0, 153, 0);">(</span>AlarmManager.<span style="color: rgb(0, 102, 51);">RTC</span>, <span style="color: rgb(0, 51, 153);"><strong>System</strong></span>.<span style="color: rgb(0, 102, 51);">currentTimeMillis</span><span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 153, 0);">)</span>+<span style="color: rgb(204, 102, 204);">60000</span>, pendingIntent<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	<span style="color: rgb(0, 153, 0);">}</span>
 
 	<span style="color: rgb(0, 128, 0);"><strong><em>/**
	 * 取消定时执行(有如闹钟的取消)
	 * 
	 * @param ctx
	 */</em></strong></span>       
	<span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 0, 0);"><strong>static</strong></span> <span style="color: rgb(0, 102, 0);"><strong>void</strong></span> cancelUpdateBroadcast<span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 51, 153);"><strong>Context</strong></span> ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(0, 153, 0);">{</span>
	    AlarmManager am = getAlarmManager<span style="color: rgb(0, 153, 0);">(</span>ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	    Intent i = <span style="color: rgb(0, 0, 0);"><strong>new</strong></span> Intent<span style="color: rgb(0, 153, 0);">(</span>ctx, UpdateReceiver.<span style="color: rgb(0, 0, 0);"><strong>class</strong></span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	    PendingIntent pendingIntent = PendingIntent.<span style="color: rgb(0, 102, 51);">getBroadcast</span><span style="color: rgb(0, 153, 0);">(</span>ctx, <span style="color: rgb(204, 102, 204);">0</span>, i, <span style="color: rgb(204, 102, 204);">0</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	    am.<span style="color: rgb(0, 102, 51);">cancel</span><span style="color: rgb(0, 153, 0);">(</span>pendingIntent<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	<span style="color: rgb(0, 153, 0);">}</span>
<span style="color: rgb(0, 153, 0);">}</span>
 
<span style="color: rgb(102, 102, 102);"><em>// 更新数据库的广播接收器</em></span>
<span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 0, 0);"><strong>static</strong></span> <span style="color: rgb(0, 0, 0);"><strong>class</strong></span> UpdateReceiver <span style="color: rgb(0, 0, 0);"><strong>extends</strong></span> BroadcastReceiver<span style="color: rgb(0, 153, 0);">{</span>
        <span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 102, 0);"><strong>void</strong></span> onReceive<span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 51, 153);"><strong>Context</strong></span> context, Intent intent<span style="color: rgb(0, 153, 0);">)</span> <span style="color: rgb(0, 153, 0);">{</span>
             Toast.<span style="color: rgb(0, 102, 51);">makeText</span><span style="color: rgb(0, 153, 0);">(</span>context, <span style="color: rgb(0, 0, 255);">"更新比分数据"</span>, Toast.<span style="color: rgb(0, 102, 51);">LENGTH_LONG</span><span style="color: rgb(0, 153, 0);">)</span>.<span style="color: rgb(0, 102, 51);">show</span><span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
 
             <span style="color: rgb(102, 102, 102);"><em>// 设置全局定时器(闹钟) 60秒后再发广播通知本广播接收器触发执行.</em></span>
             <span style="color: rgb(102, 102, 102);"><em>// 这种方式很像JavaScript中的 setTimeout(xxx,60000)</em></span>
             AlarmManagerUtil.<span style="color: rgb(0, 102, 51);">sendUpdateBroadcast</span><span style="color: rgb(0, 153, 0);">(</span>context<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
        <span style="color: rgb(0, 153, 0);">}</span>
    <span style="color: rgb(0, 153, 0);">}</span>

(2)周期性的执行某项操作

<span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 0, 0);"><strong>static</strong></span> <span style="color: rgb(0, 102, 0);"><strong>void</strong></span> sendUpdateBroadcastRepeat<span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 51, 153);"><strong>Context</strong></span> ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(0, 153, 0);">{</span>
    Intent intent =<span style="color: rgb(0, 0, 0);"><strong>new</strong></span> Intent<span style="color: rgb(0, 153, 0);">(</span>ctx, UpdateReceiver.<span style="color: rgb(0, 0, 0);"><strong>class</strong></span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
    PendingIntent pendingIntent = PendingIntent.<span style="color: rgb(0, 102, 51);">getBroadcast</span><span style="color: rgb(0, 153, 0);">(</span>ctx, <span style="color: rgb(204, 102, 204);">0</span>, intent, <span style="color: rgb(204, 102, 204);">0</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
 
    <span style="color: rgb(102, 102, 102);"><em>//开始时间</em></span>
    <span style="color: rgb(0, 102, 0);"><strong>long</strong></span> firstime=SystemClock.<span style="color: rgb(0, 102, 51);">elapsedRealtime</span><span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
 
    AlarmManager am = <span style="color: rgb(0, 153, 0);">(</span>AlarmManager<span style="color: rgb(0, 153, 0);">)</span> ctx.<span style="color: rgb(0, 102, 51);">getSystemService</span><span style="color: rgb(0, 153, 0);">(</span>ALARM_SERVICE<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
  <span style="color: rgb(102, 102, 102);"><em>//60秒一个周期,不停的发送广播</em></span>
    am.<span style="color: rgb(0, 102, 51);">setRepeating</span><span style="color: rgb(0, 153, 0);">(</span>AlarmManager.<span style="color: rgb(0, 102, 51);">ELAPSED_REALTIME_WAKEUP</span>, firstime, <span style="color: rgb(204, 102, 204);">60</span><span style="color: rgb(51, 153, 51);">*</span><span style="color: rgb(204, 102, 204);">1000</span>, pendingIntent<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
<span style="color: rgb(0, 153, 0);">}</span>

取消定时器(闹钟)

 	<span style="color: rgb(0, 128, 0);"><strong><em>/**
	 * 取消定时执行(有如闹钟的取消)
	 * 
	 * @param ctx
	 */</em></strong></span>       
	<span style="color: rgb(0, 0, 0);"><strong>public</strong></span> <span style="color: rgb(0, 0, 0);"><strong>static</strong></span> <span style="color: rgb(0, 102, 0);"><strong>void</strong></span> cancelUpdateBroadcast<span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 51, 153);"><strong>Context</strong></span> ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(0, 153, 0);">{</span>
	    AlarmManager am = getAlarmManager<span style="color: rgb(0, 153, 0);">(</span>ctx<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
            <span style="color: rgb(102, 102, 102);"><em>// 取消时注意UpdateReceiver.class必须与设置时一致,这样才要正确取消</em></span>
	    Intent i = <span style="color: rgb(0, 0, 0);"><strong>new</strong></span> Intent<span style="color: rgb(0, 153, 0);">(</span>ctx, UpdateReceiver.<span style="color: rgb(0, 0, 0);"><strong>class</strong></span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>  
	    PendingIntent pendingIntent = PendingIntent.<span style="color: rgb(0, 102, 51);">getBroadcast</span><span style="color: rgb(0, 153, 0);">(</span>ctx, <span style="color: rgb(204, 102, 204);">0</span>, i, <span style="color: rgb(204, 102, 204);">0</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	    am.<span style="color: rgb(0, 102, 51);">cancel</span><span style="color: rgb(0, 153, 0);">(</span>pendingIntent<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
	<span style="color: rgb(0, 153, 0);">}</span>
<span style="color: rgb(0, 153, 0);">}</span>

//------------------------------------自己-------------------------------------

总结:这里自己的需求就是,如果app没有打开,但是收到了推送的消息,需要启动程序。

启动程序之后,跳转到某个Activity去。

这个过程大概是,收到推送消息---判断app是否启动---没有启动,启动SplashActivity(欢迎界面)--->MainActivity(程序主界面)--->NewsActivity(最终想要启动的界面)。这里在MainActivity的onCreate方法中调用

<span style="font-size:18px;color:#ff6666;">void onCreate(){ 
......
Handler handler = new Handler();              
        Runnable runnable = new Runnable(){    
        @Override  
        public void run() {  
                        // TODO Auto-generated method stub               
                        // 在此处添加执行的代码  
<span>			</span>doSomeThing();
                        handler.removeCallbacks(this); //移除定时任务                                
               }                    
        };  
        handler.postDelayed(runnable, 50);// 打开定时器,50ms后执行runnable  
}</span>
注意:如果放到MainActivity的onResume()方法中,当MainActivity不可见了,再恢复到可见,又会调用此方法。


你可能感兴趣的:(android 定时任务的几种实现方式)