天天看點

Android中下載下傳進度條格式,android帶進度條的大檔案下載下傳代碼

package com.example.download_test;

import org.json.JSONObject;

import cn.trinea.android.common.util.DownloadManagerPro;

import cn.trinea.android.common.util.PackageUtils;

import android.app.Activity;

import android.app.AlertDialog;

import android.app.AlertDialog.Builder;

import android.app.DownloadManager;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.ProgressDialog;

import android.app.Service;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.graphics.Paint.Join;

import android.net.Uri;

import android.os.Handler;

import android.os.IBinder;

import android.os.Message;

import android.widget.Toast;

public class CheckVersion extends Service {

NotificationManager mNotificationManager;//聲明通知欄manager

public static DownloadManager downloadManager;//用于給别的類擷取id用的超全局下載下傳管理類

//用來标志現在是否已經有對話框浮出的狀态

boolean boxFlag=false;

//下載下傳檔案的路徑

public static String URL = "http://192.168.1.112:8080/auto_serve/weichat.apk";

//擷取新版本号的位址

public static String VERSION_URL = "http://192.168.1.112:8080/auto_serve/version_code.txt";

//聲明進度條對話框

ProgressDialog mReadProcessDia=null;

//設定最大進度

public final static int MAX_READPROCESS = 100;

//設定用于彈出對話框的activity對象

public Context context =  MainActivity.SUPERCONTEXT;

class versionHandler extends Handler{

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

//如果收到的是更新進度條的message

if(msg.arg1==222){

System.out.println("收到進度"+msg.arg2);

//進度條對話框更新進度

mReadProcessDia.setProgress(msg.arg2);

return;

}

//如果收到的是提示更新的message

Toast.makeText(getApplicationContext(), "發現新版本", Toast.LENGTH_SHORT).show();

//蹦出通知對話框

if(boxFlag==false){

AlertDialog.Builder normalDia =new AlertDialog.Builder(context);

normalDia.setIcon(R.drawable.ic_launcher);

normalDia.setTitle("新版本提示");

normalDia.setCancelable(false);

normalDia.setMessage("有新版本了,是否更新");

normalDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

System.out.println("點選了确定");

boxFlag=true;//禁止彈出新的對話框

//初始化進度條對話框

mReadProcessDia=new ProgressDialog(context);

mReadProcessDia.setProgress(0);

mReadProcessDia.setIndeterminate(false);

mReadProcessDia.setCancelable(false);//設定進度條對話框是否可以被點沒,如果為true,相當于背景下載下傳,完畢後不受影響

mReadProcessDia.setTitle("下載下傳進度");

mReadProcessDia.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

mReadProcessDia.setMax(MAX_READPROCESS);

mReadProcessDia.show();

new Thread(downloadRunnable).start();//啟動下載下傳子線程

}

});

normalDia.setNegativeButton("取消", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

System.out.println("點選了取消");

boxFlag=false;//後面可以繼續彈出新對話框

}

});

if(boxFlag==false){

normalDia.create().show();

boxFlag=true;//禁止再彈出對話框

}

}

if(mNotificationManager==null){//通知欄提示隻顯示一次

mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//設定通知欄的圖示

int icon = R.drawable.ic_launcher;

//通知欄的浮現文本

CharSequence tickerText = "發現新版本";

long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);

//定義下拉通知欄時要展現的内容資訊

Context context = getApplicationContext();

CharSequence contentTitle = "汽車報價大全發現新版本";

CharSequence contentText = "點選此處自動更新";

Intent notificationIntent = new Intent(CheckVersion.this, MainActivity.class);

PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText,contentIntent);

//用mNotificationManager的notify方法通知使用者生成标題欄消息通知

mNotificationManager.notify(1, notification);

}

}

}

//聲明handler

versionHandler handler1 = new versionHandler();

//下載下傳子線程的方法

Runnable downloadRunnable = new Runnable() {

public void run() {

System.out.println("下載下傳線程已啟動");

downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);

//設定下載下傳位址

String apkUrl = URL;

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));

//設定下載下傳路徑和檔案名,不要忘了開啟寫儲存設備權限

request.setDestinationInExternalPublicDir("Trinea", "MeiLiShuo.apk");//表示設定下載下傳位址為sd卡的Trinea檔案夾,檔案名為MeiLiShuo.apk。其他設定下載下傳路徑接口為setDestinationUri,setDestinationInExternalFilesDir,setDestinationToSystemCache。其中setDestinationToSystemCache僅限系統app使用。

//魅族手機在通知欄不會有提示,其他的好像都行

request.setTitle("汽車報價正在下載下傳");//設定下載下傳中通知欄提示的标題

request.setDescription("新版2.0");//設定下載下傳中通知欄提示的介紹

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//表示下載下傳進行中和下載下傳完成的通知欄是否顯示。預設隻顯示下載下傳中通知。VISIBILITY_VISIBLE_NOTIFY_COMPLETED表示下載下傳完成後顯示通知欄提示。VISIBILITY_HIDDEN表示不顯示任何通知欄提示,這個需要在AndroidMainfest中添權重限android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.

//request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);//表示下載下傳允許的網絡類型,預設在任何網絡下都允許下載下傳。有NETWORK_MOBILE、NETWORK_WIFI、NETWORK_BLUETOOTH三種及其組合可供選擇。如果隻允許wifi下載下傳,而目前網絡為3g,則下載下傳會等待。

//request.setAllowedOverRoaming(boolean allow)移動網絡情況下是否允許漫遊。

//request.setMimeType("application/cn.trinea.download.file");//設定下載下傳檔案的mineType。因為下載下傳管理Ui中點選某個已下載下傳完成檔案及下載下傳完成點選通知欄提示都會根據mimeType去打開檔案,是以我們可以利用這個屬性。比如上面設定了mimeType為application/cn.trinea.download.file,我們可以同時設定某個Activity的intent-filter為application/cn.trinea.download.file,用于響應點選的打開檔案。

//request.addRequestHeader(String header, String value)// 添加請求下載下傳的網絡連結的http頭,比如User-Agent,gzip壓縮等

//擷取該下載下傳的标示id

long downloadId = downloadManager.enqueue(request);

DownloadManagerPro downloadManagerPro = new DownloadManagerPro(downloadManager);

//用于更新進度條的方法,一秒更新五次

while(1==1){

try {

Thread.sleep(200);//設定更新頻率

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

//獲得下載下傳進度資訊

int[] bytesAndStatus = downloadManagerPro.getBytesAndStatus(downloadId);

//[0]是已經下載下傳的大小,[1]是總大小,[2]是網絡環境,2是聯網,4是斷網

int progress = 0;

try {//可能會有除以0異常

progress = bytesAndStatus[0]/(bytesAndStatus[1]/100);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Message message = Message.obtain();

message.arg1=222;

message.arg2=progress;

handler1.sendMessage(message);//發送給handler更新進度條

//如果下載下傳完畢,關閉進度條和該線程

if(bytesAndStatus[0]==bytesAndStatus[1]){

mReadProcessDia.cancel();

break;

}

}

};

};

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// TODO Auto-generated method stub

System.out.println("服務開啟");

new Thread(){

@Override

public void run() {

// TODO Auto-generated method stub

while(1==1){//不停地聯網檢查有無新版本并和現有版本比較

try {

//從伺服器擷取json并解析出新版本号,這裡可以靈活處理

String versionJson = GetCarBrands.net(VERSION_URL, null, null);

JSONObject jsonObject = new JSONObject(versionJson);

int newVersion = jsonObject.getInt("version");

//請靈活處理

System.out.println("新版本是"+newVersion);

//擷取現在的版本号

int oldVersion = PackageUtils.getAppVersionCode(getApplicationContext());

System.out.println("舊版本是"+oldVersion);

if(newVersion>oldVersion){

System.out.println("該更新了!!!");

Message message = Message.obtain();

message.arg1=1;

if(boxFlag==false)//如果現在可以彈出對話框,就向handler發出更新ui的通知

handler1.sendMessage(message);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

Thread.sleep(90000);//設定通路伺服器擷取版本号的頻率

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}.start();

return super.onStartCommand(intent, flags, startId);

}

@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

return null;

}

}