Talking about a way to use Android AsyncTask memory security

  • 2021-10-11 19:39:33
  • OfStack

Problem

Inner classes and inner anonymous classes can lead to memory leaks, so asynchronous code is often written a lot. After that, I was thinking about how to write asynchronous code. How is the standard writing? How to write concisely.

Train of thought

A weakly referenced interface is used as a bridge between the main thread and the sub-thread.

Code

WeakTask.java


public class WeakTask<T> extends AsyncTask<Void, Void, T> {

  private WeakReference<OnWeakTaskListener<T>> listenerReference;

  public WeakTask(OnWeakTaskListener<T> listener){
    this.listenerReference = new WeakReference<>(listener);
  }
  @Override
  protected T doInBackground(Void... voids) {
    if (listenerReference.get() != null) {
      return listenerReference.get().middle();
    }else{
      return null;
    }
  }

  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    if (listenerReference.get() != null) {
      listenerReference.get().before();
    }
  }

  @Override
  protected void onPostExecute(T t) {
    super.onPostExecute(t);
    if (listenerReference.get() != null && t != null){
      listenerReference.get().after(t);
    }
  }
}

OnWeakTaskListener


public interface OnWeakTaskListener<T> {

  void before();

  T middle();

  void after(T t);
}

Use-- > LoginActivity.java


public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    initLayout();
  }

  private void initLayout(){
    findViewById(R.id.btn_login).setOnClickListener(this);
  }

  @Override
  public void onClick(View view) {
    if (view.getId() == R.id.btn_login){
      new WeakTask<Integer>(new LoginWeakTaskListener()).execute();
    } 
  }


  private class LoginWeakTaskListener implements OnWeakTaskListener<Integer>{

    @Override
    public void before() {
       ... Before beginning 
    }

    @Override
    public Integer middle() {
       ... Internal execution 
    }

    @Override
    public void after(Integer integer) {
       ... Post-processing of result return 
    }
  }
}

Conclusion

In the past few days, I have been watching rxJava and thinking about why I want to learn rxJava. Of course, I feel that since it is euphemistically called observer mode, the main problem it should solve is to refresh the data displayed in the main thread with the data in the sub-thread. I have seen Android before, and it seems that the official mvvm uses rxJava, but I can't feel any advantage when I try to use rxJava. If there is time later, I will study the observer mode in depth, and then look at rxJava and rxAndroid. Recently, it is time for autumn recruitment, and I am faced with the problem of job hunting again. . .


Related articles: