Android 指定日期时间执行任务的Timer

时间:2021-08-20 03:52:32

放上一个指定详细日期及时间的timer

 public class MainActivity extends Activity {

     private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case :
Log.i("====","执行了");
//需要执行的代码放这里
break;
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); TimerTask task = new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage();
}
};
Timer timer = new Timer(true);
timer.schedule(task,strToDateLong("2016-06-14 15:33:30"));
} /**
* string类型时间转换为date
* @param strDate
* @return
*/
public static Date strToDateLong(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition();
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
}