一、使用HttpURLConnection下载并更新
1、下载APK文件
private File download() {
try {
URL url = new URL("要下载apk文件的路径");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
InputStream inputStream = null;
Log.e("------->","connection.getResponseCode()"+connection.getResponseCode());
if (connection.getResponseCode() == 200) {
int fileSize = connection.getContentLength() / 1024;
Log.e("------->","fileSize"+fileSize);
progressDialog.setMax(fileSize);
int totla = 0;
inputStream = connection.getInputStream();
File file = new File(SAVE_PATH);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
fos.write(bytes, 0, len);
totla += (len / 1024);
progressDialog.setProgress(totla);
}
//别忘了刷新哈
fos.flush();
fos.close();
inputStream.close();
progressDialog.dismiss();
return file;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
2、安装apk文件
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
//下载的apk文件(download方法返回的File文件)
intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
startActivity(intent);
二、使用DownLoadManager下载并更新
利用这个DownLoadManager方法下载,会以通知的方式显示,所以应用到广播来通知下载完毕。
1、使用DownLoadManager下载文件,并将downLoadID存到本地
public class DownloadAppUtils {
private static final String TAG = DownloadAppUtils.class.getSimpleName();
public static long downloadUpdateApkId = -1;//下载更新Apk 下载任务对应的Id
public static String downloadUpdateApkFilePath;//下载更新Apk 文件路径
/**
* 通过浏览器下载APK包
* @param context
* @param url
*/
public static void downloadForWebView(Context context, String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp.apk")),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
/**
* 下载更新apk包
* 权限:1,<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
* @param context
* @param url
*/
public static void downloadForAutoInstall(Context context, String url, String fileName, String title) {
if (TextUtils.isEmpty(url)) {
return;
}
try {
Uri uri = Uri.parse(url);
DownloadManager downloadManager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//在通知栏中显示
request.setVisibleInDownloadsUi(true);
request.setTitle(title);
String filePath = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//外部存储卡
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
return;
}
downloadUpdateApkFilePath = filePath + File.separator + fileName;
// 若存在,则删除
deleteFile(downloadUpdateApkFilePath);
Uri fileUri = Uri.parse("file://" + downloadUpdateApkFilePath);
request.setDestinationUri(fileUri);
downloadUpdateApkId = downloadManager.enqueue(request);
} catch (Exception e) {
e.printStackTrace();
downloadForWebView(context, url);
}
}
private static boolean deleteFile(String fileStr) {
File file = new File(fileStr);
return file.delete();
}
}
2、定义广播
public class ApkInstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Cursor c=null;
try {
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
if (DownloadAppUtils.downloadUpdateApkId >= 0) {
long downloadId = DownloadAppUtils.downloadUpdateApkId;
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
DownloadManager downloadManager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
c = downloadManager.query(query);
if (c.moveToFirst()) {
int status = c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_FAILED) {
downloadManager.remove(downloadId);
} else if (status == DownloadManager.STATUS_SUCCESSFUL) {
if (DownloadAppUtils.downloadUpdateApkFilePath != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(
Uri.parse("file://"
+ DownloadAppUtils.downloadUpdateApkFilePath),
"application/vnd.android.package-archive");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
PreferenceFlag.getInstance().setRedDotFlag(false);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (c != null) {
c.close();
}
}
}
}
3、在AndroidManifest中注册广播(两种方式)
方式一:
<receiver android:name=".receiver.ApkInstallReceiver">
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
方式二:
ApkInstallReceiver receiver = new ApkInstallReceiver();
IntentFilter intent = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, intent);