我們在開發中經常需要從服務器下載文件,下載的內容可能有交換的信息,緩存的圖片,程序更新包等。我們使用URLConnection來實現下載。先看幾行代碼:
URL url=new URL(urls);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();//建立連接
conn.setConnectTimeout(5000);//設置等待時間
fileSize =conn.getContentLength();//獲取文件的長度
InputStream is=conn.getInputStream();//獲取輸入流
FileOutputStream fos=new FileOutputStream(file);
byte[] buffer =new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){//將文件下載到指定目錄中
fos.write(buffer,0,len);
downloadSize += len;//獲取當前下載的長度
Message msg=new Message();
Log.i(TAG,downloadSize+" "+fileSize);
// msg.what=1;
msg.what= downloadSize * 100 / fileSize;
Log.i("downloadSize",msg.what+"");
handler.sendMessage(msg);//向handle進行傳值
}
fos.flush();
fos.close();
is.close();
下載文件很簡單,主要是和通知欄建立聯繫 這就需要用到Handle 通過Handle可以對通知欄進行刷新,並且還可以傳遞下載進度。
DownActivity.java 主程序
DownUtil .java 設置、刷新通知欄進度
FileDownloadThread .java 下載附件
在DownActivity中我們只需要設置下載文件的文件名、存儲地址和下載地址就可以
DownActivity.java
public class DownActivity extends Activity {
Button btn;
public String downloadDir;//文件的存儲路徑
public String downloadUrl;//文件的下載地址
private String fileName;//下載文件名
Down down;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//從網上隨便找的一個APK下載地址
downloadUrl = "http://activitymo.homelink.com.cn/download/homelink/android/Android_homelinkfanstong1.apk";
down = new Down(DownActivity.this);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
download();
}
});
}
/**
* 下載附件
*/
public void download(){
downloadDir= Environment.getExternalStorageDirectory()+"/taotao/attach";
File file=new File(downloadDir);
//如果文件夾不存在 則重建
if(!file.exists()){
file.mkdirs();
}
//返回最後一個“/”後一個字符的位置int值
int filestart=downloadUrl.lastIndexOf("/");
//截取()之後的字符
fileName=downloadUrl.substring(filestart+1);
// downloadProgressBar.setVisibility(View.VISIBLE);
// downloadProgressBar.setProgress(0);
down.downloadTask(downloadUrl, downloadDir, fileName);
}
}
接下來就是通知欄下載進度條、通知欄刷新這個放在一個工具類中
DownUtil .java
public class DownUtil {
private String fileName;//下載文件名
private String paths;//文件地址
private Context context;
public DownUtil(Context context){
this.context = context;
}
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
//當收到更新視圖消息時,計算以完成下載百分比,同時個in關心進度條信息
//通知欄功能的實現
String ns = Context.NOTIFICATION_SERVICE;
//初始化通知管理
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(ns);
//創建Notification對象
Notification notification = new Notification();
int progress = msg.what;
if (progress == -1) {
notification.contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
notification.contentView.setProgressBar(R.id.ProgressBar01, 100, progress, false);
notification.contentView.setTextViewText(R.id.TextView01, "下載失敗");
notification.contentView.setTextViewText(R.id.TextView03, progress + "%");
notification.contentView.setTextViewText(R.id.TextView02, fileName+"下載");
notification.icon = R.mipmap.ic_launcher;
mNotificationManager.notify(1, notification);
} else {
if (progress <= 100) {
notification.contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
notification.contentView.setProgressBar(R.id.ProgressBar01, 100, progress, false);
notification.contentView.setTextViewText(R.id.TextView03, progress + "%");
notification.contentView.setTextViewText(R.id.TextView02, fileName+"下載");
notification.icon = R.mipmap.ic_launcher_icon;
mNotificationManager.notify(1, notification);
}
if (progress == 100) {
//定義通知欄展現的內容信息
notification.icon = R.mipmap.ic_launcher_icon;
notification.tickerText = fileName+"下載完成";
notification.defaults = Notification.DEFAULT_VIBRATE;
//定義下拉通知欄時要展現的內容信息
// Context context = getApplicationContext();
CharSequence contentTitle = fileName+"下載完成";
CharSequence contentText = "淘淘:" + fileName;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = AndroidFileUtil.openFile(new File(paths));
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
//用mNotificationManager的notify方法通知用戶生成標題欄消息通知
mNotificationManager.notify(1, notification);
}
}
}
};
/**
* 線程下載開始
*
* **/
public void downloadTask(String urlStr,String dirPath,String fileName){
this.fileName = fileName;
Message msg = new Message();
msg.what = 0;
handler.sendMessage(msg);
paths=dirPath+fileName;
File file=new File(dirPath + fileName);
//如果文件已存在 則先刪除 後下載
if(file.exists()){
file.delete();
}
//啓動線程,文件
FileDownloadThread fdt=new FileDownloadThread(urlStr,file,handler);
fdt.setName("thread");
fdt.start();
}
}
最後就是下載文件的工具類
FileDownloadThread .java
/**
* 下載文件
* @author Administrator
*
*/
public class FileDownloadThread extends Thread {
private static final int BUFFER_SIZE = 1024;
private static final String TAG = "FileDownloadThread";
private String urls;
private File file;
private int curPosition;
private int fileSize;
//用於標識當前線程是否下載完成
private boolean finished=false;
private int downloadSize=0;
private Handler handler;
/**
*
* @param url 下載地址
* @param file
*/
public FileDownloadThread(String urls,File file,Handler handler){
this.urls=urls;
this.file=file;
this.handler = handler;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
URL url=new URL(urls);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
fileSize =conn.getContentLength();
InputStream is=conn.getInputStream();//獲取輸入流
Log.i("file",file+"");
FileOutputStream fos=new FileOutputStream(file);
byte[] buffer =new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
downloadSize += len;
Message msg=new Message();
Log.i(TAG,downloadSize+" "+fileSize);
// msg.what=1;
msg.what= downloadSize * 100 / fileSize;
Log.i(“downloadSize”,msg.what+”“);
handler.sendMessage(msg);
}
fos.flush();
fos.close();
is.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
xml文件我就寫通知欄的佈局
notification.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:id="@+id/relayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:src="@mipmap/ic_launcher" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/relayout"
android:layout_alignTop="@+id/relayout"
android:layout_marginRight="10dp"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:layout_toRightOf="@+id/relayout"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="正在下載 ..."
android:textSize="18sp" >
</TextView>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文件名。。。。" >
</TextView>
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="0%" >
</TextView>
</RelativeLayout>
<ProgressBar
android:id="@+id/ProgressBar01"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
</RelativeLayout>