如何以编程方式从服务安装APK

时间:2013-05-03 07:40:51

标签: android install apk

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

这是在这里找到的: Question [4967669] android-install-apk-programmatically

使用Android 服务如果这样做,我收到以下错误消息:

  

05-03 08:24:14.559:E / AndroidRuntime(21288):致命异常:   Thread-1706 05-03 08:24:14.559:E / AndroidRuntime(21288):   android.util.AndroidRuntimeException:从中调用startActivity()   在Activity上下文之外需要FLAG_ACTIVITY_NEW_TASK   旗。这真的是你想要的吗?

我添加了FLAG_ACTIVITY_NEW_TASK:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

但现在没有任何反应。没有错误但也没有尝试安装apk。 我想这可能是因为它没有活动(因为它是一项服务)?

问题 是否可以通过Android后台服务安装APK? (如果是的话)任何一个人怎么办?

先谢谢

PS:根据我对服务的理解,他们非常喜欢活动,所以不确定为什么这不起作用。

1 个答案:

答案 0 :(得分:3)

您可以从后台服务安装APK。 尝试使用Uri.parse代替Uri.fromFile

        File apkfile = new File(Environment.getExternalStorageDirectory() +
                  "/download/" + "app.apk");
        if (!apkfile.exists()) {
            return;
        }
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        installIntent.setDataAndType(
                Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        startActivity(installIntent);