Updating an Activity from an AsyncTask
So I'm an iOS developer learning android, and I'm having a difficult time understanding some things. Right now I have a datamanager class. In that class it has an AsyncTask to update the data. OnPreExecute I pop an activity to show it is updating. I understand I could use extras to pass initial information to the UpdateActivity. My problem is I'm not sure how to send new information in OnProgressUpdate. Here is my code widdled down:
private class myTask extends AsyncTask<Integer,String,Void>{
@Override
protected void onCancelled() {
super.onCancelled();
isUpdating = false;
}
@Override
protected Void doInBackground(Integer... params) {
//My BG Code
}
@Override
protected void 开发者_运维知识库onPostExecute(Void result) {
// TODO Remove updating view
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Intent myIntent = new Intent(mContext,UpdateActivity.class);
mContext.startActivity(myIntent);
}
}
AsyncTask is designed to work best when nested in an Activity class.
What makes AsyncTask 'special' is that it isn't just a worker thread - instead it combines a worker thread which processes the code in doInBackground(...)
with methods which run on the Activity's UI thread - onProgressUpdate(...)
and onPostExecute(...)
being the most commonly used.
By periodically calling updateProgress(...)
from doInBackground(...)
, the onProgressUpdate(...)
method is called allowing it to manipulate the Activity's UI elements (progress bar, text to show name of file being downloaded, etc etc).
In short, rather than firing your 'update' Activity from an AsyncTask, your update Activity itself should have a nested AsyncTask which it uses to process the update and publish progress to the UI.
You have two options:
1) Pass an instance of activity to your AsyncTask constructor in order to invoke some method on it:
new MyTask(this).execute();
So, you can do:
public MyTask (Activity activity) {
this.activity = activity;
}
public void onPostExecute(...) {
activity.someMethod();
}
2) Pass a Handler
instance and send message from onPostExecute() to the activity.
精彩评论