避免AsyncTask內存泄漏

避免AsyncTask內存泄漏的簡單例子:java

Activity代碼:android

public class MainActivity extends Activity {
  private MyAsyncTask task;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    task = new MyAsyncTask();
    task.setListener(createListener());
    task.execute();
  }
  @Override
  protected void onDestroy() {
    task.setListener(null);
    super.onDestroy();
  }
  private MyAsyncTask.Listener createListener() {
    return new MyAsyncTask.Listener() {
      @Override
      public void onSuccess(Object object) {
        // adapt contents
      }
    };
  }
}


這裏是AsyncTask:git

class MyAsyncTask extends AsyncTask {
  private Listener listener;
  @Override
  protected Object doInBackground(Object[] params) {
    return doSomeStuff();
  }
  private Object doSomeStuff() {
    //do something to get result
    return new Object();
  }
  @Override
  protected void onPostExecute(Object object) {
    if (listener != null) {
      listener.onSuccess(object);
    }
  }
  public void setListener(Listener listener) {
    this.listener = listener;
  }
  interface Listener {
    void onSuccess(Object object);
  }
}

總體思路:github

    經過註冊接口回調的方式,處理AsyncTask返回的數據。app

 

novoda/bonfire-firebase-sample
bonfire-firebase-sample - An app to discuss your favourite emojis. This is a sample app built with Firebase.github.com
ide

novoda/spikes
spikes - Where ideas & concepts are born & incubatedgithub.com
ui

防止內存泄漏的重要守則是讓內部類爲靜態的。尤爲是它們要作耗時的後臺任務的時候。或者更好的方法是把這個類移到外面做爲單獨的類。this

用非靜態的內部類作耗時的後臺任務老是很糟糕的實踐,不光是在安卓中。idea

相關文章
相關標籤/搜索