网络下载 并保存

 Android实现下载图片并保存到SD卡中 收藏


1.java代码,下载图片的主程序

先实现显示图片,然后点击下载图片按钮,执行下载功能。




view plaincopy to clipboardprint?
01.package com.min.android_test_2_3_3; 
02. 
03.import java.io.BufferedOutputStream; 
04.import java.io.ByteArrayOutputStream; 
05.import java.io.File; 
06.import java.io.FileOutputStream; 
07.import java.io.IOException; 
08.import java.io.InputStream; 
09.import java.net.HttpURLConnection; 
10.import java.net.URL; 
11. 
12.import android.app.Activity; 
13.import android.app.ProgressDialog; 
14.import android.graphics.Bitmap; 
15.import android.graphics.BitmapFactory; 
16.import android.os.Bundle; 
17.import android.os.Environment; 
18.import android.os.Handler; 
19.import android.os.Message; 
20.import android.util.Log; 
21.import android.view.View; 
22.import android.widget.Button; 
23.import android.widget.ImageView; 
24.import android.widget.Toast; 
25.public class AndroidTest2_3_3 extends Activity { 
26.    private final static String TAG = "AndroidTest2_3_3"; 
27.    private final static String ALBUM_PATH  
28.            = Environment.getExternalStorageDirectory() + "/download_test/"; 
29.    private ImageView imageView; 
30.    private Button btnSave; 
31.    private ProgressDialog myDialog = null; 
32.    private Bitmap bitmap; 
33.    private String fileName; 
34.    private String message; 
35.     
36.     
37.    @Override 
38.    protected void onCreate(Bundle savedInstanceState) { 
39.        super.onCreate(savedInstanceState); 
40.        setContentView(R.layout.main); 
41.         
42.        imageView = (ImageView)findViewById(R.id.imgSource); 
43.        btnSave = (Button)findViewById(R.id.btnSave); 
44.         
45.        String filePath = "http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg"; 
46.        fileName = "test.jpg"; 
47.         
48.        try {    
49.            byte[] data = getImage(filePath);    
50.            if(data!=null){    
51.                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap    
52.                imageView.setImageBitmap(bitmap);// display image    
53.            }else{    
54.                Toast.makeText(AndroidTest2_3_3.this, "Image error!", 1).show();    
55.            }    
56.        } catch (Exception e) {    
57.            Toast.makeText(AndroidTest2_3_3.this,"Newwork error!", 1).show();    
58.            e.printStackTrace();    
59.        }    
60. 
61.         
62.        // 下载图片 
63.        btnSave.setOnClickListener(new Button.OnClickListener(){ 
64.            public void onClick(View v) { 
65.                myDialog = ProgressDialog.show(AndroidTest2_3_3.this, "保存图片", "图片正在保存中,请稍等...", true); 
66.                new Thread(saveFileRunnable).start(); 
67.        } 
68.        }); 
69.             
70.    } 
71. 
72.    /**  
73.     * Get image from newwork  
74.     * @param path The path of image  
75.     * @return  
76.     * @throws Exception  
77.     */   
78.    public static byte[] getImage(String path) throws Exception{    
79.        URL url = new URL(path);    
80.        HttpURLConnection conn = (HttpURLConnection) url.openConnection();    
81.        conn.setConnectTimeout(5 * 1000);    
82.        conn.setRequestMethod("GET");    
83.        InputStream inStream = conn.getInputStream();    
84.        if(conn.getResponseCode()==200){    
85.            return readStream(inStream);    
86.        }    
87.        return null;    
88.    }    
89.   
90.    /**  
91.     * Get data from stream  
92.     * @param inStream  
93.     * @return  
94.     * @throws Exception  
95.     */   
96.    public static byte[] readStream(InputStream inStream) throws Exception{    
97.        ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
98.        byte[] buffer = new byte[1024];    
99.        int len = 0;    
100.        while( (len=inStream.read(buffer)) != -1){    
101.            outStream.write(buffer, 0, len);    
102.        }    
103.        outStream.close();    
104.        inStream.close();    
105.        return outStream.toByteArray();    
106.    }  
107. 
108.    /**
109.     * 保存文件
110.     * @param bm
111.     * @param fileName
112.     * @throws IOException
113.     */ 
114.    public void saveFile(Bitmap bm, String fileName) throws IOException { 
115.        File dirFile = new File(ALBUM_PATH); 
116.        if(!dirFile.exists()){ 
117.            dirFile.mkdir(); 
118.        } 
119.        File myCaptureFile = new File(ALBUM_PATH + fileName); 
120.        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); 
121.        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); 
122.        bos.flush(); 
123.        bos.close(); 
124.    } 
125.     
126.    private Runnable saveFileRunnable = new Runnable(){ 
127.        @Override 
128.        public void run() { 
129.            try { 
130.                saveFile(bitmap, fileName); 
131.                message = "图片保存成功!"; 
132.            } catch (IOException e) { 
133.                message = "图片保存失败!"; 
134.                e.printStackTrace(); 
135.            } 
136.            messageHandler.sendMessage(messageHandler.obtainMessage()); 
137.        } 
138.             
139.    }; 
140.     
141.    private Handler messageHandler = new Handler() { 
142.        @Override 
143.        public void handleMessage(Message msg) { 
144.            myDialog.dismiss(); 
145.            Log.d(TAG, message); 
146.            Toast.makeText(AndroidTest2_3_3.this, message, Toast.LENGTH_SHORT).show(); 
147.        } 
148.    }; 
149.     
150.} 


下载进度条的可以参考我的另外一个帖子:Android更新下载进度条

2.main.xml文件,只有一个button和一个ImageView




view plaincopy to clipboardprint?
01.<?xml version="1.0" encoding="utf-8"?> 
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
03.    android:orientation="vertical" 
04.    android:layout_width="fill_parent" 
05.    android:layout_height="fill_parent" 
06.    > 
07.    <Button 
08.        android:id="@+id/btnSave" 
09.        android:layout_width="wrap_content"  
10.        android:layout_height="wrap_content" 
11.        android:text="保存图片" 
12.        /> 
13.    <ImageView 
14.        android:id="@+id/imgSource" 
15.        android:layout_width="wrap_content"  
16.        android:layout_height="wrap_content"  
17.        android:adjustViewBounds="true" 
18.        /> 
19.</LinearLayout> 


3.在mainfest文件中增加互联网权限和写sd卡的权限




view plaincopy to clipboardprint?
01.<uses-permission android:name="android.permission.INTERNET" />  
02.<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
03.   <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> 


 

/**
  * 把Bitmap转Byte
  *
  * @Author HEH
  * @EditTime 2010-07-19 上午11:45:56
  */
 public static byte[] Bitmap2Bytes(Bitmap bm) {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
  return baos.toByteArray();
 }
预览图:

你可能感兴趣的:(android,exception,String,网络,layout,byte)