2012-07-30 63 views
2

我已將另一個應用程序的.apk文件存儲在我的/ res/raw目錄中,並希望爲用戶提供安裝提示。這裏是我當前的代碼:以編程方式安裝位於/ res/raw的.apk文件

Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(new File("android.resource://" + getPackageName() + "/res/raw/myapk.apk")), "application/vnd.android.package-archive"); 
startActivity(intent); 

然而,當意圖運行,我得到一個解析錯誤:There is a problem parsing the package.

的.apk文件是在Eclipse中/ bin目錄下創建當我運行其他的一個應用。

我該如何正確完成本地編程的本地安裝?

回答

6

我想通了。我最終將我的.apk文件放在/ assets目錄下,並以編程方式將其複製到安裝它的sd卡中。這裏是我的代碼:

AssetManager assetManager = getAssets(); 
InputStream in = null; 
OutputStream out = null; 
try { 
    in = assetManager.open("myapk.apk"); 
    out = new FileOutputStream("/sdcard/myapk.apk"); 
    byte[] buffer = new byte[1024]; 
    int read; 
    while((read = in.read(buffer)) != -1){ 
     out.write(buffer, 0, read); 
    } 
    in.close(); 
    in = null; 
    out.flush(); 
    out.close(); 
    out = null; 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(new File("/sdcard/myapk.apk")), "application/vnd.android.package-archive"); 
    startActivity(intent); 
}catch(Exception e){ 
    // deal with copying problem 
} 

希望這會幫助別人提出類似的問題!

+0

謝謝!但更好地使用Environment.getExternalStorageDirectory()而不是硬編碼「/ sdcard」 – ligi 2014-01-27 10:52:26

0
String path = "file:///android_asset/raw/myapk.apk"; 

Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive"); 
startActivity(intent); 
+0

我試過了,但我仍然得到相同的分析錯誤。 – 2012-07-30 18:32:04

0

還增加一個許可清單文件

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

否則拒絕「權限」錯誤發生。