网络加载图片

package com.example.lenovo.demo8;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button selImage;
private ImageView imageView;
@SuppressLint(“HandlerLeak”)
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:

                imageView.setImageBitmap((Bitmap) msg.obj);
                break;
            case 2:
                Toast.makeText(MainActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
                break;
        }
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView=findViewById(R.id.iv_iv);
    selImage=findViewById(R.id.selImage);
    selImage.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.selImage:
            Toast.makeText(MainActivity.this,"111",Toast.LENGTH_LONG).show();
            //路径存到String中
            final String spec="http://169.254.53.96:8080/c.jpg";
            //转到getfilename方法中
            final File file=new File(getCacheDir(),getFileName(spec));
            //进行判断文件是否存在
            if (file.exists()){
                //通过BitmapFactory,decodeFile方法,参数是文件对象.getAbsolutePath();得到本地缓存的Bitmap对象.
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                //                    ///创建message对象,最好用obtainmessage方法得到
                Message message=Message.obtain();
                //把数据赋予给message.obj
                message.obj=bitmap;
                //把数据赋予给message.what
                message.what=1;
                //发送数据
                handler.sendMessage(message);
            }else{
                Thread t=new Thread(){
                    @Override
                    public void run() {
                        try {
                            //实用网址封装一个url对象new url网址
                            URL url=new URL(spec);
                            //获取网络对象
                            HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
                            //请求方式
                            urlConnection.setRequestMethod("GET");
                            //连接超时
                            urlConnection.setConnectTimeout(3000);
                            //读取超时
                            urlConnection.setReadTimeout(8000);
                            //发送请求
                            urlConnection.connect();
                            if (urlConnection.getResponseCode()==200){
                                //拿到返回流
                                InputStream inputStream = urlConnection.getInputStream();
                                //从流中拿取图片
                                byte[] bytes = new byte[1024];
                                //定义int变量
                                int length;
                                //定义一个fileoutputstream,传入对象
                                FileOutputStream fileOutputStream = new FileOutputStream(file);
                                //while判断,输入流.read(byte数组),赋给int变量,判断!=-1
                                while((length=inputStream.read(bytes))!=-1){
                                    //输出流.write(byte数组,0,int变量)
                                    fileOutputStream.write(bytes,0,length);
                                }
                                //关流
                                fileOutputStream.close();
                                //通过本地路径构造一张位图对象,使用的是bitemapfactory.decodeFile(参数文件对象.FileOutputStream拿到绝对路径)
                                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                                //往主线程发送消息,创建message对象.
                                Message message=new Message();
                                message.obj=bitmap;
                                message.what=1;
                                //发送数据
                                handler.sendMessage(message);
                            }else {
                                Message message=handler.obtainMessage();
                                message.what=2;
                                //发送数据
                                handler.sendMessage(message);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                t.start();
            }
            break;
    }
}
private String getFileName(String spec) {
    int i = spec.lastIndexOf("/");
    String substring = spec.substring(i + 1);
    return substring;
}

}

猜你喜欢

转载自blog.csdn.net/qq_42828101/article/details/83027432