android - 在 Android 上下载 html 源会使应用程序崩溃

标签 android html

我正在尝试将某些网站的代码下载到我的应用程序中,如下所示:

 public void wypned(final View pwn) throws IllegalStateException, IOException{
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet("http://example.com");
    HttpResponse response = httpClient.execute(httpGet, localContext);
    String result = "";

    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent() ) );

    String line = null;
    while ((line = reader.readLine()) != null){
    result += line + "\n";
    }
}

我得到的只是 fatal error 。 LogCat 说:

Caused by: android.os.NetworkOnMainThreadException
 on Android 3.x and up, you can't do network I/O on the main thread

有人能告诉我怎么解决吗?我尝试用线程做一些事情,但没有成功。

最佳答案

为此实现一个 asyncTask :

public class MyAsyncTask extends AsyncTask<Void, Void, Result>{

                        private Activity activity;
                        private ProgressDialog progressDialog;

            public MyAsyncTask(Activity activity) {
                            super();
                this.activity = activity;
            }

            @Override
            protected void onPreExecute() {
            super.onPreExecute();
                progressDialog = ProgressDialog.show(activity, "Loading", "Loading", true);
            }

            @Override
            protected Result doInBackground(Void... v) {
            //do your stuff here
            return null;

            }

            @Override
            protected void onPostExecute(Result result) {
                progressDialog.dismiss();
                Toast.makeText(activity.getApplicationContext(), "Finished.", 
                        Toast.LENGTH_LONG).show();
            }


}

从 Activity 中调用它:

MyAsyncTask task = new AsyncTask(myActivity.this);
task.execute();

关于android - 在 Android 上下载 html 源会使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12041786/

相关文章:

android - 将 Camera SurfaceView 旋转为纵向

java - 添加两 Pane 平板电脑布局导致在移动设备中找不到 View (小于 w600dp)

android - 通过 mediaCodec dequeueInputBuffer() 解码 h264 数据包返回 "no such buffer is currently available"

java - 您如何判断您的 Android 应用程序在 Android Studio 中使用的是 Kotlin 还是 Java?

html - 在没有一堆不同的图像大小和媒体查询的情况下使图像具有响应性的更有效方法?

java - 复制 xml 中的 View

javascript - 将元素添加到表格 - HTML/CSS/JS

HTML 移动应用程序和表格

javascript - 使用数据库值更改 div 背景颜色

javascript - 如何将外部 css 导入到 typescript 元素中