本篇文章将介绍给大家如何在Android下从网络上获取一张图片并显示出来,希望和大家共同学习交流。
主要包括两种方法,使用Google提供的官方API或者使用开源框架;
方法一、使用Android自带API:
涉及的知识主要包括:线程开启、Handler消息机制、Bitmap。
先来看一下布局文件activity_main. xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入图片地址" />
<Button
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查看" />
<ImageView //imageView用于显示从网络上获得的图片
android:id="@+id/iv_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
布局中放置了一个EditText
用于输入图片的地址,并为按钮设置了一个onClick
属性,这样在MainActivity
只需定义同名函数即可实现点击事件。点击按钮后图片将会被下载并显示到imageView
中
接下来我们来看一下Main_Activity
中代码
package imagelook.mystudy.kjpc.imagelook;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
ImageView iv;
EditText et_path;
String path;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Bitmap bitmap = (Bitmap) msg.obj;
iv_show.setImageBitmap(bitmap);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//寻找相应控件
et_path = findViewById(R.id.et_path);
iv_show = findViewById(R.id.iv_show);
}
public void click(View v){
new Thread(){
Message message = Message.obtain();
@Override
public void run() {
File file = new File(getCacheDir(),"test.png");
if(file.exists() && file.length()>=0){
System.out.print("本地缓存");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
message.obj = bitmap;
handler.sendMessage(message);
}
else{
path = et_path.getText().toString().trim();
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");//设置请求方法
conn.setConnectTimeout(5000);//设置超时时间
InputStream in = conn.getInputStream();//拿到服务器返回的输出流
Bitmap bitmap = BitmapFactory.decodeStream(in);
message.obj = bitmap;
message.what = 2;
handler.sendMessage(message);//发送消息
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
由于这里需要联网操作,故需要在子线程(Android下进行联网,复制大规模数据等耗时操作时,都需要在子线程中进行,如果在主线程中操作会引发ANR
异常(Application Not Responding))。
所以这里首先声明了Handler用来接收从子线程中发送的消息,接着在按钮的点击事件中我们首先判断这张图片是否下载过,如果已下载就从本地加载,否则先从editText
中拿到文本并将其转化为url
对象,接着通过URL的openConnection()
方法拿到urlConnection
的实例,接着设置超时时间和请求方法,注意这里服务器是以流的形式返回数据的,所以使用一下BitmapFactory
工厂类(这个类下的方法全是静态方法,建议大家去这里看一下)下的decodeStream()
静态方法将流转换为图片并显示即可。
这里我用的是Android Studio最新版,他可以自动进行部分转型,用Eclipse的小伙伴记得在findViewById
前添加一下向下转型(et_path = (EditText)findViewById(R.id.et_path);
)
方法二、使用开源框架:Picasso、Glide等。
这里以Picasso为例进行介绍:
项目地址:https://github.com/square/picasso
使用方法:
- 在build.gradle文件中添加如下依赖:
implementation 'com.squareup.picasso:picasso:2.71828'
- 在Activity中添加如下代码,其中iv_show是用于显示图片的控件,internetUrl是图片的网址
ImageView iv_show = findViewById(R.id.iv_show);
String internetUrl = "https://a.36krcnd.com/photo/2014/5be404781da19da8778d6cbf0296acc1.jpg";
Picasso.get().load(internetUrl).into(iv_show);`