2013-01-16 61 views
3

我目前正在每24小時在後臺檢查應用程序版本,一次在我的網絡服務器不在安卓市場。如果更新可用,它提示用戶下載新的apk。從我的網站安裝Android應用程序更新

Uri uri = Uri.parse(downloadURL); 
Intent intent = new Intent(Intent.ACTION_VIEW,uri); 
startActivity(intent); 

上面的代碼打開用戶瀏覽器並開始下載。

我想不用打開瀏覽器,我需要下載apk文件或我需要直接安裝最新的APK而無需打開和其他應用程序(如瀏覽器)

回答

7

做這樣的事情

//首先你需要下載apk文件。

String extStorageDirectory =  Environment.getExternalStorageDirectory().toString(); 
     File folder = new File(extStorageDirectory, "APPS"); 
     folder.mkdir(); 
     File file = new File(folder, "AnyName."+"apk"); 
     try { 
       file.createNewFile(); 
     } catch (IOException e1) { 
       e1.printStackTrace(); 
     } 
     /** 
     * APKURL is your apk file url(server url) 
     */ 
     DownloadFile("APKURL", file); 

//的DownloadFile功能

 public void DownloadFile(String fileURL, File directory) { 
     try { 

      FileOutputStream f = new FileOutputStream(directory); 
      URL u = new URL(fileURL); 
      HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
      c.setRequestMethod("GET"); 
      //c.setDoOutput(true); 
      c.connect(); 
      InputStream in = c.getInputStream(); 
      byte[] buffer = new byte[1024]; 
      int len1 = 0; 
      while ((len1 = in.read(buffer)) > 0) { 
        f.write(buffer, 0, len1); 
      } 
      f.close(); 
    } catch (Exception e) { 
     System.out.println("exception in DownloadFile: --------"+e.toString()); 
      e.printStackTrace(); 
    } 

和下載apk文件後寫這樣的代碼

 Intent intent = new Intent(Intent.ACTION_VIEW); 
      intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/APPS/" + "AnyName.apk")), "application/vnd.android.package-archive"); 
      startActivity(intent); 

//並在清單

 <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

賦予權限它可能會幫助你,iu sed這與你的需要相同。

+0

我如何知道文件下載完成。有什麼權限需要給這 – Navaneethan

+0

@Navaneethan使用Asynch任務,在doInBackground()函數中下載apk文件並在onPostExecute()函數中編寫代碼以安裝apk文件。 onPostExecute()函數在doInBackground()完成後調用。 –

+0

@Navaneethan在上面寫入權限ie。 <使用權限android:name =「android.permission.INTERNET」/> <使用權限android:name =「android.permission.WRITE_EXTERNAL_STORAGE」/> –

相關問題