开发者

Handler.postdelayed

开发者 https://www.devze.com 2023-03-06 02:21 出处:网络
I am using handler.postDelayed method to create some delay for some animation stuff. With that i am playing some song as well using Mediaplayer. User can exit this action class by clicking next. But

I am using handler.postDelayed method to create some delay for some animation stuff.

With that i am playing some song as well using Mediaplayer. User can exit this action class by clicking next. But on next screen the same song is continuing even though i called stop method in the next button's onclicklistener.

Is it due to the time开发者_Go百科delay that is added which gets executed after the next activity is loaded. Any idea?

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


Did you add a Log to see if run() gets called? I would assume that your handler gets unregistered; after all, postDelayed will wait until the looper kicks in again.

I assume your animation is faster than those 2000ms? You wouldn't be able to have your handler called anyway after your activity is gone, it's accessing imageView1 which I presume is destroyed in onDestroy.

You could consider adding a flag that will force the operation to be called immediately in onDestroy, and/or you could use a Timer. In case of the timer, be sure to not use something like imageView1 after it has been destroyed.


Use threads. And then stop it with an interruption:

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();
       }
    };
  };
}

Or you can use use the postDelayed function

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();
       }
    };
  };
}

you will find that there's a little difference between this two methods. To interrupt it, do something like this:

  Thread t = getThread(handle, delay);
  t.start();
  if(t != null)
  {
   if (t.isAlive())
   {
     t.interrupt();
   }
 }

Hope I have helped.

0

精彩评论

暂无评论...
验证码 换一张
取 消