在这里给大家提供一种在指定时间执行任务的代码,代码很简单,这里使用的是Timer来实现的,具体看代码吧
public class MainActivity extends Activity {
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
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(1);
}
};
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(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
}