通过HttpURLConnection获取网页图片 并保存至内存卡的例子


  该demo为通过多线程和HttpURLConnection获取网上图片,并保存至内存卡 ,再通过多线程更新UI的例子:

  1.MainActivity.java

public class MainActivity extends AppCompatActivity {
Handler handler=new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView=(ImageView)findViewById(R.id.image);
        new HttpThreadImagen("http://img5.imgtn.bdimg.com/it/u=2107413826,1990412659&fm=21&gp=0.jpg",imageView,handler).start();

    }


2. HttpThreadImagen.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.webkit.WebView;
import android.widget.ImageView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by pss on 2015/12/31.
 */
public class HttpThreadImagen extends Thread {

    private String murl;
    private ImageView mimageView;
    private Handler mhandler;

    /**
     * 创建构造函数
     * @param url
     * @param imageView
     * @param handler
     */
    public HttpThreadImagen(String url,ImageView imageView,Handler handler){

        this.murl=url;
        this.mhandler=handler;
        this.mimageView=imageView;
    }


    @Override
    public void run() {
        try {
            URL httpUrl=new URL(murl);//获取传入进来的url地址  并捕获解析过程产生的异常
            //使用是Http访问  所以用HttpURLConnection  同理如果使用的是https  则用HttpsURLConnection
            try {
                HttpURLConnection conn= (HttpURLConnection) httpUrl.openConnection();//通过httpUrl开启一个HttpURLConnection对象
                conn.setReadTimeout(5000);//设置显示超市时间为5秒
                conn.setRequestMethod("GET");//设置访问方式
                conn.setDoInput(true);//设置可以获取输入流

                InputStream in=conn.getInputStream();//获取输入流

                //创建一个写入ID卡的文件对象
                FileOutputStream out=null;
                File download=null;
                String filename=String.valueOf(System.currentTimeMillis());//获取系统时间
                //判断文件是否存在   Environment.MEDIA_MOUNTEDID卡是否挂载  如果是则创建文件对象
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                   File parent=Environment.getExternalStorageDirectory();//获取ID卡目录
                     download=new File(parent,filename);//在父类的目录下创建一个以当前下载的系统时间为文件名的文件

                  out=new FileOutputStream(download);
                }

                byte[]b=new byte[2*1024];
                int len;
                if (out!=null){//id卡如果存在  则写入
                    while((len=in.read(b))!=-1){
                        out.write(b,0,len);
                    }
                }

                //读取该文件中的内容
                final Bitmap bitmap= BitmapFactory.decodeFile(download.getAbsolutePath());
                //更新UI
                mhandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mimageView.setImageBitmap(bitmap);
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


    }

}


3.layoutxml

<ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"/>



4.需要的权限为:

<uses-permission android:name="android.permission.INTERNET"/>
    <!--获取读取图片权限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


5.运行效果:



 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值