0

嗨,当我想从 url 下载图像时,你能帮我找出为什么我的应用程序停止工作吗,这是代码

    public void getOnClick(View view) throws IOException {

    urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp-     content/uploads/2010/11/Capri.jpg");
    InputStream is = urlAdress.openStream();
    filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
    outputFile = new File(context.getCacheDir(),filename);
    OutputStream os = new FileOutputStream(outputFile);
    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);

        is.close();
        os.close();

我也尝试使用来自类似主题的一些代码,但我收到相同的消息

您的应用已停止运行

它关闭了

4

1 回答 1

0
Caused by: android.os.NetworkOnMainThreadException

问题是您正在尝试从 UIThread 下载图像。您必须创建一个扩展为 AsyncTask 类的类并在 doInBackground 方法上进行下载

private class DownloadAsync extends AsyncTask<Void, Void, Void> {

        private Context context;

        DownloadAsync(Context context) {
            this.context = context;
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {

                URL urlAdress = urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp-     content/uploads/2010/11/Capri.jpg");
                InputStream is = urlAdress.openStream();
                String filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
                File outputFile = new File(context.getCacheDir(), filename);
                OutputStream os = new FileOutputStream(outputFile);
                byte[] b = new byte[2048];
                int length;

                while ((length = is.read(b)) != -1) {
                    os.write(b, 0, length);

                    is.close();
                    os.close();

                    return null;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

    }

然后你可以像这样执行

public void getOnClick(View view){
   new DownloadAsync(this).execute();
}
于 2016-01-21T18:01:36.470 回答