SDK在API Level 9中加入了DownloadManager服务,可以将长时间的下载任务交给系统,完全由系统管理。

直接看实例代码:

import java.io.File;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.quma.core.Attribute;
import com.quma.db.DaoManager;
import com.quma.db.DatabaseOpenHelper;
import com.quma.db.DatabaseOpenHelper.WritableHandler;
import com.quma.db.entity.Upgrade;
import com.quma.webservice.ServiceManager;
import com.quma.webservice.constants.UpgradeStatus;

/**
*
* @company qq:176291935
* @author iaiai
* @version
* @date 2015-5-27 下午12:15:41
*/
public class UpgradeService extends Service {

private File updateDir; //目录

private File updateFile; //文件

private String fileName; //文件名

/** 安卓系统下载类 **/
DownloadManager manager;

/** 接收下载完的广播 **/
DownloadCompleteReceiver receiver;

/** 初始化下载器 **/
private void initDownManager() {
manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
receiver = new DownloadCompleteReceiver();

//设置下载地址
DownloadManager.Request down = new DownloadManager.Request(Uri.parse("http://www.xxx.com/xx.apk"));

// 设置允许使用的网络类型,这里是移动网络和wifi都可以
down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);

// 下载时,通知栏显示途中
// down.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
down.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

// 显示下载界面
down.setVisibleInDownloadsUi(true);

// 设置下载后文件存放的位置
down.setDestinationUri(Uri.fromFile(updateFile));

down.setTitle("趣马养车");
down.setDescription("下载更新");

// 将下载请求放入队列
manager.enqueue(down);

//注册下载广播
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//创建文件
if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
updateDir = new File("/sdcard/download");
fileName = "temp.apk";
updateFile = new File(updateDir.getPath(),fileName);
}

// 调用下载
initDownManager();

return START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onDestroy() {
// 注销下载广播
if (receiver != null)
unregisterReceiver(receiver);

super.onDestroy();
}

// 接受下载完成后的intent
private class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//判断是否下载完成的广播
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
DatabaseOpenHelper.writableDatabase(UpgradeService.this, new WritableHandler() {
@Override
public void exec(SQLiteDatabase db) {
Upgrade upgrade = DaoManager.getUpgradeDao().query(db, appid);
if(upgrade!=null){
upgrade.setStatus(UpgradeStatus.下载完成.getVal());
DaoManager.getUpgradeDao().update(db, upgrade);
}
}
});

//获取下载的文件id
long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

//自动安装apk
installAPK(manager.getUriForDownloadedFile(downId));

//停止服务并关闭广播
UpgradeService.this.stopSelf();
}
}

/**
* 安装apk文件
*/
private void installAPK(Uri apk) {
// 通过Intent安装APK文件
Intent intents = new Intent();

intents.setAction("android.intent.action.VIEW");
intents.addCategory("android.intent.category.DEFAULT");
intents.setType("application/vnd.android.package-archive");
intents.setData(apk);
intents.setDataAndType(apk,"application/vnd.android.package-archive");
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// android.os.Process.killProcess(android.os.Process.myPid());
// 如果不加上这句的话在apk安装完成之后点击单开会崩溃
startActivity(intents);
}

}

}