1

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

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

4

1 回答 1

5

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)
于 2012-09-17T03:39:57.403 回答