我有一个问题,希望你能帮助我。 我有一个 Asynctask,如果我在我的主要 Activity 中按下一个按钮,它就会开始上传数据。 它工作正常,除非我的互联网连接速度很慢。 Asynctask 启动一个进度对话框,如果我的连接速度很慢,Asynctask 会停止,但 Progressdialog 不会消失,因为它从未到达 onPostExecute。
现在我正在尝试实现超时但找不到方法,因此进度对话框会取消执行此操作。
这是我的代码:
@Override
protected void onPreExecute() {
super.onPreExecute();
time = System.currentTimeMillis();
Log.d(TAG, "PBar: Hat gestartet");
if (MainActivity.MessungStart == true)
{
ConnectionTask.dialog = new ProgressDialog(MainActivity.context);
ConnectionTask.dialog.setMessage("Daten werden hochgeladen...");
dialog.setCanceledOnTouchOutside(false);
ConnectionTask.dialog.show();
}
}
protected Void doInBackground(String... args) {
mUser = MainActivity.username;
mPassword = MainActivity.password;
Log.d(TAG,"Async: User= "+mUser+" Password= "+mPassword);
Timer t = new Timer();
TimerTask tk = new TimerTask() {
@Override
public void run() {
timeout = true;
}
};
t.schedule(tk, 100);
if(timeout == true)
{
Log.d(TAG, "TimeOut = true");
onPostExecute(null);
}
try {
authenticate();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
try {
sendData();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(temp!= null)
{
try {
ReceiveMessageState();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sendungfertig = true;
if(MainActivity.asyncIsCanceled == true)
{
if (ConnectionTask.dialog.isShowing() == true)
{
ConnectionTask.dialog.dismiss();
}
}
isCancelled();
return null;
}
@Override
protected void onPostExecute(Void v) {
super.onPostExecute(v);
Log.d(TAG, "PBar: Sollte enden");
if(MessageChecked==true)
{
if (ConnectionTask.dialog.isShowing() == true)
{
ConnectionTask.dialog.dismiss();
}
if(isCancelled()==true)
{
if (ConnectionTask.dialog.isShowing() == true)
{
ConnectionTask.dialog.dismiss();
}
MessageChecked = false;
MainActivity.MessungStart = false;
}
}
}
最佳答案
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
而不是做
if(timeout == true)
{
Log.d(TAG, "TimeOut = true");
onPostExecute(null); // this should be removed
只是 return null
在那里。这会将控制返回给 onPostExecute()
,您可以在其中关闭 Dialog
。
编辑
我认为在这种情况下,您使用 TimerTask
会使事情变得过于复杂,因为一切都会继续运行。您可以做的是使用 while 循环
和一个计数器来计算您想要的任何时间。所以像
long waitTime = 1000; // or whatever you want the timeout length to be
long curWaitTime = 0;
while (!timeout && curWaitTime < waitTime)
{
// put your network/file code here
// if the data finishes then you can set timeout to true
curWaitTime += 100; // or some other value to add
Thread.sleep(100);
}
return null;
关于android - 如何使 Asynctask 超时并关闭 ProgressDialog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945003/