Issue
In the following example if I declare an AsyncTask
android studio gives a warning so that I should define it static. According to the this great explanation we define it as a static class to make it possible for virtual machine to garbage collect the service.
But it appears that thread does not need to be static. Why is that? Is it just android studio that doesn't give a warning or thread behaves in a totally different way?
public class MyTrackingService extends Service {
class TrackingThread extends Thread {
private final Context cotext;
TrackingThread(Context context){
this.cotext = context;
}
@Override
public void run() {
super.run();
}
}
class TrackingTask extends AsyncTask<Void, Void, Void> {
private final Context context;
TrackingTask(Context context){
this.context = context;
}
@Override
protected Void doInBackground(Void... voids) {
return null;
}
}
}
Solution
In the following example if I declare an AsyncTask android studio gives a warning so that I should define it static
The Lint warning is over-aggressive. The need for it to be static
mostly comes with activities and fragments.
Of course, having an AsyncTask
in a Service
, as you do here, is pointless. You almost never want to do anything on the main application thread in a Service
, and the point of AsyncTask
is to do something on the main application thread when the task completes. Having an AsyncTask
without onPostUpdate()
is a code smell and indicates that you should be using something else, such as a regular thread.
Also note that while AsyncTask
is not officially deprecated, its use is has been frowned upon for the past few years.
But it appears that thread does not need to be static
It suffers from the same problems that AsyncTask
does. There just isn't a Lint warning for it.
Is it just android studio that doesn't give a warning
Correct.
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.