2011-08-05 13 views
0

可能重复:
Download a file with Android, and showing the progress in a ProgressDialogAndroid:使用“进度”GUI在后台线程中从网络加载数据?

我想从一个Web服务器的信息加载到我的应用程序。目前,我正在主线程中执行此操作,我读过的操作非常糟糕(如果请求花费的时间超过5秒,则应用程序崩溃)。

因此,我想了解如何将此操作移至后台线程。这是否涉及某种服务?

下面是代码的样本,我做服务器的请求:

 // send data 
     URL url = new URL("http://www.myscript.php"); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     wr.write(data); 
     wr.flush(); 

     // Get the response 
     BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     while ((line = rd.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 

     wr.close(); 
     rd.close(); 

     String result = sb.toString(); 

     Intent i = new Intent(searchEventActivity.this, searchResultsActivity.class); 
      i.putExtra("result", result); 
     startActivity(i); 

我等待着要建立一个JSON字符串的响应,那么我传递一个字符串到一个新的活动。这是一个及时的操作,而不是悬挂用户界面,我想向用户展示某种好的“进度”栏(即使其中一个圆形灯具旋转灯也亮),而此URL业务正在发生后台线程。

感谢您的任何帮助或指导教程的链接。

+0

[与答案相同的问题(http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-progress-in-a-progressdialog)...已经有数百个(好的,很多)类似/相同的问题。 –

回答

4

该过程的基本思想是创建一个Thread来处理Web请求,然后使用Handler s和Runnable s来管理UI交互。

我在应用程序中管理这种方式的方式是使用包含所有智能和业务规则来管理我的通信的自定义类。它还包含构造函数中的变量以允许调用UI线程。

下面是一个例子:

public class ThreadedRequest 
{ 
    private String url; 
    private Handler mHandler; 
    private Runnable pRunnable; 
    private String data; 
    private int stausCode; 

    public ThreadedRequest(String newUrl, String newData) 
    { 
     url = newUrl; 
     data = newData; 
     mHandler = new Handler(); 
    } 

    public void start(Runnable newRun) 
    { 
     pRunnable = newRun; 
     processRequest.start(); 
    } 

    private Thread processRequest = new Thread() 
    { 
     public void run() 
     { 
      //Do you request here... 
      if (pRunnable == null || mHandler == null) return; 
      mHandler.post(pRunnable); 
     } 
    } 
} 

这会从您的UI线程调用如下:

final ThreadedRequest tReq = new ThreadedRequest(url, maybeData); 
//This method would start the animation/notification that a request is happening 
StartLoading(); 
tReq.start(new Runnable() 
    { 
     public void run() 
     { 
      //This would stop whatever the other method started and let the user know 
      StopLoading(); 
     } 
    });