Handler.postdelayed

3

我正在使用handler.postDelayed方法来为一些动画效果创建一些延迟。

同时,我也在使用Mediaplayer播放一些音乐。用户可以通过点击“下一个”退出此操作类。但是在下一个屏幕上,即使我在下一个按钮的onclicklistener中调用了stop方法,同一首歌曲仍在继续播放。

这是由于添加的定时延迟在加载下一个活动后执行导致的吗?有什么想法吗?

handler.postDelayed(new Runnable() {
        public void run() {
            mp = MediaPlayer.create(getApplicationContext(), R.raw.num2);
            mp.start();
            imageView1.setImageResource(R.drawable.countcat2);
        }
    }, 2000);
2个回答

2
您是否添加了Log以查看是否调用了run()?我会假设您的处理程序已注销;毕竟,postDelayed将等待循环器再次启动。
我假设您的动画速度比这2000毫秒更快?在您的活动消失后,您将无法调用处理程序,它正在访问imageView1,我假设onDestroy中已被销毁。
您可以考虑添加一个标志,它将在onDestroy中强制立即调用该操作,和/或者您可以使用Timer。在计时器的情况下,请确保在其被销毁后不要使用诸如imageView1之类的东西。

糟糕!flag 很简单。我感到非常尴尬。谢谢 :) - nasaa

0

使用线程。然后通过中断停止它:

Public Thread getThread(final Handler handle, int delay)
{
  return new Thread() 
  {
    @Override
    public void run() 
    {
      try
      {
         synchronized(this) 
         {
           Thread.sleep(delay);     
           handle.post(new Runnable() 
           {    
             @Override
             public void run() 
             {      
               "the code to be exec."
             }
           });

         }    
     }
       catch(Exception e)
       {
    e.printStackTrace();
       }
    };
  };
}

或者你可以使用postDelayed函数

Public Thread getThread(final Handler handle, int delay)
{
  return new Thread() 
  {
    @Override
    public void run() 
    {
      try
      {
         synchronized(this) 
         {  
           handle.postDelayed(new Runnable() 
           {    
             @Override
             public void run() 
             {      
               "the code to be exec."
             }
           }, delay);

         }    
     }
       catch(Exception e)
       {
    e.printStackTrace();
       }
    };
  };
}

你会发现这两种方法之间有一点不同。为了中断它,可以这样做:
  Thread t = getThread(handle, delay);
  t.start();
  if(t != null)
  {
   if (t.isAlive())
   {
     t.interrupt();
   }
 }

希望我有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接