我编写了一个 Utilloader 类,它提供了一个从网络加载一些数据的加载器线程。在我的活动中,我启动了一个新的加载程序线程。然后线程通过 handler.post() 更新活动。
class MyActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
initUI();
UtilLoader.getInstance().load("url", new UtilLoad.OnLoadListener
{
public void onLoadSuccess(String response)
{
updateUI();
}
});
}
}
class UtilLoader
{
private Handler handler = new Handler();
private UtilLoader instance = new UtilLoader();
private ExecutorService executorService = Executors.newFixedThreadPool(3);
public interface OnLoadListener
{
public void onLoadSuccess(String response);
}
public UtilLoader getInstance()
{
return instance;
}
public load(String url, OnLoadListener onLoadListener)
{
executorService.submit(new Loader(url, onLoadListener));
}
public class Loader extends Runnable
{
private String url;
private OnLoadListener onLoadListener;
public Loader(String url, OnLoadListener onLoadListener)
{
this.url = url;
this.onLoadListener = onLoadListener;
}
public void run()
{
// LOAD DATA
handler.post(new Runnable() {
public void run() {
onLoadListener.onLoadSuccess(sb.toString());
}
});
}
}
}
这种活动更新方式是否会通过保留对活动的引用而导致内存泄漏?如果是,我必须如何更改它,所以没有内存泄漏?