如何避免Asyntask中的内存泄漏?

时间:2018-08-31 07:20:08

标签: android android-asynctask

下面是我的测试代码。我让线程故意睡觉。我试图模拟繁重的IO任务。 我试图使用静态内部类。并且还使用了WeakReference。我想我必须错过一些非常重要的部分。活动结束后,我测试代码仍在泄漏。谁能提供一些提示?谢谢。

public class Main2Activity extends AppCompatActivity {
TextView textView;

MyAsyn myAsyn;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    textView=findViewById(R.id.test_view);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           finish();
        }
    });

    myAsyn=new MyAsyn(textView);
    myAsyn.execute();

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (myAsyn!=null){
        myAsyn.cancel(true);
    }
}
static class MyAsyn extends AsyncTask {

    WeakReference<TextView> textViewWeakReference;


    public MyAsyn(TextView textView) {
        this.textViewWeakReference = new WeakReference<>(textView);
    }

    @Override
    protected Object doInBackground(Object[] objects) {
        t(textViewWeakReference);

        try {
            Thread.sleep(10000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
       TextView textView= textViewWeakReference.get();
       if (textView!=null) {
           textView.setText("DONE");
       }
    }
}



public  static  void t( WeakReference<TextView> textViewWeakReference){

    final TextView textView=textViewWeakReference.get();

    new Thread(){
        @Override
        public void run() {
            super.run();
            try {
                Thread.sleep(500000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (textView!=null) {
                String a = textView.getText().toString();

                String b = a + a;
            }

        }
    }.run();
}

}

0 个答案:

没有答案