Android之延时操作方法

整理常见的延时处理方法,作为记录。

1、Handler.postDelayed()

适合在主线程更新UI操作,不会阻塞线程

 Handler handler = new Handler(); // 如果这个handler是在UI线程中创建的
 handler.postDelayed(new Runnable() {  // 开启的runnable也会在这个handler所依附线程中运行,即主线程
	 @Override
	 public void run() {
		 // 可更新UI或做其他事情
		 // 注意这里还在当前线程,没有开启新的线程
		 // new Runnable(){},只是把Runnable对象以Message形式post到UI线程里的Looper中执行,并没有新开线程。
	 }
 }, 3000); // 延时3s执行run内代码

2、Handler.sendEmptyMessage()

 final int MSG_WHAT = 1;
 Handler handler = new Handler() {
     @Override
     public void handleMessage(Message message) {
         switch(message.what) {
             case MSG_WHAT:
                 // 更新UI
                 break;
         }
     }
 };
 // 延时3s执行MSG_WHAT
 handler.sendEmptyMessageDelayed(MSG_WHAT, 3000);

3、Thread.sleep()

Thread.sleep()会使当前线程阻塞,建议创建新线程做延时操作

new Thread(new Runnable() {
	@Override
	public void run() {
		try {
	   		Thread.sleep(3000);
	   		// 3s后会执行的操作
		} catch (InterruptedException e) {
			 e.printStackTrace();
		}
	}
}).start();

4、TimerTask

 TimerTask task = new TimerTask() {
   @Override
     public void run() {
       // 要执行的操作
     }
 };
 Timer timer = new Timer();
 timer.schedule(task, 3000); // 延时3s 执行TimeTask的run方法

5、AlarmManager.setRepeating()

适合需要一直在后台运行的定时任务,比如每隔5分钟就做一件事,在应用保活情况下,延时是精准的。

概念
Intent是立刻执行的, PendingIntent不是立刻执行的。
getBroadcast(Context, int, Intent, int) 发送一个广播组件
getService(Context, int, Intent, int) 启动一个服务组件

代码释义:从当前时间开始设置闹钟去启动TestIntentService服务,执行其action为ACTION_TEST的内容,设定每隔1分钟执行一次。

 Intent intent = new Intent(context, TestIntentService.class); 
 intent.setAction(TestIntentService.ACTION_TEST);
 PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
 AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,      // 使用手机系统设置的时间
		System.currentTimeMillis(),      // 表示任务首次执行的时间
		60*1000,                        // 1min后再次执行任务
		pendingIntent);

 public static class TestIntentService extends IntentService {
    protected static final String ACTION_TEST= "action_test";
    public TestIntentService () {
        super("TestIntentService ");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
     	String action = intent.getAction();
    	switch (action) {
    		case ACTION_TEST:
    			...
    			break;
    	}
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值