启动 APK 安装器 Oreo

Launch APK Installer Oreo

我已经让这段代码工作了一段时间,但是使用 Android Orea 它不起作用。

        Context context = mContextRef.get();

        if (context == null) {
            return;
        }

        // Get the update
        String filepath = getDownloadLocation();
        File apkFile = new File(filepath);

        Uri fileLoc;
        Intent intent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            fileLoc = android.support.v4.content.FileProvider.getUriForFile(context, mFileProviderAuthority, apkFile);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            fileLoc = Uri.fromFile(apkFile);
        }

        intent.setDataAndType(fileLoc, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        context.startActivity(intent);

此代码适用于除 8.0 及更高版本之外的所有 android 版本。

编辑

抱歉没有解释更多。 IT 不起作用意味着,它会闪烁 window 几分之一秒然后消失(有时难以察觉)并在旧应用程序中继续。该文件已成功下载(我可以导航到它并安装)但是当我尝试启动 activity 以编程方式安装它时它失败了,没有任何错误或日志。

显然,如果您的应用程序针对 android 的更高版本,则清单中需要 android.permission.REQUEST_INSTALL_PACKAGES 权限,否则除了 LogCat.[=14= 中的单行错误外什么也不会发生。 ]

所以在 manifest.xml 文件中包含以下内容:

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

Manifest API for REQUEST_INSTALL_PACKAGES

请先在Manifest.xml中添加<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>权限

如果 SDK 版本等于或大于 26,我们应该检查 getPackageManager().canRequestPackageInstalls() 的结果。

代码如下:

private void checkIsAndroidO() {  
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  
    boolean result = getPackageManager().canRequestPackageInstalls();  
    if (result) {  
      installApk();
    } else {  
      // request the permission 
      ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_PACKAGES_REQUESTCODE);  
    }  
  } else {
    installApk();  
  }  
}

@Override  
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {  
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);

  switch (requestCode) {  
    case INSTALL_PACKAGES_REQUESTCODE:  
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {  
        installApk();  
      } else {  
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);  
        startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);  
      }  
    break;  
  }  
}

@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  super.onActivityResult(requestCode, resultCode, data); 

  switch (requestCode) {  
    case GET_UNKNOWN_APP_SOURCES:  
      checkIsAndroidO();  
      break;  

    default:  
      break;  
  }  
}

希望对你有所帮助