Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask doInBackground parameters vs constructor parameters

Tags:

android

Inside doInBackground I need to refer to application context or an activity.

Is there any difference between new MyAsyncTask(getApplicationContext()) and doInBackground(Context... params) in terms of thread safety and other possible multi-thread concepts, restrictions ?

Thanks.

like image 961
midnight Avatar asked Oct 11 '12 08:10

midnight


1 Answers

No. Assuming you have something like:

private class MyAsyncTask extends AsyncTask<Context, Integer, Long> {
  private Context _context = null;

  MyAsyncTask(Context context) {
    _context = context;
  }

  protected Long doInBackground(Context... context) {
     // if _context and context are the same, it doesn't matter
     // which you use.
     return 0;
  }

  protected void onProgressUpdate(Integer... progress) {
    // update progress
  }

  protected void onPostExecute(Long result) {
    // publish result
  }
}

Then there are no inherent issues regarding multi-threading wrt the Context itself.

Context useMe = getApplicationContext();
MyAsyncTask task = new MyAsyncTask(useMe);
task.execute(useMe); // should use this if provided, otherwise, what was in constructor
like image 151
GNewc Avatar answered Nov 15 '22 11:11

GNewc