今天就跟大家聊聊有关Android中怎么利用Handler防止内存泄露,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
Handler可能导致的内存泄露及其优化
1 关于常见的Handler的用法但是可能导致内存泄露
2 优化方式请参考BetterHandler和BetterRunnable的实现
package cc.cc; import java.lang.ref.WeakReference; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; public class MainActivity extends Activity { private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } private void initHandler() { mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; // ......doing something // ......doing something // ......doing something // 发送延迟消息 mHandler.postDelayed(new Runnable() { @Override public void run() { } }, 1000 * 20); } private static class BetterHandler extends Handler{ private final WeakReference<Activity> activityWeakReference; public BetterHandler(Activity activity){ activityWeakReference=new WeakReference<Activity>(activity); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (activityWeakReference.get()!=null) { //.....handle message } else { System.out.println("Activity==null"); } } } //同样采用静态内部类 private static class BetterRunnable implements Runnable{ @Override public void run() { // ......doing something } } //发送延迟消息 private void sendMessage(){ BetterHandler betterHandler=new BetterHandler(MainActivity.this); betterHandler.postDelayed(new BetterRunnable(), 1000 * 20); } }
看完上述内容,你们对Android中怎么利用Handler防止内存泄露有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网行业资讯频道,感谢大家的支持。