Android中如何延时执行操作

  • 1、最简单直接的使用Handler PostDelay

java

new Handler().postDelayed(new Runnable(){   
public void run() {   
    //execute the task   
    }   
 }, delaytime); 

*2、 开启一个新的线程

java

new Thread(new Runnable(){   
public void run(){   
    Thread.sleep(delaytime);   
    handler.sendMessage(); //execute the task
    }   
}).start    
  • 3、使用定时器

java

TimerTask task = new TimerTask(){   
public void run(){   
//execute the task 
  }   
};   
Timer timer = new Timer(); 
timer.schedule(task, delay); 
  • 4、使用AlarmManager实现精准定时任务

java 设定时间发送广播

Intent intent = new Intent("com.heykel.ClockReceiver");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,15);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1 * 1000, sender);

xml 初始化广播接收者

 
        
            
        
 

java 获取广播执行操作

public class BlockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //excute the task
    }
}

你可能感兴趣的:(Android中如何延时执行操作)