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 初始化广播接收者

 <receiver
        android:name=".receiver.ClockReceiver"
        android:enabled="true"
        android:exported="true"
        tools:ignore="ExportedReceiver" >
        <intent-filter>
            <action android:name="com.heykel.BlockReceiver" />
        </intent-filter>
 </receiver>

java 获取广播执行操作

public class BlockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //excute the task
    }
}
    原文作者:Heykel
    原文地址: https://www.jianshu.com/p/6d0a11c580ae
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞