android有進度條的下載圖片並且顯示圖片

來源:互聯網
上載者:User

       最近工作不忙,感覺對progressBar不熟悉,所以決定寫一個有進度條的下載檔案例子!下面的代碼就是我寫的下載一個圖片,並且把圖片顯示出來的代碼:

layout檔案布局很簡單:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:id="@+id/bt"        android:text="開始下載檔案" />    <ProgressBar        android:id="@+id/pb"        android:layout_width="fill_parent"        style="?android:attr/progressBarStyleHorizontal"        android:layout_height="wrap_content" />    <ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/img"/></LinearLayout>

一個檔案工具類:

 

package com.spring.sky.download;import java.io.File;import android.content.Context;import android.os.Environment;import android.util.Log;/** * 檔案工具類 * @author spring sky * Email:vipa1888@163.com * QQ:840950105 * name:石明政 * */public class FileUtil {/** * 檢驗SDcard狀態 * @return boolean */public static boolean checkSDCard(){if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){return true;}else{return false;}}/** * 儲存檔案檔案到目錄 * @param context * @return  檔案儲存的目錄 */public static String setMkdir(Context context){String filePath;if(checkSDCard()){filePath = Environment.getExternalStorageDirectory()+File.separator+"myfile";}else{filePath = context.getCacheDir().getAbsolutePath()+File.separator+"myfile";}File file = new File(filePath);if(!file.exists()){boolean b = file.mkdirs();Log.e("file", "檔案不存在  建立檔案    "+b);}else{Log.e("file", "檔案存在");}return filePath;}}

 

下面就是介面上的邏輯處理:

 

 

package com.spring.sky.download;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;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.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.Toast;/** * 檔案下載介面 * @author spring sky * Email:vipa1888@163.com * QQ:840950105 * name:石明政 * */public class IndexActivity extends Activity implements OnClickListener{private static final int DOWNLOAD_PREPARE = 0;private static final int DOWNLOAD_WORK = 1;private static final int DOWNLOAD_OK = 2;private static final int DOWNLOAD_ERROR =3;private static final String TAG = "IndexActivity";private Button bt ;private ProgressBar pb;private ImageView img;/** * 需要下載的檔案 * 注意:在模擬器上面使用無法解析有網域名稱的主機 */private String url = "http://61.155.165.32/shuixiyue/pic/item/f141247490d0e96fb251b963.jpg";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);bt = (Button) this.findViewById(R.id.bt);bt.setOnClickListener(this);pb = (ProgressBar) this.findViewById(R.id.pb);pb.setVisibility(ProgressBar.INVISIBLE);img =(ImageView) this.findViewById(R.id.img);}/** * 按鈕點擊事件 */@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.bt:Toast.makeText(this, "開始下載檔案", Toast.LENGTH_SHORT).show();new Thread(){@Overridepublic void run() {downloadFile();super.run();}}.start();break;}}/** * 檔案下載 */private void downloadFile(){try {URL u = new URL(url);URLConnection conn = u.openConnection();conn.connect();InputStream is = conn.getInputStream();fileSize = conn.getContentLength();if(fileSize<1||is==null){sendMessage(DOWNLOAD_ERROR);}else{sendMessage(DOWNLOAD_PREPARE);FileOutputStream fos = new FileOutputStream(getPath());byte[] bytes = new byte[1024];int len = -1;while((len = is.read(bytes))!=-1){fos.write(bytes, 0, len);downloadSize+=len;sendMessage(DOWNLOAD_WORK);}sendMessage(DOWNLOAD_OK);is.close();fos.close();}} catch (Exception e) {sendMessage(DOWNLOAD_ERROR);e.printStackTrace();} }/** * 檔案一共的大小 */int fileSize = 0;/** * 已經下載的大小 */int downloadSize = 0;/** * handler處理訊息 */private Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case DOWNLOAD_PREPARE:Toast.makeText(IndexActivity.this, "下載準備", Toast.LENGTH_SHORT).show();pb.setVisibility(ProgressBar.VISIBLE);Log.e(TAG, "一共:"+fileSize);pb.setMax(fileSize);break;case DOWNLOAD_WORK:Log.e(TAG, "已下載:"+downloadSize);pb.setProgress(downloadSize);int res = downloadSize*100/fileSize;bt.setText("已下載:"+res+"%");break;case DOWNLOAD_OK:try {if(getPath().endsWith(".jpg")||getPath().endsWith(".png")){FileInputStream fis = new FileInputStream(getPath());img.setImageBitmap(BitmapFactory.decodeStream(fis));}downloadSize = 0;fileSize = 0;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}Toast.makeText(IndexActivity.this, "下載完成", Toast.LENGTH_SHORT).show();break;case DOWNLOAD_ERROR:Toast.makeText(IndexActivity.this, "下載出錯", Toast.LENGTH_SHORT).show();break;}super.handleMessage(msg);}};/** * 得到檔案的儲存路徑 * @return * @throws IOException */private String getPath() throws IOException{String path = FileUtil.setMkdir(this)+File.separator+url.substring(url.lastIndexOf("/")+1);return path;}/** * 給hand發送訊息 * @param what */private void sendMessage(int what){Message m = new Message();m.what = what;handler.sendMessage(m);}}

以上就是一個檔案下載的完整代碼,有需要這方面的朋友可以直接拷貝使用了!如果使用過程中有問題,可以聯絡我!

 

一位朋友提醒我了,這個下載過程需要兩個許可權,不然對新手來說,很困惑的!具體的許可權如下:

 
<!-- Internet許可權 --><uses-permission android:name="android.permission.INTERNET"></uses-permission><!--可訪問SD卡--><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

 

 具體的代碼:http://download.csdn.net/detail/vipa1888/4028594    以後我提倡代碼共用,也不會要積分的!我準備修改不要積分的  修改不了!請大家諒解!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.