Is this Runnable safe from memory leak?

前端 未结 4 804
野的像风
野的像风 2021-01-18 05:58

I am a total beginner in Java and have created a simple Java Android snippet where in a Runnable after 1,5 seconds I change the TextView from Hello World<

相关标签:
4条回答
  • 2021-01-18 06:17

    Please do this, otherwise you will be blocking UIThread and it is not recommended. To do this, you can also use a TimerTask, check it here: http://developer.android.com/reference/java/util/TimerTask.html

    import android.widget.TextView;
    import android.util.Log;
    import java.lang.ref.WeakReference;
    
    public class HelloWorldActivity extends Activity
    {
        private Handler h = new Handler();
        private static TextView txtview;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            txtview = (TextView) findViewById(R.id.mainview);        
    
            h.postDelayed(new Runnable() {
               @Override
               public void run() {
                  changeText();
               }
            }, 1500);
        }
    
        public void changeText(){
           txtview.setText("Hola mundo.");
           h.removeCallbacksAndMessages(null);
        }          
    
    }
    

    By the way, you can change orientation in your emulator this way: Ctrl+F12

    0 讨论(0)
  • 2021-01-18 06:24

    h.postDelayed(new WeakRunnable(txtview),1500); I think it will be blocking UI Thread. here is a good sample for memory leak. https://github.com/badoo/android-weak-handler

    0 讨论(0)
  • 2021-01-18 06:25

    I think your code is leak free if you use :

    private static Handler h = new Handler(); 
    

    or

    txtview.postDelayed(new WeakRunnable(txtview),1500);
    

    because you have stored the view as a WeakReference. the method:

    txtview.postDelayed(new WeakRunnable(txtview),1500);
    

    simply call main handler of the UI thread so if the activity is destroyed the view is null and the runnable dose nothing.

    also because of the weakreference the activity can be garbage collected because there is no strong reference to it.

    0 讨论(0)
  • 2021-01-18 06:26

    I have a doubt if there's absolutely no memory leak whenever device orientation occurs.

    It could be. For 1.5seconds. After the queue is emptied the handler can be garbage collected, and also the old Activity. To be safe override onPause, and call handler.removeCallbacks(null); to clear the Handler's queue

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