2011-08-22 111 views
0

我有一个AsynTask实现,当我从设备启动应用程序时,应用程序有延迟。这种延迟在第一次运行时不会出现,但始终在第一次运行之后,所以如果我杀了应用程序并在6分钟后回来,它将启动连接并永远不会结束。AsyncTask在启动应用程序时出现奇怪的延迟

这里是我的AsyncTask:

private class MakeConnection extends AsyncTask<String, Void, String> { 

    Context context; 
    ProgressDialog myDialog; 

    public MakeConnection(Context conetext) 
    { 
     this.context = conetext; 
     myDialog = new ProgressDialog(this.context); 
    } 

    @Override 
    protected String doInBackground(String... urls) { 
     String response = ""; 
     for(String url : urls) 
     { 
      try 
      { 
       URL theUrl = new URL(url); 
       URLConnection ucon = theUrl.openConnection(); 
       ucon.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 
       InputStream is = ucon.getInputStream(); 
       BufferedInputStream bis = new BufferedInputStream(is); 
       ByteArrayBuffer baf = new ByteArrayBuffer(50); 
       int current = 0; 
       while(((current = bis.read()) != -1) && !isCancelled()) 
       { 
        baf.append((byte)current); 
       } 
       response = new String(baf.toByteArray()); 

      } 
      catch (Exception e) 
      { 
       response = e.getMessage(); 
      } 

     } 
     return response; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     try { 
      myDialog.dismiss(); 
      success(result); 
     }catch(JSONException e) 
     { 
      data = e.toString(); 
     } 
    } 

    @Override 
    protected void onPreExecute(){ 
     myDialog = ProgressDialog.show(
       context, 
       "Please wait...", 
       "Loading the data", 
       true, 
       true, 
       new DialogInterface.OnCancelListener(){ 
        @Override 
        public void onCancel(DialogInterface dialog) { 
         MakeConnection.this.cancel(true); 
        } 
       } 
     ); 
    } 
} 

然后在我的onCreate()

task = new MakeConnection(this); 
task.execute(new String[] {url}); 

我无法理解为什么会发生?

编辑:

当应用程序启动的第一次工作得很好,但是当我再次打开该应用程序在以后的阶段上面看到的第一个连接执行以下操作:

  • 它启动进度对话框,然后我不知道它是否实际连接,因为我看到的是进度对话框永远不会消失,换句话说,它永远不会完成连接,因为如果连接完成进度对话框将完成
+0

您可以重新解释或解释什么是延迟或什么连接没有完成。您是否在“doInBackground”中放置了一些日志代码来查看它何时开始和结束? – Fraggle

+0

@Fraggle好吧我编辑帖子 – Armand

+0

好的,首先,你可以插入一些日志代码,看看实际发生了什么。其次,我仍然不知道“当我在稍后的阶段重新打开应用程序”的意思。 Activity是否调用了onDestroy方法? wasCreate实际上是第二次?您是否退出主屏幕然后重新启动?尝试在中间运行的应用程序上执行Force stop并查看是否得到不同的结果。 – Fraggle

回答

0

我发现问题在于服务器获取请求,我做的是添加一个计时器刷新连接,如果花费很长时间。