Handlers and memory leaks in Android

前端 未结 6 2143
攒了一身酷
攒了一身酷 2020-11-29 18:14

Please have a look at the code below:

public class MyGridFragment extends Fragment{

     Handler myhandler = new Handler() {
    @Override
    public void h         


        
6条回答
  •  忘掉有多难
    2020-11-29 18:37

    If you read docs about AccountManager or PendingIntent, you will see that some methods take Handler as one of arguments.

    For example:

    • onFinished - The object to call back on when the send has completed, or null for no callback.
    • handler - Handler identifying the thread on which the callback should happen. If null, the callback will happen from the thread pool of the process.

    Imagine the situation. Some Activity calls PendingIntent.send(...) and put the non-static inner subclass of Handler. And then activity is destroyed. But inner class lives.

    Inner class still holds a link to destroyed activity, it cannot be garbage-collected.

    If you're not planning to send your handler to such methods, you have nothing to worry about.

提交回复
热议问题