Android:在后台线程中使用"进度"GUI从Web加载数据?

JDS*_*JDS 1 url multithreading android json

可能重复:
使用Android下载文件,并在ProgressDialog中显示进度

我想从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);
Run Code Online (Sandbox Code Playgroud)

所以我正在等待构建一个JSON字符串响应,然后我将该字符串传递给一个新的活动.这是一个及时的操作,而不是挂起用户界面,我想向用户展示一个不错的"进度"栏(甚至其中一个旋转灯的圈子很好),而这个URL业务正在发生后台线程.

感谢您提供任何帮助或教程链接.

gtc*_*ist 5

该过程的基本思想是创建一个Thread处理Web请求,然后使用Handlers和Runnables来管理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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将从您的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();
        }
    });
Run Code Online (Sandbox Code Playgroud)