As the title says, I have created an alternative class to imitate AsyncTask class (deprecated) with Thread and Handler classes but i feel uncomfortable to use it.(the app works fine with my class) Can you guys tell me is it ok or not? I feel like there is nothing changed. The reason i want to stop using AsyncTask is memoryleak issue.
import android.os.Handler;
public class BackgroundTask
{
protected Handler localHandler;
protected Thread localThread;
public void execute()
{
this.localHandler = new Handler();
this.onPreExecute(); //onPreExecute Method
this.localThread = new Thread(new Runnable()
{
@Override
public void run()
{
BackgroundTask.this.doInBackground(); //doInBackground Method
BackgroundTask.this.localHandler.post(new Runnable()
{
@Override
public void run()
{
BackgroundTask.this.onPostExecute(); //onPostExecute Method
}
});
}
});
this.localThread.start();
}
public void cancel()
{
if(this.localThread.isAlive())
this.localThread.interrupt();
}
protected void onPreExecute()
{
}
protected void doInBackground()
{
}
protected void onPostExecute()
{
}
}
Example for use (I can interrupt the Thread when i want so this must be solving the leak issue but i want this code to be seen by some other programmers too.)
public class HttpPostUserScore extends BackgroundTask
{
private final Context context;
private Exception taskException;
private final String point;
public HttpPostUserScore(Context context, String point)
{
this.context = context;
this.point = point;
}
@Override
protected void doInBackground()
{
try
{
OkHttpClient client = new OkHttpClient();
FormBody.Builder formBuilder = new FormBody.Builder();
formBuilder.add("token", User.loggedUser.getToken());
formBuilder.add("score", this.point);
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder().url(this.context.getString(R.string.user_score_api_url_body)).post(requestBody).build();
Response response = client.newCall(request).execute();
Log.println(Log.WARN, "ScorePost Response", response.body().string());
}
catch (Exception e) { this.taskException = e; }
}
@Override
protected void onPostExecute()
{
if(this.taskException != null)
Log.println(Log.ERROR, "ScorePost Error", this.taskException.getMessage());
else
Toast.makeText(this.context, this.point + " Points Added!", Toast.LENGTH_LONG).show();
}
}
I have examined some codes from Facebook's android login api. They are still using AsyncTask for asynchronous programming. Is it a big deal or not?