I was reading the book "Professional Android" and they say the following regarding AsyncTask
:
It's important to note that Async Tasks have no built-in understanding of the life cycle of the components they're running with. This means that if you are creating an
Async Task
in anActivity
, to avoid memory leaks you should define it as static (and ensure it doesn't hold a strong reference to anActivity
or itsViews
).
To test Async Task
I wrote the following code that should reverse a string in the background and show the string being built gradually by updating a TextView
. Am I using strong reference here?
package com.example.leo.test01;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TextView textView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_reversed_string);
new reverseStringAsync(textView).execute("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
private static class reverseStringAsync extends AsyncTask<String, String, String> {
private TextView textView;
reverseStringAsync(TextView textView) {
this.textView = textView;
}
@Override
protected void onPreExecute() {
Log.d(TAG, "onPreExecute()");
textView.setText("");
}
@Override
protected String doInBackground(String... strings) {
Log.d(TAG, "doInBackground()");
int n = strings[0].length();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; i <= n; i++) {
stringBuilder.append(strings[0].charAt(n - i));
publishProgress(stringBuilder.toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
@Override
protected void onProgressUpdate(String... values) {
Log.d(TAG, "onProgressUpdate()");
textView.setText(values[0]);
}
@Override
protected void onPostExecute(String s) {
Log.d(TAG, "onPostExecute()");
textView.setText(s);
}
}
}