【问题标题】:Programatically install .apk file located in /res/raw以编程方式安装位于 /res/raw 中的 .apk 文件
【发布时间】:2014-01-27 22:17:42
【问题描述】:

我在 /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);

但是,当 Intent 运行时,我收到 Parse 错误:There is a problem parsing the package.

.apk 文件是 eclipse 在我运行其他应用程序时在 /bin 目录中创建的文件。

我将如何正确完成这个程序化本地安装?

【问题讨论】:

    标签: android


    【解决方案1】:

    我想通了。我最终将我的 .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
    }
    

    希望这可以帮助其他有类似问题的人!

    【讨论】:

    • 谢谢!但最好使用 Environment.getExternalStorageDirectory() 而不是硬编码“/sdcard”
    【解决方案2】:
    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);
    

    【讨论】:

      【解决方案3】:

      在清单文件中也添加一项权限

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

      否则会出现“权限被拒绝”错误。

      【讨论】:

        猜你喜欢
        • 2019-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        相关资源
        最近更新 更多