2012-07-30 62 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" /> 

否则拒绝“权限”错误发生。