gpt4 book ai didi

android - 实现处理程序的基本方式

转载 作者:行者123 更新时间:2023-11-29 15:26:22 25 4
gpt4 key购买 nike

我在处理程序上有这个示例应用程序,它在特定时间触发日志,但是当我单击开始按钮时它似乎不工作。下面是我的代码。

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 上触发日志消息

最佳答案

postAtTime Handler 类中的方法从状态开始获取时间(以毫秒为单位);不是 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)

关于android - 实现处理程序的基本方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12452478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com