我正在写游戏。当用户结束关卡时,会发生以下情况:
- 发送 POST,检查关卡记录是否被打破。(1-5 秒)
- 如果是这样,请显示
Dialog
“输入您的姓名”。(快速地) - 当用户单击确定时,发送一个带有他的记录的 POST。(1-5 秒)
当用户结束关卡时,他处于GameActivity
. checkWorldRecord()
被调用,并在其中AsyncTask
启动 an:
private void checkWorldRecord(final RecordType recordType, final double time, final int level)
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
new DownloadTask(recordType, time, level).execute();
}
});
}
DownloadTask
正在做这三件事,我在一开始就列出了:
class DownloadTask extends AsyncTask<Void, Void, Void>
{
RecordType recordType;
double time;
int level;
public DownloadTask(RecordType recordType, double time, int level)
{
super();
this.recordType = recordType;
this.time = time;
this.level = level;
}
@Override
protected Void doInBackground(Void... params)
{
try
{
if (!Network.isWorldRecord(recordType, time, level)) // 1.
{
return null;
}
}
catch (Exception e)
{
return null;
}
Dialogs.showEnterNameAndSend(GameActivity.this, recordType, time, level, highScores.getGamesPlayed(),
highScores.getStars()); // 2.
return null;
}
}
一切都很好,当用户在游戏结束后等待时,如果他留在GameActivity
.
问题是,当:
- 用户结束游戏。
checkWorldRecord()
叫做。 - 在单独的线程中,第一个 POST 开始。
- 用户按下后退按钮并将活动更改为另一个,到
MainActivity
。 AsyncTask
完成检查,我们有新的记录。showEnterNameAndSend()
想先建后展示AlertDialog
。繁荣。因为我们正在通过GameActivity
,现在MainActivity
在顶部:
public static void showEnterNameAndSend(final Activity activity, final RecordType recordType, final double time,
final int level, final long gamesPlayed, final int stars)
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity); // BOOM!!!
final EditText editText = new EditText(activity);
editText.setFilters(new InputFilter[]
{ new InputFilter.LengthFilter(Const.MAX_NAME_LENGTH) });
editText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
builder.setView(editText);
builder.setTitle(recordType + " world record!");
builder.setMessage("Enter your name:");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int whichButton)
{
String username = editText.getText().toString();
if (username.equals(""))
{
return;
}
try
{
Network.sendRecord(recordType, username, time, level, gamesPlayed, stars); // 3.
}
catch (Exception e)
{
showInternetError(activity);
}
}
});
showDialogOnUiThread(activity, builder);
}
private static void showDialogOnUiThread(Activity activity, final AlertDialog.Builder builder)
{
activity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
builder.show();
}
});
}
是的,我也更喜欢通过Context
,而不是整体Activity
到showEnterNameAndSend()
。但是,showDialogOnUiThread()
(由 调用showEnterNameAndSend()
)需要Activity
,以显示Dialog
UI 线程,使用activity.runOnUiThread()
。
如何修复这个?也许例如有一些方法getCurrentActivity()
,所以我不必传递一个Activity
可以已经隐藏的?如果我能以某种方式取消显示对话框,在用户关闭后GameActivity
,它也可以。