android 之文件下载

首先,我们使用IO对文件进行下载操作,把下载到的文件保存到sdCard目录下。前提是保证有sdCard。

看代码吧:

ImageService.java

package com.hkrt.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ImageService {
	//从互联网上读取图片http://hiphotos.baidu.com/huyangdiy/pic/item/7509b40db709fce9d0581bfc.jpg
	public static byte[] getImage(String path) throws Throwable{
		URL url = new URL(path);
		HttpURLConnection  conn = (HttpURLConnection)url.openConnection();
		conn.setReadTimeout(5*1000);
		if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
			InputStream is  = conn.getInputStream();
			return readIS(is);
		}else{
			throw new Exception("请求路径错误");
		}
	
		
	}
	public  static byte []  readIS(InputStream is) throws IOException{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte [] buff = new byte[1024];
		int length=0;
		while((length =is.read(buff))!=-1){
			bos.write(buff, 0, length);
		}
		return bos.toByteArray();
	}
	
	/**
	 * @param path 资源路径
	 * @return   资源文件流
	 * @throws Throwable
	 */
	public static InputStream getInputStream(String path) throws Throwable{
		URL url = new URL(path);
		HttpURLConnection  conn = (HttpURLConnection)url.openConnection();
		conn.setReadTimeout(5*1000);
		if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
			InputStream is  = conn.getInputStream();
			return is;
		}
		return null;
	}
	/**对下载文件以时间重命名*/
	public static String getDateTime(){
		return new SimpleDateFormat("yyyy-MM-dd hh-MM-ss").format(new Date()).toString();
	}
}
ImageViewActivity.java

package com.hkrt.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
/**
 * 点击按钮从网下查看图片
 * @author Administrator
 *
 */
public class ImageViewActivity extends Activity {
	private static final String TAG="ImageViewActivity";
    private EditText urlEdt;//文件路径
    private ImageView imageView;//页面中展示的图片
    private Button downLoadButton ;//下载按钮
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        urlEdt=(EditText)this.findViewById(R.id.path);
        imageView =(ImageView)this.findViewById(R.id.image);
        downLoadButton  =(Button)this.findViewById(R.id.button);
        downLoadButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String imagePath = urlEdt.getText().toString();
				try {
					byte [] imageByte = ImageService.getImage(imagePath);
					Bitmap bm = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length);
					imageView.setImageBitmap(bm);
					String imageSuffix = imagePath.substring(imagePath.lastIndexOf("."), imagePath.length());
					downLoadImage(imagePath,ImageService.getDateTime()+imageSuffix );//下载图片
				} catch (Throwable e) {
					Log.i(TAG, e.toString());
					Toast.makeText(getApplicationContext(), "图片儿获取失败", Toast.LENGTH_SHORT).show();
				}
			}
		});
    }
	/**下载文件到sd卡上*/
	public void downLoadImage(String path,String fileName){
		 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
            File sdCardDir = Environment.getExternalStorageDirectory();//获取到文件的存储路径	
            InputStream is=null ;
            try {
            	 
            	 File dest =new File(sdCardDir.getCanonicalPath()+File.separator+"imageMe"); 
             	 is = ImageService.getInputStream(path);
             	 if(!dest.exists()){
             		dest.mkdirs();
             	 }
            	 OutputStream output = new FileOutputStream(dest+File.separator+fileName);  
                 byte[] buffer = new byte[8192];  
                 while((is.read(buffer)) != -1){  
                     output.write(buffer);  
                 }  
                 output.flush(); 
                 System.out.println("下载成功");
			} catch (Throwable e) {
				e.printStackTrace();
			}finally{
				if(is!=null){
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		   
		 }
	}

}

效果图:

注:把下载的文件导出去,使用文件预览打不开,原始不明。换其他的打开方式。
以上方法是实现了图片显示和下载的功能,但下载的时候是在主线程中执行的,这人时候就会有问题了。UI线程执行代码的速度最好不要超过10秒。

这个时候,做下载时,我们应该独立开启一个线程做下载功能处理。

主要实现代码:

在点击获取图片是开启一个新的线程:

Thread loginThread = new Thread(new DownloadThread());  
loginThread.start();

线程的新方法实现下载,并把下载成功与否返回给handle 。

private class DownloadThread implements Runnable{
		@Override
		public void run() {
			String imageSuffix = imagePath.substring(imagePath.lastIndexOf("."), imagePath.length());
			boolean down =	downLoadImage(imagePath,ImageService.getDateTime()+imageSuffix );//下载图片
			Message message = new Message();
			Bundle bun = new Bundle();
			bun.putBoolean("downLoadState", down);
			message.setData(bun);
			downLoadHandler.sendMessage(message);}
		}

返回handle处理结果信息并通知下载成功与否:
 downLoadHandler  = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				Bundle bun = msg.getData();
				boolean downState = (Boolean)bun.getBoolean("downLoadState");
				if(downState){
					Intent intent = new Intent(ImageViewActivity.this,OtherActivity.class);
					PendingIntent contentIntent = PendingIntent.getActivity(ImageViewActivity.this, 0, intent, 0);
					Notification notify = new Notification();
					notify.icon=R.drawable.icon1;
					notify.tickerText="启动otherActivity通知";
					notify.when=System.currentTimeMillis();
					notify.defaults=Notification.DEFAULT_SOUND;
					notify.defaults=Notification.DEFAULT_ALL;
					notify.setLatestEventInfo(ImageViewActivity.this, "普通通知", "点击查看", contentIntent);
					NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
					manager.notify(0, notify);
				}else{
					Toast.makeText(getApplicationContext(), "图片儿下载失败", Toast.LENGTH_SHORT).show();
				}
				super.handleMessage(msg);
			}
        	
        };

同时需要添加通知震动的权限:
 
  <uses-permission android:name="android.permission.VIBRATE" />









原文地址:https://www.cnblogs.com/java20130726/p/3218330.html