Android中实现网络图片的获取
16lz
2021-01-23
在Android中要想获取网络资源,可以使用 HttpURLConnection 和 HttpsURLConnection 来实现相关功能。
下面案例实现了基于URL的简单请求响应,通过HttpURLConnection 获取连接,通过InputStream获取输入流,BitmapFactory 将数据流转换为 Bitmap,再将 Bitmap 通过线程的 Message发送出去,Handler 接收到消息就会通知 ImageView 显示出来。相关操作是通过点击按钮触发的。
接下来看相关代码的实现:
XML文件:
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity">
java文件:
package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.ImageView;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends AppCompatActivity { String path = "https://s1.ax1x.com/2020/05/05/YkGcqg.png"; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.btn); imageView = (ImageView) findViewById(R.id.imageView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { Bitmap bm=getBitmap(path); Message msg = new Message(); msg.what = 0; msg.obj = bm; System.out.println("000"); handle.sendMessage(msg); } }).start(); } }); } //在消息队列中实现对控件的更改 private Handler handle = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: System.out.println("111"); Bitmap bm=(Bitmap)msg.obj; imageView.setImageBitmap(bm); break; } }; }; private Bitmap getBitmap(String path) { Bitmap bm = null; try { URL url = new URL(path);//创建一个URL对象,其参数为网络图片的链接地址 //使用一个URL对象开启一个链接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); //设置相关参数 con.setDoInput(true); con.setConnectTimeout(5000);//设置超时 con.setReadTimeout(2000); con.connect(); InputStream is = con.getInputStream();//获取输入流 bm = BitmapFactory.decodeStream(is);//将输入流解码为Bitmap对象 is.close(); } catch (Exception e) { e.printStackTrace(); } return bm; }}
在这里要 注意 的是,千万不要忘记要在 manifest 文件中添加下面一行代码
android:name="android.permission.INTERNET" />
进行上网权限的添加,否则就无法获取网络资源。
运行后点击按钮实现效果:
注:
其中的链接是我的图床上的一张图片(https://s1.ax1x.com/2020/05/05/YkGcqg.png)
参考博文:https://blog.csdn.net/u013408061/article/details/97000473
https://blog.csdn.net/z474013281/article/details/99684602
https://www.cnblogs.com/yxwkf/p/5134431.html
更多相关文章
- AsyncTask异步下载图片
- Android图片加载框架Picasso最全使用教程 一
- android checkbox 未选中状态 已选中状态 替换成自己的图片
- Android 控件之Gallery和ImageSwitcher图片切换器
- android中使用Thumbnails批量加载sdcard中的缩略图片
- Android 拼接两个图片