Issue
Activity starts AsyncTask and after it done, this task needs to check if this activity is destroyed and garbage collected. I thought that WeakReference help me to solve this question. But even if i rotate screen and activity is destroyed, i still not null. What i do wrong?
class MyAsyncTask extends AsyncTask<String,String,String> {
WeakReference<ActivitySecond> sactivity;
MyAsyncTask(ActivitySecond a)
{
sactivity = new WeakReference<>(a);
}
@Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(5000);
}
finally {
return "Ok";
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (sactivity!=null)
{
ActivitySecond activity = sactivity.get();
if (activity!=null)
Toast.makeText(activity,s,Toast.LENGTH_LONG).show();
}
}
}
Solution
If there is no other reference to the object apart from the weak reference, the object is allowed to be garbage collected.
But no guarantee is made when this is actually done.
Answered By - pveentjer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.