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

标签 android multithreading json url

<分区>

Possible Duplicate:
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 字符串响应,然后将该字符串传递给一个新的 Activity 。这是一个及时的操作,而不是挂起 UI,我想向用户展示某种漂亮的“进度”栏(即使是那些带有旋转灯的圆圈之一也很好),而这个 URL 业务正在发生后台线程。

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

最佳答案

流程的基本思路是创建一个Thread来处理web请求,然后使用HandlerRunnable来管理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();
        }
    });

关于Android:使用 "progress"GUI 在后台线程中从 Web 加载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6960020/

相关文章:

android - 如何在 android 中使用 Gson 库解析 json 响应?

c# - 线程安全问题

android无法使用json将3个编码字符串从base64发送到mysql

javascript - 无法在模拟器上运行React Native Project

java - 如何通过多个HashMap进行算术运算?

单独线程上的 Javascript 回调函数

java - 匿名 Runnable 的这种特殊使用会导致内存泄漏吗?

javascript - 使用 JQUERY 通过 PHP AJAX JSON 显示所有数据

php - 如何以 .JSON 文件格式存储 MySQL 数据?

android - 无法找到 Java 运行时 Android Studio Robolectric