单例
public class AppManager {
//有内存泄漏的问题:
// private static AppManager instance;
// private Context context;
// private AppManager(Context context) {
// this.context = context;
// }
// public static AppManager getInstance(Context context) {
// if (instance == null) {
//传入的Activity回收时由于被单例持有无法回收
// instance = new AppManager(context);
// }
// return instance;
// }
// 修复内存泄漏的写法:
private static AppManager instance;
private Context context;
private AppManager(Context context) {
this.context = context.getApplicationContext();// 使用Application 的context
}
public static AppManager getInstance(Context context) {
if (instance == null) {
instance = new AppManager(context);
}
return instance;
}
}
匿名内部类handler
public class MainActivity extends AppCompatActivity {
//容易造成内存泄漏的写法:
//非静态内部类
// private Handler mHandler = new Handler() {
// @Override
// public void handleMessage(Message msg) {
// //...
// }
// };
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// loadData();
// }
//
// private void loadData() {
// //...request
// Message message = Message.obtain();
// mHandler.sendMessage(message);
// }
//
// static class TestResource {
//该静态实例持有activity的引用,内存资源得不到正常回收,应该设为静态内部类
// private static final String TAG = "";
// //...
// }
// 修复内存泄漏的方法:
//1.设为静态内部类2.在handler内部持有外部类Activity的弱引用
private MyHandler mHandler = new MyHandler(this);
private TextView mTextView ;
private static class MyHandler extends Handler {
private WeakReference<Context> reference;
public MyHandler(Context context) {
reference = new WeakReference<>(context);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = (MainActivity) reference.get();
if(activity != null){
// activity.mTextView.setText("");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
}
private void loadData() {
//...request
Message message = Message.obtain();
mHandler.sendMessage(message);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
}