install / uninstall APKs programmatically (PackageManager vs Intents)

后端 未结 10 2020
时光取名叫无心
时光取名叫无心 2020-11-22 13:53

My application installs other applications, and it needs to keep track of what applications it has installed. Of course, this could be achieved by simply keeping a list of i

10条回答
  •  粉色の甜心
    2020-11-22 14:21

    API level 14 introduced two new actions: ACTION_INSTALL_PACKAGE and ACTION_UNINSTALL_PACKAGE. Those actions allow you to pass EXTRA_RETURN_RESULT boolean extra to get an (un)installation result notification.

    Example code for invoking the uninstall dialog:

    String app_pkg_name = "com.example.app";
    int UNINSTALL_REQUEST_CODE = 1;
    
    Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);  
    intent.setData(Uri.parse("package:" + app_pkg_name));  
    intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
    startActivityForResult(intent, UNINSTALL_REQUEST_CODE);
    

    And receive the notification in your Activity#onActivityResult method:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UNINSTALL_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Log.d("TAG", "onActivityResult: user accepted the (un)install");
            } else if (resultCode == RESULT_CANCELED) {
                Log.d("TAG", "onActivityResult: user canceled the (un)install");
            } else if (resultCode == RESULT_FIRST_USER) {
                Log.d("TAG", "onActivityResult: failed to (un)install");
            }
        }
    }
    

提交回复
热议问题