Android(安卓)URL访问网络资源,通过URL加载网络图片
16lz
2021-12-04
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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" tools:context="shortcut.song.com.myapplication.UrlTestActivity"> <ImageView android:id="@+id/url_show" android:layout_width="wrap_content" android:layout_height="wrap_content" />LinearLayout>
package shortcut.song.com.myapplication;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.widget.ImageView;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.MalformedURLException;import java.net.URL;public class UrlTestActivity extends AppCompatActivity { ImageView imageView; Bitmap bitmap; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0x1234) { imageView.setImageBitmap(bitmap); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_url_test); imageView = (ImageView)findViewById(R.id.url_show); new Thread(){ @Override public void run() { super.run(); try { // 定义一个URL对象 URL url = new URL("http://192.168.8.27/files/JPG/9.jpg"); // 打开该URL对应的资源输入流 InputStream is = url.openStream(); // 从InputStream中解析出图片 bitmap = BitmapFactory.decodeStream(is); // 发送消息,通知UI组件加载图片 handler.sendEmptyMessage(0x1234); is.close(); // 再次打开该URL对应的资源输入流 is = url.openStream(); // 打开文件对应的输出流 OutputStream os = openFileOutput("9.jpg", MODE_PRIVATE); byte[] buff = new byte[1024]; int hasRead = 0; // 将URL对应的资源下载到本地 while ((hasRead = is.read(buff)) > 0){ os.write(buff, 0, hasRead); } is.close(); os.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); }}
运行效果(通过URL加载的图片):
更多相关文章
- android 处理图片工具
- android submenu
- Android(安卓)双击和手势的图片缩放
- android HttpClient 上传图片
- android背景模糊化处理
- Android(安卓)WebView的加载超时处理
- android中颜色对应的值
- Android(安卓)– 加载图片本缓存到内存与本地
- android点击实现图片放大缩小