我有一个共享对象,它在 Application 对象中进行实例化,并且我想从对服务器的调用中设置其值。但是当对象在异步任务 onPostExecute 中被引用时,我认为我引用的对象在异步任务之外没有改变。
这是我的简化代码:
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);
}
“临时用户 ID”和“当前用户 ID”的日志输出是我期望从 AsyncTask 内部调用它们时的输出。但是从另一个 Activity 调用它们是空的。另一方面,像 examplePlayer 这样实例化的对象在所有其他活动中保留其值。这是为什么?以及如何在 AsyncTask 内部进行更改以在外部进行更改?
即使在我让调用类实现回调接口之后,问题仍然存在。