从java代码卸载apk文件

时间:2013-08-05 14:53:51

标签: java android

我需要根据服务器的最新版本卸载并重新安装apk文件。当我没有在Google Play中更新我的应用程序时,如何卸载并重新安装该应用程序?我的卸载代码:

public void UnInstallApplication(String packageName)// Passing com.example.homelauncher as package name.
    {

        Uri packageURI = Uri.parse(packageName.toString());
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(uninstallIntent); 
    }

我收到以下错误:

08-05 20:07:29.670: E/AndroidRuntime(845): FATAL EXCEPTION: main
08-05 20:07:29.670: E/AndroidRuntime(845): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.DELETE dat=com.example.homelauncher flg=0x10000000 }
08-05 20:07:29.670: E/AndroidRuntime(845):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1409)
08-05 20:07:29.670: E/AndroidRuntime(845):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1379)
08-05 20:07:29.670: E/AndroidRuntime(845):  at android.app.Activity.startActivityForResult(Activity.java:2827)
08-05 20:07:29.670: E/AndroidRuntime(845):  at android.app.Activity.startActivity(Activity.java:2933)
08-05 20:07:29.670: E/AndroidRuntime(845):  at com.example.homelauncher.MainActivity.UnInstallApplication(MainActivity.java:246)
08-05 20:07:29.670: E/AndroidRuntime(845):  at com.example.homelauncher.MainActivity$2$1.onClick(MainActivity.java:152)
08-05 20:07:29.670: E/AndroidRuntime(845):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
08-05 20:07:29.670: E/AndroidRuntime(845):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 20:07:29.670: E/AndroidRuntime(845):  at android.os.Looper.loop(Looper.java:123)
08-05 20:07:29.670: E/AndroidRuntime(845):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-05 20:07:29.670: E/AndroidRuntime(845):  at java.lang.reflect.Method.invokeNative(Native Method)
08-05 20:07:29.670: E/AndroidRuntime(845):  at java.lang.reflect.Method.invoke(Method.java:507)
08-05 20:07:29.670: E/AndroidRuntime(845):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-05 20:07:29.670: E/AndroidRuntime(845):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-05 20:07:29.670: E/AndroidRuntime(845):  at dalvik.system.NativeStart.main(Native Method)

有人可以告诉我如何在不使用Google Play的情况下执行此操作吗?

2 个答案:

答案 0 :(得分:1)

您正在形成URI错误。有关相关问题,请参阅this SO post(几乎一式两份)。我已经复制了下面的相关细节:基本上你需要使用以下代码来构造URI以使intent方法起作用。

Intent intent = new Intent(Intent.ACTION_DELETE, Uri.fromParts("package",
getPackageManager().getPackageArchiveInfo(apkUri.getPath(), 0).packageName,null));
startActivity(intent);

答案 1 :(得分:0)

如果您的设备是rootet,则可以使用Android Linux shell中执行的adb命令卸载apk。

String command = "pm uninstall com.my.first.program ";