Issue
I am getting the following lint warning:
This AsyncTask class should be static or leaks might occur
Calling Class
private static Helper.GetRadar mTask;
private void setRadar(String area, String distance, String radar) {
**/// LINT WARNING ON THE BELOW LINE**
mTask = new Helper.GetRadar(activity, area, distance, radar) {
@Override
protected void onPostExecute(String result) {
gotRadar(result);
}
};
}
Inner Static Async Task:
class Helper {
....
public static class GetRadar extends AsyncTask<String, Void, String> {
private WeakReference<Context> mContext;
GetRadar(Context context, String area, String distance, String radar) {
mContext = new WeakReference<Context>(context);
}
@Override
protected String doInBackground(String... arg) {
....
return result;
}
@Override
protected void onPostExecute(String result) {
/// Override
}
}
}
Why am I getting this error when the class is already declared static?
Solution
You are extending the static class with an anonymous inner class, which will hold a reference to the calling activity, which is why you are getting that warning. You could create your own custom interface to call in onPostExecute
, like this:
public static class GetRadar extends AsyncTask<String, Void, String> {
private WeakReference<Context> mContext;
private MyPostExecute mRunner;
interface MyPostExecute {
void run(String result);
}
GetRadar(Context context, String area, String distance, String radar, MyPostExecute runner) {
mContext = new WeakReference<Context>(context);
mRunner = runner;
}
@Override
protected String doInBackground(String... arg) {
....
return result;
}
@Override
protected void onPostExecute(String result) {
mRunner.run(result);
}
}
Each class that wants to use the AsyncTask can define its own PostExecute implementation, like this:
private static MyRunner implements GetRadar.MyPostExecute {
private WeakReference<Helper> mHelper;
MyRunner(Helper h) {
mHelper = new WeakReference<>(h);
}
@Override
void run(String result)
{
Helper h = mHelper.get();
if( h != null && !h.isFinishing() ) {
h.gotRadar(result);
}
}
}
Then for this case, you would call it with:
mTask = new Helper.GetRadar(activity, area, distance, radar, new MyRunner(this));
Answered By - Tyler V
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.