使用Android从服务器下载图像

时间:2017-03-15 21:06:04

标签: android image download server

我正在尝试从互联网上下载图片。现在,应用程序仅下载部分图像,但随后停止。我正在使用AsyncTask。关于该怎么做的任何建议?

我得到的错误是:

android.os.NetworkOnMainThreadException
 at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:74)
W/System.err:     at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:30)

这是我的代码:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void onClick (View view){
    DownloadAsyncTask task = new DownloadAsyncTask();
    task.execute(new String[] {"http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg" });
}

private class DownloadAsyncTask extends AsyncTask<String, Void, String> {


    Bitmap bitmap = null;
    InputStream in = null;

    @Override
    protected String doInBackground(String... urls){


        int response = -1;
        URL url;

        try {
            url = new URL("http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg");

        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            System.out.println("This is wrong");


        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
            return "success";
        }
        }

    catch (IOException e) {
        System.out.println("IOException");
    }
        return "Download failed";
    }

    @Override
    protected void onPostExecute(String result) {
        //try {
            bitmap = BitmapFactory.decodeStream(in);
         /*   in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }*/
        ImageView img = (ImageView) findViewById(R.id.image);

        img.setImageBitmap(bitmap);
    }

}

}

1 个答案:

答案 0 :(得分:0)

如果您不想使用第三方库,请尝试此操作

        new DownloadImage(Imageview).execute(YourUrl);

创建AsyncTask类

    public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    CircleImageView bmImage;

    public DownloadImage(ImageView bmImage) {
        this.bmImage = (CircleImageView) bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.d("Error", e.getStackTrace().toString());

        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}