检查倒计时到运行与否?

时间:2016-05-30 18:51:24

标签: java android timer countdowntimer

我有计时器,我可以设置我的计时器响铃。 我还有一个暂停按钮来停止计时器。 当你第一次访问应用程序时,因为没有计时器暂停。 当你点击暂停按钮我得到了错误。  这是我的计时器:

long result = date2.getTime() - date1.getTime();

                        timer = new CountDownTimer(result, 1000) {


                            public void onTick(long millisUntilFinished) {
                                time.setText(("seconds remaining: " + millisUntilFinished / 1000));
                                //create HashMap<Integer,String> textMap at the constructer of the adapter
                                //now fill this info int'o it
                                textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
                                //notify about the data change
                                notifyDataSetChanged();

                            }

                            public void onFinish() {

                                time.setVisibility(View.INVISIBLE);
                                //create HashMap<Integer,String> textMap at the constructer of the adapter
                                //now fill this info into it

                                textMap.put(new Integer(position),null);
                                //notify about the data change
                                notifyDataSetChanged();
                                Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
                                if (rowView != lastview || mediaPlayer == null) {
                                    play(position);
                                    if (lastview != null)
                                        lastview = rowView;
                                } else {
                                    play.setImageResource(R.drawable.n_btn_play_unselected);
                                    mediaPlayer.release();
                                    lastview = null;
                                }


                            }

                        }.start();
                        deleteDialog.dismiss();
                    }
                });

这是我的暂停按钮:

      stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                time.setVisibility(View.INVISIBLE);
                //create HashMap<Integer,String> textMap at the constructer of the adapter
                //now fill this info into it
              int  position=0;
                textMap.put(new Integer(position),null);
                //notify about the data change
                notifyDataSetChanged();

                    timer.cancel();


            }            });

如何让我的时间运转? 点击它时我得到了nullpointexecption。

1 个答案:

答案 0 :(得分:0)

检查它是否正在运行:

if(timer != null){
    //Here the timer will be running
}

但是,当您取消时,您必须执行以下操作:

timer.cancel();
timer = null;

因此,如果计时器不为null,则意味着它正在运行。如果为null则表示用户已取消它。