android下載文件到應用的文件目錄并安裝
在進行應用開發時,我們的產品需要升級,如果升級的產品放在服務器上我們就需要下載,并進行安裝。一般可以選擇下載到sd卡中進行安裝,
但是對于沒有sd卡的設備進行安裝升級怎么辦,
本文提供了一種方法,將下載的文件放到應用文件目錄下然后通過設置為Context.MODE_WORLD_READABLE,讓安裝程序可以有權限安裝此文件。
下載代碼如下:
path:網絡url
apkname:你希望保存的文件名稱
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(); }
}</pre>
啟動安裝程序:
apkname:是保存文件時的文件名,
在需要進行升級的地方調用下面函數即可。
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卡的條件下也可以順利的升級自己的應用程序了。
本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!