我有一个共享对象,它在Application对象中实例化,我希望从调用服务器设置其值。但是当在异步任务onPostExecute中引用该对象时,我认为我引用的对象不会在asyncTask之外更改。
这是我的简化代码:
public class AwesomApplication extends Application implements OnTaskComplete {
public Player currentPlayer;
public Player examplePlayer;
public void onCreate() {
super.onCreate();
new getPlayerInfoAsync(this).execute(new Player("User", "Password"));
examplePlayer = new Player(Some values);
}
@Override
public void onTaskComplete(Player player){
this.currentPlayer = player;
}
private class getPlayerInfoAsync extends AsyncTask <Player, Integer, Player>
{
private OnTaskCompleted listener;
public getPlayerInfoAsync(OnTaskCompleted listener){
this.listener=listener;
}
@Override
protected Player doInBackground(Player... players) {
Player tmpPlayer = gameServer.getPlayerInfo(new Player(players[0].getUserName(), players[0].getPassword()));
Log.d(TAG, "Temp userID" + tmpPlayer.getUserID());
return tmpPlayer;
}
@Override
protected void onPostExecute(Player player) {
super.onPostExecute(player);
currentPlayer = player;
listener.onTaskComplete();
Log.d(TAG, "Current userID" + currentPlayer.getUserID());
}
}
}
我为Asynctask创建了一个接口,用作回调。
public interface OnTaskCompleted{
void onTaskCompleted(Player player);
}
“Temp userID”和“当前用户ID”的日志输出是我从AsyncTask内部调用时所期望的。但是从另一个Activity调用它们是null。另一方面,像examplePlayer一样实例化的对象会在所有其他活动中保留其值。这是为什么?如何在AsyncTask内部进行更改以便在外部进行更改?
即使我让调用类实现了一个回调接口,问题仍然存在。