最近工作不忙,感覺對progressBar不熟悉,所以決定寫一個有進度條的下載文件例子!下面的代碼就是我寫的下載一個圖片,並且把圖片顯示出來的代碼:
layout文件佈局很簡單:
[html]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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>
一個文件工具類:
[java]
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;
}
}
下面就是界面上的邏輯處理:
[java]
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 = "/wp-content/images1/20181005/f141247490d0e96fb251b963201.jpg";
@Override
protected 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);
}
/**
* 按鈕點擊事件
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt:
Toast.makeText(this, "開始下載文件", Toast.LENGTH_SHORT).show();
new Thread(){
@Override
public 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(){
@Override
public 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發送消息 www.aiwalls.com
* @param what
*/
private void sendMessage(int what)
{
Message m = new Message();
m.what = what;
handler.sendMessage(m);
}
}
以上就是一個文件下載的完整代碼,有需要這方面的朋友可以直接拷貝使用瞭!如果使用過程中有問題,可以聯系我!
摘自 spring sky