欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

安卓实现从互联网上获取图片并保存到本地目录中

程序员文章站 2022-12-25 12:09:22
因为是对互联网和内存操作,所以我们要添加如下权限: package com.itfom.getpicfromnet; import java.io.file; imp...

因为是对互联网和内存操作,所以我们要添加如下权限:

 

 

package com.itfom.getpicfromnet;

import java.io.file;
import java.io.fileoutputstream;
import java.io.inputstream;
import java.net.httpurlconnection;
import java.net.url;

import android.annotation.suppresslint;
import android.app.activity;
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.imageview;

@suppresslint("handlerleak")
public class mainactivity extends activity {

	private imageview iv_pic;
	private button btn_get;
	@override
	protected void oncreate(bundle savedinstancestate) {
		super.oncreate(savedinstancestate);
		setcontentview(r.layout.activity_main);
		btn_get = (button) findviewbyid(r.id.btn_get);
		iv_pic = (imageview) findviewbyid(r.id.iv_img);
		//设置监听事件
		btn_get.setonclicklistener(new onclicklistener() {

			@override
			public void onclick(view v) {
				//开启子线程
				new thread(){
					public void run() {
						try {
							string urlpath = "https://pic7.nipic.com/20100607/4791134_172835008083_2.jpg";
							url url = new url(urlpath);
							httpurlconnection conn = (httpurlconnection) url.openconnection();
							conn.setconnecttimeout(6*1000);  // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
							if (conn.getresponsecode() != 200) throw new runtimeexception("请求url失败");
							inputstream insream = conn.getinputstream();
							//把图片保存到项目的根目录
							readasfile(insream, new file(environment.getexternalstoragedirectory()+"/"+"test.jpg"));
							message msg=new message();
							msg.what=0;
							handler.sendmessage(msg);
						} catch (exception e) {
							e.printstacktrace();
						}
					};
				}.start();
			}
		});
	}
	public static void readasfile(inputstream insream, file file) throws exception{
		fileoutputstream outstream = new fileoutputstream(file);
		byte[] buffer = new byte[1024];
		int len = -1;
		while( (len = insream.read(buffer)) != -1 ){
			outstream.write(buffer, 0, len);
		}
		outstream.close();
		insream.close();
	}
	//创建handler
	handler handler=new handler(){
		public void handlemessage(android.os.message msg) {
			if(msg.what==0){
				//开始绑定数据
				iv_pic.setimagebitmap(bitmapfactory.decodefile(environment.getexternalstoragedirectory()+"/test.jpg"));
			}
		};
	};
}