参考一
//错误的示范: //mHandler是匿名内部类的实例,会引用外部对象MainActivity.this。如果Handler在Activity退出的时候,它可能还活着,这时候就会一直持有Activity。 // private Handler mHandler = new Handler(){ // @Override // public void handleMessage(Message msg) { // super.handleMessage(msg); // switch (msg.what){ // case 0: // //加载数据 // break; // // } // } // }; //解决方案: private static class MyHandler extends Handler{ // private MainActivity mainActivity;//直接持有了一个外部类的强引用,会内存泄露 private WeakReference<MainActivity> mainActivity;//设置软引用保存,当内存一发生GC的时候就会回收。 public MyHandler(MainActivity mainActivity) { this.mainActivity = new WeakReference<MainActivity>(mainActivity); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); MainActivity main = mainActivity.get(); if(main==null||main.isFinishing()){ return; } switch (msg.what){ case 0: //加载数据 // MainActivity.this.a;//有时候确实会有这样的需求:需要引用外部类的资源。怎么办? int b = main.a; break; } } };
参考二 public class MainActivity extends Activity implements View.OnClickListener { public static final int UPDATE_TEXT = 1; private static TextView mtext; private Button mbutton; private final Myhander myhander = new Myhander(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mtext = findViewById(R.id.text); mbutton = findViewById(R.id.change_text); mbutton.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.change_text: new Thread(new Runnable() { @Override public void run() { String str = "你年龄:"; Message message = new Message(); message.what = UPDATE_TEXT; message.obj = str; message.arg1 = 1; message.arg2 = 8; myhander.sendMessage(message); } }).start(); break; } } private static class Myhander extends Handler { private final WeakReference<MainActivity> mainActivity; Myhander(MainActivity activity) { mainActivity = new WeakReference<>(activity); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); MainActivity activity = mainActivity.get(); if (activity != null) { switch (msg.what) { case UPDATE_TEXT: String mstring = (String) msg.obj; int age = msg.arg1; int age1 = msg.arg2; //这行代码有警告,不能应该这样写,我测试写法 mtext.setText(mstring + age + age1); break; } } } } }
详情信息:https://blog.csdn.net/wanghao200906/article/details/79305126
详情信息:
https://blog.csdn.net/weixin_41101173/article/details/79710782