Here is a sample code which make me a little missing:
package com.leak; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; public class WindowLeakActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new LeakThread().execute(); } class LeakThread extends AsyncTask<Void, Void,Void>{ ProgressDialog dialog; @Override protected void onPreExecute() { dialog=new ProgressDialog(WindowLeakActivity.this); dialog.show(); } @Override protected Void doInBackground(Void... params) { try { Thread.sleep(2000); finish(); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { //that would be ok if(WindowLeakActivity.this!=null && !WindowLeakActivity.this.isFinishing()) dialog.dismiss(); } }}
As you see,I create a LeakThread and finish the WindowLeakActivity at doInBackground()method.
In order to prevent window leak error,I have to check if the Activity has been finished at onPostExecute()method.That make me a little missing.I have following questions:
- Is do Activity instance isFinish() check at onPostExecute safe?If my Thread class is not a inner class of Activity.Do I have to check Activity instance is not null at first?
- When would Activity instance die?As Activity's lifecycle description,it will terminal when callback call onDestroy().But however,the Activity's Thread is still going.Though it's window been not visible,I can also get it's instance.
- If I call the System.gc().Will it collect Activity's instance?
Sorry for my bad description.Thank you for reading my question very much.