【问题标题】:Android: loading data from the web in background thread with a "progress" GUI? [duplicate]Android:使用“进度”GUI在后台线程中从网络加载数据? [复制]
【发布时间】:2011-10-21 01:28:30
【问题描述】:

可能重复:
Download a file with Android, and showing the progress in a ProgressDialog

我想将信息从网络服务器加载到我的应用程序中。目前我正在主线程中执行此操作,我读过这是非常糟糕的做法(如果请求花费的时间超过 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 字符串响应,然后我将该字符串传递给一个新的活动。这是一个及时的操作,而不是挂起 UI,我想在这个 URL 业务发生时向用户展示一个不错的某种“进度”栏(即使是带有旋转灯的圆圈也不错)一个后台线程。

感谢任何帮助或教程链接。

【问题讨论】:

标签: android multithreading json url


【解决方案1】:

该过程的基本思想是创建一个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);
        }
    }
}

这将从您的 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();
        }
    });

【讨论】:

    猜你喜欢
    • 2010-10-13
    • 1970-01-01
    • 2014-08-20
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    相关资源
    最近更新 更多