How to pause / sleep thread or process in Android?

后端 未结 12 874
故里飘歌
故里飘歌 2020-11-22 05:49

I want to make a pause between two lines of code, Let me explain a bit:

-> the user clicks a button (a card in fact) and I show it by changing the background of thi

相关标签:
12条回答
  • 2020-11-22 06:28

    One solution to this problem is to use the Handler.postDelayed() method. Some Google training materials suggest the same solution.

    @Override
    public void onClick(View v) {
        my_button.setBackgroundResource(R.drawable.icon);
    
        Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() {
             @Override 
             public void run() { 
                  my_button.setBackgroundResource(R.drawable.defaultcard); 
             } 
        }, 2000); 
    }
    

    However, some have pointed out that the solution above causes a memory leak because it uses a non-static inner and anonymous class which implicitly holds a reference to its outer class, the activity. This is a problem when the activity context is garbage collected.

    A more complex solution that avoids the memory leak subclasses the Handler and Runnable with static inner classes inside the activity since static inner classes do not hold an implicit reference to their outer class:

    private static class MyHandler extends Handler {}
    private final MyHandler mHandler = new MyHandler();
    
    public static class MyRunnable implements Runnable {
        private final WeakReference<Activity> mActivity;
    
        public MyRunnable(Activity activity) {
            mActivity = new WeakReference<>(activity);
        }
    
        @Override
        public void run() {
            Activity activity = mActivity.get();
            if (activity != null) {
                Button btn = (Button) activity.findViewById(R.id.button);
                btn.setBackgroundResource(R.drawable.defaultcard);
            }
        }
    }
    
    private MyRunnable mRunnable = new MyRunnable(this);
    
    public void onClick(View view) {
        my_button.setBackgroundResource(R.drawable.icon);
    
        // Execute the Runnable in 2 seconds
        mHandler.postDelayed(mRunnable, 2000);
    }
    

    Note that the Runnable uses a WeakReference to the Activity, which is necessary in a static class that needs access to the UI.

    0 讨论(0)
  • 2020-11-22 06:30
      class MyActivity{
        private final Handler handler = new Handler();
        private Runnable yourRunnable;
        protected void onCreate(@Nullable Bundle savedInstanceState) {
           // ....
           this.yourRunnable = new Runnable() {
                   @Override
                   public void run() {
                       //code
                   }
                };
    
            this.handler.postDelayed(this.yourRunnable, 2000);
           }
    
    
         @Override
      protected void onDestroy() {
          // to avoid memory leaks
          this.handler.removeCallbacks(this.yourRunnable);
          }
        }
    

    And to be double sure you can be combined it with the "static class" method as described in the tronman answer

    0 讨论(0)
  • 2020-11-22 06:32

    You can try this one it is short

    SystemClock.sleep(7000);
    

    WARNING: Never, ever, do this on a UI thread.

    Use this to sleep eg. background thread.


    Full solution for your problem will be: This is available API 1

    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View button) {
                    button.setBackgroundResource(R.drawable.avatar_dead);
                    final long changeTime = 1000L;
                    button.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            button.setBackgroundResource(R.drawable.avatar_small);
                        }
                    }, changeTime);
                }
            });
    

    Without creating tmp Handler. Also this solution is better than @tronman because we do not retain view by Handler. Also we don't have problem with Handler created at bad thread ;)

    Documentation

    public static void sleep (long ms)

    Added in API level 1

    Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long), but does not throw InterruptedException; interrupt() events are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.

    Parameters

    ms to sleep before returning, in milliseconds of uptime.

    Code for postDelayed from View class:

    /**
     * <p>Causes the Runnable to be added to the message queue, to be run
     * after the specified amount of time elapses.
     * The runnable will be run on the user interface thread.</p>
     *
     * @param action The Runnable that will be executed.
     * @param delayMillis The delay (in milliseconds) until the Runnable
     *        will be executed.
     *
     * @return true if the Runnable was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the Runnable will be processed --
     *         if the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     *
     * @see #post
     * @see #removeCallbacks
     */
    public boolean postDelayed(Runnable action, long delayMillis) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.postDelayed(action, delayMillis);
        }
        // Assume that post will succeed later
        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
        return true;
    }
    
    0 讨论(0)
  • 2020-11-22 06:34

    This is my example

    Create a Java Utils

        import android.app.ProgressDialog;
        import android.content.Context;
        import android.content.Intent;
    
        public class Utils {
    
            public static void showDummyWaitingDialog(final Context context, final Intent startingIntent) {
                // ...
                final ProgressDialog progressDialog = ProgressDialog.show(context, "Please wait...", "Loading data ...", true);
    
                new Thread() {
                    public void run() {
                        try{
                            // Do some work here
                            sleep(5000);
                        } catch (Exception e) {
                        }
                        // start next intent
                        new Thread() {
                            public void run() {
                            // Dismiss the Dialog 
                            progressDialog.dismiss();
                            // start selected activity
                            if ( startingIntent != null) context.startActivity(startingIntent);
                            }
                        }.start();
                    }
                }.start();  
    
            }
    
        }    
    
    0 讨论(0)
  • 2020-11-22 06:40

    This is what I did at the end of the day - works fine now :

    @Override
        public void onClick(View v) {
            my_button.setBackgroundResource(R.drawable.icon);
            // SLEEP 2 SECONDS HERE ...
            final Handler handler = new Handler(); 
            Timer t = new Timer(); 
            t.schedule(new TimerTask() { 
                    public void run() { 
                            handler.post(new Runnable() { 
                                    public void run() { 
                                     my_button.setBackgroundResource(R.drawable.defaultcard); 
                                    } 
                            }); 
                    } 
            }, 2000); 
        }
    
    0 讨论(0)
  • 2020-11-22 06:40

    In addition to Mr. Yankowsky's answers, you could also use postDelayed(). This is available on any View (e.g., your card) and takes a Runnable and a delay period. It executes the Runnable after that delay.

    0 讨论(0)
提交回复
热议问题