2012-10-11 29 views
5

doInBackground內部我需要引用應用程序上下文或活動。AsyncTask doInBackground參數vs構造函數參數

在線程安全性和其他可能的多線程概念,限制方面,new MyAsyncTask(getApplicationContext())doInBackground(Context... params)之間是否有區別?

謝謝。

+0

請參閱http://developer.android.com/reference/android/os/AsyncTask.html –

+0

@拉胡爾,分辨 – midnight

回答

1

號假設你有這樣的:

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 
    } 
} 

再就是關於多線程WRT語境本身沒有內在的問題。

Context useMe = getApplicationContext(); 
MyAsyncTask task = new MyAsyncTask(useMe); 
task.execute(useMe); // should use this if provided, otherwise, what was in constructor