我有一个问题,希望你能帮助我。
我有一个异步任务,如果我在主要活动中按下按钮,它就会开始上传数据。
除非我的互联网连接速度很慢,否则它工作正常。
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;
}
}
}
根据文件 http://developer.android.com/reference/android/os/AsyncTask.html
不要手动调用 onPreExecute()、onPostExecute(Result)、doInBackground(Params...)、onProgressUpdate(Progress...)。
而不是做
if(timeout == true)
{
Log.d(TAG, "TimeOut = true");
onPostExecute(null); // this should be removed
just return null
那里代替。这会将控制权返回给onPostExecute()
你可以在哪里关闭你的Dialog
.
Edit
我认为你把事情搞得太复杂了TimerTask
在这种情况下,因为一切都会继续进行。你能做的就是使用while loop
以及您想要的任何时间的计数器。所以像
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)