0


Android之延时操作方法

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

1、Handler.postDelayed()

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

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

2、Handler.sendEmptyMessage()

  1. final int MSG_WHAT = 1;
  2. Handler handler = new Handler() {
  3. @Override
  4. public void handleMessage(Message message) {
  5. switch(message.what) {
  6. case MSG_WHAT:
  7. // 更新UI
  8. break;
  9. }
  10. }
  11. };
  12. // 延时3s执行MSG_WHAT
  13. handler.sendEmptyMessageDelayed(MSG_WHAT, 3000);

3、Thread.sleep()

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

  1. new Thread() {
  2. @Override
  3. public void run() {
  4. Thread.sleep(3000);
  5. // 3s后会执行的操作
  6. }
  7. }.start();

4、TimerTask

  1. TimerTask task = new TimerTask() {
  2. @Override
  3. public void run() {
  4. // 要执行的操作
  5. }
  6. };
  7. Timer timer = new Timer();
  8. 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分钟执行一次。

  1. Intent intent = new Intent(context, TestIntentService.class);
  2. intent.setAction(TestIntentService.ACTION_TEST);
  3. PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  4. AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
  5. alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, // 使用手机系统设置的时间
  6. System.currentTimeMillis(), // 表示任务首次执行的时间
  7. 60*1000, // 1min后再次执行任务
  8. pendingIntent);
  1. public static class TestIntentService extends IntentService {
  2. protected static final String ACTION_TEST= "action_test";
  3. public TestIntentService () {
  4. super("TestIntentService ");
  5. }
  6. @Override
  7. protected void onHandleIntent(Intent intent) {
  8. String action = intent.getAction();
  9. switch (action) {
  10. case ACTION_TEST:
  11. ...
  12. break;
  13. }
  14. }
  15. }
标签: android ui java

本文转载自: https://blog.csdn.net/JoesaCSDN/article/details/123111330
版权归原作者 Joesacsdn 所有, 如有侵权,请联系我们删除。

“Android之延时操作方法”的评论:

还没有评论