0

我想编写一个 Android 应用程序,它将从互联网上检索数据并保存在本地文件中。这是我写的:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Runnable r = new Runnable() {
        @Override
        public void run() {
            updateData();
        }
    };
    Handler h = new Handler();
    h.post(r);
}
private Boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if(ni != null && ni.isConnectedOrConnecting()) {
        return true;
    }
    else {
        return false;
    }
}

private void updateData() {
    if(!isOnline()) {
        Toast.makeText(this, "Unable to update data: Internet Connection Unavailable", Toast.LENGTH_SHORT).show();
    }
    else {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet req = new HttpGet("***SOME URL****");
            HttpResponse res = client.execute(req);             
            InputStream is = res.getEntity().getContent();
            InputStreamReader ir = new InputStreamReader(is);
            StringBuilder sb = new StringBuilder();
            Boolean end = false;
            do {
                int t = ir.read();
                if(t==-1) {
                    end = true;
                }
                else {
                    sb.append((char)t);
                }
            }
            while(!end);
            String s = sb.toString();
            File f = new File(getFilesDir(), "data.txt");
            FileWriter fw = new FileWriter(f);
            fw.write(s);
            fw.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

我让主线程阻塞了大约 2-3 秒。而且我不确定这是否是正确的方法。因此,如果您认为这是不正确的做法,请随时告诉我。

问候,萨伦

4

2 回答 2

1

从处理程序构造函数API

将此处理程序与当前线程的 Looper 相关联。

这意味着Handler您创建的 与LooperUI 线程相关联,这意味着runnable正在 UI 线程上执行(因此您会看到 UI 的暂停)。我建议您使用 Android或在后台线程上AsyncTask实例化。Handler

于 2013-10-28T12:44:34.977 回答
0

使用 AsyncTask 来摆脱这个。AsyncTask 的代码如下:

class AsyncLogin extends AsyncTask<Void, Void, String> {
        ProgressDialog dialog = new ProgressDialog(MyTopic.this);

        protected String doInBackground(Void... params) {


            return msg;
        }

        protected void onPostExecute(String result) {
            try {

                    dialog.cancel();

                }
            } catch (Exception e) {
                dialog.cancel();
            }

        }

        protected void onPreExecute() {
            super.onPreExecute();
            dialog.setMessage("Fetching...Topic List!!!");
            dialog.setCancelable(true);
            dialog.show();

        }
    }

调用代码:

AsyncLogin as = new AsyncLogin();
as.execute();
于 2013-10-28T12:55:40.357 回答