I am launching a activity, and once a user is logged in, i want to refresh the main activity. To load the data from the logged in user.
Such as the image and name. I have all of this set up already.
I just need to know is it possible to launch another activity and run its async task again.From an launching开发者_高级运维 an intent from inside another activity?
It's not clear what exactly your design is, but if you need to use the same AsyncTask from two different activities, it should be a separate class, not tied to a particular activity. You can have the two activities implement a common interface, so that the AsyncTask doesn't need to know which activity it is updating. Then instantiate the task by passing a reference to the enclosing activity, and start it as needed. There is no need for one activity to start the other.
Something like:
public interface UserActivity {
void updateUserData(UserData userData);
}
public class Activity1 implements UserActivity {
public void onStart() {
UpdateUserDataTask task = new UpdateUserDataTask(this);
task.execute();
}
public void updateUserData(UserData userData) {
// update
}
}
public class UpdateUserDataTask extends AsyncTask<Void, Void, UserData> {
UserActivity userActivity;
public UpdateUserDataTask(UserActivitiy userActivity) {
this.userActivity = userActivity;
}
// doInBackground, etc implementation.
protected void onPostExecute(UserData userData) {
userActivity.updateUserData(userData);
}
}
As far as I'm aware, AsyncTasks aren't supposed to be reused. They're supposed to be run once and then you can create a new one if you need it.
Once an AsyncTask
is executed once, you cannot execute it again. What you can do, though, is control it's "refresh" using onProgressUpdate()
and publishProgress()
as follows. Note that this will only work for a one-time refresh. If you wanted to be more semantically correct, you might do the "normal" operation in onProgressUpdate()
and use onPostExecute()
for your resfresh.
public class MyAsyncTask extends AsyncTask<Void, String, Void> {
private boolean isRefresh = false;
@Override
protected Void doInBackground(Void... arg0) {
while (!isRefresh){
//Perform your normal operation
}
//When isRefresh is true, you want to refresh.
this.publishProgress(values);
return null;
}
@Override
protected void onProgressUpdate(String... values) {
// Refresh code here
super.onProgressUpdate(values);
}
public void refreshTask(){
this.isRefresh = true;
}
}
You could then maintain a reference to the object of MyAsyncTask
and invoke refreshTask()
on it whenever you want to refresh it.
精彩评论