[html]
<pre name="code" class="html">
在進行應用開發時,我們的產品需要升級,如果升級的產品放在服務器上我們就需要下載,並進行安裝。一般可以選擇下載到sd卡中進行安裝,
但是對於沒有sd卡的設備進行安裝升級怎麼辦,
本文提供瞭一種方法,將下載的文件放到應用文件目錄下然後通過設置為Context.MODE_WORLD_READABLE,讓安裝程序可以有權限安裝此文件。
下載代碼如下:
path:網絡url
apkname:你希望保存的文件名稱
[java]
public void downloadApktoappDir(String path,String apkname) throws IOException{
URL url;
FileOutputStream fos = null;
BufferedInputStream bis = null;
InputStream is = null;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
// 獲取到文件的大小
int size = conn.getContentLength();
is = conn.getInputStream();
fos = openFileOutput(apkname,
Context.MODE_WORLD_READABLE);
bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
int total = 0;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
// 獲取當前下載量
total += len;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
fos.close();
bis.close();
is.close();
}
}
啟動安裝程序:
apkname:是保存文件時的文件名,
在需要進行升級的地方調用下面函數即可。
[html]
public void installApkFromLocalPath(String apkname){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//first method
intent.setDataAndType(
Uri.parse("file://"+getApplicationContext().getFilesDir().getAbsolutePath() + "/" + apkname),
"application/and.android.package-archive");
startActivity(intent);
//second method
// intent.setDataAndType(
// Uri.fromFile(
// new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/" + apkname)),
// "application/and.android.package-archive");
// startActivity(intent);
}
這樣就可以實現再沒有sd卡的條件下也可以順利的升級自己的應用程序瞭。
摘自 weidawei0609的專欄