定时器被反复调用

时间:2013-07-01 12:45:30

标签: android timer timertask contentobserver

我正在开发一个Android应用程序,我想在按下音量减小按钮时启动计时器,并在按下音量增大按钮时停止计时器,并在音量调低时重新启动计时器,依此类推。

问题是,即使我清除并取消它,时间也不会停止。它不断循环。

请检查下面的代码,让我知道可能出错的地方。

    @Override
public void onChange(boolean selfChange) 
{
    super.onChange(selfChange);

    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

    int delta=initialVolume-currentVolume;

    //if down pressed
    if(delta>0)
    {
        Log.e("delta","down");
        downpress = "yes";
        downpressdonefirsttime = "yes";
        timer = new Timer();
    }

    //if up pressed
    else if(delta < 0)
    {
        Log.e("delta","up");
    }

    //if down + up pressed
    else if(delta == 0)
    {
        if(downpress.equalsIgnoreCase("yes"))
        {
            Log.e("inisde","delta is 0 , shake it!!");
        }
    }


    if(downpressdonefirsttime.equalsIgnoreCase("yes"))
    {
        if(downpress.equalsIgnoreCase("yes"))
        {
            timer.scheduleAtFixedRate(new TimerTask() 
            {

                @Override
                public void run() 
                {
                    time = ++time;


                    Log.e("inside","time run , time is" + time);

                    if(time <= 5)
                    {
                        Log.e("inside","time less than 5");
                        downpressdonefirsttime = "no";
                    }

                    if(time > 5)
                    {
                        Log.e("inside","time greater than 5");

                        downpress = "no";
                        time = 0;

                        timer.cancel();
                        timer.purge();
                    }

                }



            }, 0, 1000);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码段:

public boolean onKeyDown(int keyCode, KeyEvent event) { 
   if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { 
       // On Volume DOWN
       return true;
   }
else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP){
       // On Volume UP
       return true;
}
else {
       return super.onKeyDown(keyCode, event); 
}

通过这种方式,您可以确保按下这些按钮。如果问题仍然存在,那可能与按下按钮无关。 }