Is this Runnable safe from memory leak?

前端 未结 4 838
野的像风
野的像风 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: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.

提交回复
热议问题