Android下载网络图片资源

从网络下载图片资源在各种APP中很常见,比如很多APP都有广告轮番功能,这些广告图片通常是从服务器获取的,这里就需要从服务器上下载图片资源并显示。

一、获取网络图片并下载到本地:

代码:MainActivity.java:

package com.example.androidt11;

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

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private EditText editText;
	private Button button;
	private ImageView imageView;
	
	private Bitmap bitmap;
	//手柄更新的作用
	Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what==111){
				imageView.setImageBitmap(bitmap);
			}
		};
	};
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		//初始化组件
		editText=(EditText) findViewById(R.id.imagepath);
		button=(Button) findViewById(R.id.upload);
		imageView=(ImageView) findViewById(R.id.imageView);
		
		//给下载按钮添加一个监听
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				new Thread(t).start();
			}
		});
	}
	
	//为了下载图片资源,开辟一个新的子线程
	Thread t=new Thread(){
		public void run() {
			//下载图片的路径
			String iPath=editText.getText().toString();
			try {
				//对资源链接
				URL url=new URL(iPath);
				//打开输入流
				InputStream inputStream=url.openStream();
				//对网上资源进行下载转换位图图片
				bitmap=BitmapFactory.decodeStream(inputStream);
				handler.sendEmptyMessage(111);
				inputStream.close();
				
				//再一次打开
				inputStream=url.openStream();
				File file=new File(Environment.getExternalStorageDirectory()+"/haha.gif");
				FileOutputStream fileOutputStream=new FileOutputStream(file);
				int hasRead=0;
				while((hasRead=inputStream.read())!=-1){
					fileOutputStream.write(hasRead);
				}
				fileOutputStream.close();
				inputStream.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		};
	};
	
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <EditText 
        android:id="@+id/imagepath"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"
        />
    <Button 
        android:id="@+id/upload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载"
        />
    <ImageView 
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

这时查看SD卡根目录,会看到一个haha.gif的图片

效果图:



二、下载图片后显示在ListVIew中(更接近实际应用):

MainActivity.java:

package com.example.demo1;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
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.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class MainActivity extends Activity {

	
	private ListView listView;   //界面组件
	private Bitmap[] bitmaps;    //定义一个位图数组,用来存放从网络下载下来的位图
	private ImageView[] images;  //定义一个ImageView数组,用来存放位图数组中的位图图片

	//网络图片资源
	private String[] urls = {
			"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2720761512,1992761174&fm=26&gp=0.jpg",
			"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=401967138,750679164&fm=26&gp=0.jpg",
			"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1059486618,1562064036&fm=26&gp=0.jpg" };

	//使用handler更新UI
	Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what==111){
				listView.setAdapter(new MyAdapter());
			}
		};
	};
	
	//继承BaseAdapter
	private class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			
			return urls.length;
		}

		@Override
		public Object getItem(int arg0) {
			
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, 100);
			images[arg0].setLayoutParams(layoutParams);
			return images[arg0];
		}
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		bitmaps = new Bitmap[urls.length];
		images = new ImageView[urls.length];
		listView = (ListView) findViewById(R.id.listView);

		// 为了下载图片资源,开辟一个新的子线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < urls.length; i++) {
					// 下载图片的路径
					String iPath = urls[i];
					try {
						// 对资源链接
						URL url = new URL(iPath);
						// 打开输入流
						InputStream inputStream = url.openStream();
						// 对网上资源进行下载转换位图图片
						bitmaps[i] = BitmapFactory.decodeStream(inputStream);
						images[i] = new ImageView(MainActivity.this);
						images[i].setImageBitmap(bitmaps[i]);
						inputStream.close();
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				handler.sendEmptyMessage(111);
			}

		}).start();

		
	}
}

xml文件里面仅一个ListView组件....

效果图:


发布了133 篇原创文章 · 获赞 43 · 访问量 18万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览