I have a couple private AsyncTask methods that I'd like to break out into public external classes. In my application, I have a public class extending Application which holds some shared routines I want to access from different parts of my application. When I break out the AsyncTask class however, I'm no longer able to call getApplicationContext() to get a reference to my application library (the class does not inherit anything from Activity now). getBaseContext() will have problems as well. Should I be passing a context into the AsyncTask when it gets instantiated and build from there? Not sure if that was safe or not.
import java.util.ArrayList;
import android.os.AsyncTask;
public class DlTask extends AsyncTask
{
long totalbytes = 0;
long totalread = 0;
ArrayList <String> data;
@Override
protected void onPreExecute ()
{
AppLib lib = (AppLib) getApplicationContext();
lib.saveStatusText ("Contacting " + lib.getServerAddress () + ":" + lib.getServerPort () + "...");
super.onPreExecute ();
}
@Override
protected Object doInBackground (Object... params)
{
data = lib.sendCommand (CMD_LIST);
return true;
}
@Override
protected void onPostExecute (Object result)
{
if (data != null)
{
lib.saveStatusText (data.size () + " files found");
}
else
{
Log.d (TAG, "data is null");
Toast.makeText (getBaseContext(), msg, Toast.LENGTH_SHORT).show ();
}
super.onPostExecute(result);
}
}
This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext().
getContext() : Returns the context the view is currently running in. Usually the currently active Activity. Activity. getApplicationContext() : Returns the context for the entire application (the process all the Activities are running inside of).
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
AsyncTask instances can only be used one time.
Should I be passing a context into the AsyncTask when it gets instantiated and build from there?
You do not have a choice, as you will be unable to get a Context
by any other means.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With