Handler.postdelayed

I use the handler.postDelayed method to create some delay for some animated materials.

With this, I play some kind of song using Mediaplayer. The user can exit this action class by clicking next. But on the next screen, the same song continues, although I called the stop method in the next onclicklistener button.

This is due to the addition of timedelay, which starts after loading the next action. Any idea?

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

Have you added Logto find out if the call is called run()? I would suggest that your handler becomes unregistered; in the end, it postDelayedwill wait until the looper starts up again.

, , 2000 ? , , ​​ imageView1, , , onDestroy.

, onDestroy / Timer. - imageView1 .

+2

. :

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

, .

0

All Articles