我有一个问题,希望你能帮助我。我有一个 Asynctask,如果我在 mainactivity 中按下一个按钮,它就会开始上传数据。它工作正常,除非我的互联网连接速度很慢。Asynctask 启动一个progressdialog,如果我的连接速度很慢,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;
}
}
}