1. 程式人生 > >Android下載網路圖片資源

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元件....

效果圖: