好的,所以我已经阅读了许多关于处理程序的教程和线程,但是他们似乎对我自己的处理程序知识更加先进,这是我第一次使用处理程序这么光顾我。我在处理程序上有这个示例应用程序,它在某个时间触发Log,但是当我点击我的开始按钮时它似乎无法正常工作。以下是我的代码。
public class Main extends Activity {
private long selectedTimeInMills;
private Handler handler;
private static final Calendar CALENDAR = Calendar.getInstance();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimePicker timepicker = (TimePicker) findViewById(R.id.timePicker1);
final TextView timeText = (TextView) findViewById(R.id.time);
Button start = (Button) findViewById(R.id.button1);
handler = new Handler();
String textTime = formatDate(CALENDAR.getTimeInMillis(), "hh:mm a");
timeText.setText(textTime);
timepicker.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
CALENDAR.set(Calendar.HOUR_OF_DAY, hourOfDay);
CALENDAR.set(Calendar.MINUTE, minute);
selectedTimeInMills = CALENDAR.getTimeInMillis();
String textTime = formatDate(CALENDAR.getTimeInMillis(), "hh:mm a");
timeText.setText(textTime);
}
});
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Runnable runnable = new Runnable() {
public void run() {
Log.d("HandlerCheck", "Handler Fired! @ ("+selectedTimeInMills+") "+formatDate(selectedTimeInMills, "hh:mm a"));
}
};
boolean flag = handler.postAtTime(runnable, selectedTimeInMills);
Toast.makeText(Main.this, "Handler is Fired?:: "+flag, Toast.LENGTH_LONG).show();
}
});
}
}
注意:当我点击我的按钮并实现handler.postAtTime()
它返回true
但仍然不会显示登录DDMS,即使我已经设置了我的时间戳1分钟当前时间仍然不会触发DDMS上的日志消息
答案 0 :(得分:5)
Handler
类中的 postAtTime
方法占用了来自statup的时间,以毫秒为单位;不是Calendar
时间(这是你要经过的)。您应该使用SystemClock.uptimeMillis()
来计算时间。
或者,您可以使用postDelayed
函数在设定的时间段(以毫秒为单位)后调用Runnable对象。
// Introduce a new private variable
private long delayedTimeInMillis;
// Update delayedTimeInMillis inside onTimeChanged method:
delayedTimeInMillis = selectedTimeInMills - Calendar.getInstance().getTimeInMillis();
// replace handler.postAtTime(runnable, selectedTimeInMills); line with this:
handler.postDelayed(runnable, delayedTimeInMillis)