2011-03-25 100 views
6

我想從我的應用程序安裝apk文件。如何以編程方式安裝apk文件

我已經創建了一個包含一個按鈕,當我點擊該按鈕,然後,我存儲在資源文件夾中其他APK 應安裝一個應用程序,
下面有東西,我已經做了:

public void onClick(View v) { 
    // Intent intent = new Intent("com.google.zxing.client.android.SCAN"); 
    // intent.setPackage("com.google.zxing.client.android"); 
    // intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); 
    // startActivityForResult(intent, 0); 
    File file = new File("android.resource://com.app.barcodescanner/raw", "scan.apk"); 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); 
    startActivity(intent); 
} 

任何想法?
請幫我這個

回答

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

以編程方式將第一個apk文件複製到sd卡,然後執行上述步驟 – sUrAj 2011-04-06 10:10:53

+1

這會創建一個提示讓用戶接受嗎?如果是,是否有避免它的解決方法? – 2014-08-21 17:40:49

+0

安裝完成後可以重新打開嗎? – zionpi 2015-06-30 09:49:49

2

它可能不會與android.resourceUri。嘗試將APK複製到外部存儲並從那裏進行安裝。

+0

我有一個簡單的問題。我從網上下載我的apk並更新下載的apk。現在我想知道我將如何同步兩者,意味着進度條需要同時顯示下載和上傳活動。幫助我在這 – AndroidOptimist 2014-03-04 06:28:13

+0

@AndroidOptimist:如果「上傳活動」確實意味着「更新活動」,那是不可能的。當您的應用程序正在更新時,您的程序將不會運行。而且,在更新開始之前,您的用戶界面將不可見,因爲*用戶*必須開始更新,*用戶*必須批准更新。 – CommonsWare 2014-03-04 12:00:52

0
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    File DbFile=new File("mnt/sdcard/HelloAndroid.apk"); 
    if(!(DbFile.exists())) 
    { 
     try 
     { 
      int length = 0; 
      DbFile.createNewFile(); 
      InputStream inputStream = this.getAssets().open("HelloAndroid.apk"); 
      FileOutputStream fOutputStream = new FileOutputStream(DbFile); 
      byte[] buffer = new byte[inputStream.available()]; 
      while ((length = inputStream.read(buffer)) > 0) 
      { 
       fOutputStream.write(buffer, 0, length); 
      } 
      fOutputStream.flush(); 
      fOutputStream.close(); 
      inputStream.close(); 
     } 
     catch (Exception ex) 
     { 
      System.out.println("Error in creating new database at mobile..." + ex); 
      ex.printStackTrace(); 
     } 
    } 

    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/HelloAndroid.apk")), "application/vnd.android.package-archive"); 
    startActivity(intent); 
} 

在這裏,我已經存儲在資產的文件夾我的apk文件。你可以試試這個。

+0

爲什麼不只是'intent.setDataAndType(Uri.fromFile(DbFile)),「application/vnd.android.package-archive」)'? – Pierre 2015-03-14 09:21:10