I have this code example below and i want to make sure that no memory will happen. By passing the whole activity to an async task will lead to a memory leak if the task itself will have a bigger lifecycle than activity's. But if i declare a weakReference, means that if a rotation is about to happen, the activity will be destroyed without memory leak. Am right guys? Do i have to set something to null also?
Main .java
public class Main extends Activity {
private TextView mMessageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView();
new Background(this /*getBaseContext()*/ ).execute();
}
}
Background.java
public class Background extends AsyncTask<String, Void, String>
{
private WeakReference activity;
public void Background(Activity act)
{
activity = new WeakReference(act);
}
@Override
protected String doInBackground(String... params)
{
}
@Override
protected void onPostExecute(String result)
{
if(activity.get()!=null)
//ToDo
}
}
There is no need for explicit nulling when using WeakReference. Regarding the use of AsyncTask inside an Activity, just be careful not to create an anonymous instance because it will have an implicit reference to the enclosing class which can lead to memory leaks.
The code you posted seems ok, don't forget to terminate the AsyncTask gracefully when the activity is recreated.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments