0

我只想扫描我的时间何时等于当前时间,并使用计时器,但是当单击复选框并且我的时间等于当前时间时......它会出现致命错误。还有其他解决方案吗?

        privae int currentHourOfDay,currentMinutes;
        private int mHourOfDay, mMinutes;
        .....

        chk1 = (CheckBox) findViewById(R.id.checkBox1);
        chk1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (chk1.isChecked()) {

                h = tv.getText().toString(); //get text from hours input
                m = tv2.getText().toString(); //get text from miutes input
                mHourOfDay = Integer.parseInt(h);
                mMinutes = Integer.parseInt(m);

                System.out.println(mHourOfDay);
                System.out.println(mMinutes);

                final Timer timer = new Timer();

                timer.schedule( new TimerTask() {
                    public void run() { 

                Calendar cal = Calendar.getInstance();
                currentHourOfDay = cal.get(Calendar.HOUR_OF_DAY);
                currentMinutes = cal.get(Calendar.MINUTE);

                System.out.println(currentHourOfDay);
                System.out.println(currentMinutes);

                Integer x = mHourOfDay;
                Integer y = currentHourOfDay;
                Integer x1 = mMinutes;
                Integer y1 = currentMinutes;

                if (x.equals(y) && x1.equals(y1)) {

                    Toast toast = Toast.makeText(getApplicationContext(),
                            "Now it equels!!", Toast.LENGTH_SHORT);
                    toast.show();
                    timer.cancel();

                } 
            }}, 0, 1000);


            } else {
                System.out.println("alarm is off");
            }
        }
    });

当我的时间等于当前时间时,我必须使用其他一些方法来解决我的任务做一些事件吗?

4

1 回答 1

0

在 UI 线程上更新 ui。在 ui 线程上显示 toast 消息。

只需在下面显示 toast 的位置添加以下内容。

      runOnUiThread(new Runnable() //update ui here
         {
          public void run() 
          {
         Toast.makeText(getApplicationContext(),
                        "Now it equels!!", Toast.LENGTH_SHORT).show();
          }
         });

定时器任务示例

_t.scheduleAtFixedRate( new TimerTask() {
    @Override
    public void run() {
         //do something
        runOnUiThread(new Runnable() //update ui here
         {
          public void run() 
          {
         //display toast here.
          }
         });
    }
}, 1000, 1000 );
于 2013-03-19T10:41:14.147 回答