一、使用HttpURLConnection下載下傳并更新
1、下載下傳APK檔案
private File download() {
try {
URL url = new URL("要下載下傳apk檔案的路徑");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout();
connection.setRequestMethod("GET");
InputStream inputStream = null;
Log.e("------->","connection.getResponseCode()"+connection.getResponseCode());
if (connection.getResponseCode() == ) {
int fileSize = connection.getContentLength() / ;
Log.e("------->","fileSize"+fileSize);
progressDialog.setMax(fileSize);
int totla = ;
inputStream = connection.getInputStream();
File file = new File(SAVE_PATH);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[];
int len = ;
while ((len = inputStream.read(bytes)) != -) {
fos.write(bytes, , len);
totla += (len / );
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 = -;//下載下傳更新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 >= ) {
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);