如何得到 android 安装程序的响应(apk 是否安装成功)?

How to get response from android installer (whether the apk is installed successfully or not)?

我正在开发一个 android 应用程序(充当控制器),它将触发 android 安装程序来安装我的其他应用程序的 apk。我已经通过以下代码从我的应用程序启动了安装过程。

Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uri = FileProvider.getUriForFile(context, "com.example.android.fileprovider", updated_app_apk_file);
                intent.setDataAndType(uri,"application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                Uri apkUri = Uri.fromFile(updated_app_apk_file);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }

            startActivity(intent);

上面指定的代码将打开 android 安装程序,这个 android 安装程序有两个按钮。一个是 "install",另一个是 "cancel" 按钮。

所以,我需要知道用户点击的是 "install" 按钮还是 "cancel" 按钮。我怎样才能得到这些回应?

接下来,我需要知道安装是否成功(如果用户点击了"install"按钮)?

提前致谢。

最后尝试使用 startActivityForResult(intent, 1); 而不是 startActivity(intent) 并在回调方法中添加以下代码.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// requestCode == 1 means the result for package-installer activity
if (requestCode == 1) 
{
    // resultCode == RESULT_CANCELED means user pressed `Done` button after installation
    if (resultCode == RESULT_CANCELED) {
        Toast.makeText(this, "Done button pressed", Toast.LENGTH_SHORT).show();
    } 
    else{ 
        //Check for the packagename to verify if user clicked on cancle button
        return isAppInstalled(context, "com.packagename");
    }
}
  super.onActivityResult(requestCode, resultCode, data);
}

现在我们必须创建一个方法来检查系统上的特定包,如果应用程序已安装,它将 return 为真,否则为假。

public static boolean isAppInstalled(Context context, String packageName) {
    try {
        context.getPackageManager().getApplicationInfo(packageName, 0);
        return true;
    }
    catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

希望对您有所帮助....