Answers:
您可以轻松启动Play商店链接或安装提示:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
    .setDataAndType(Uri.parse("content:///path/to/your.apk"), 
                    "application/vnd.android.package-archive");
startActivity(promptInstall); 要么
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
    .setData(Uri.parse("https://play.google.com/store/apps/details?id=com.package.name"));
startActivity(goToMarket);但是,未经用户的明确许可,您无法安装.apks 。除非设备和您的程序已植根。
/sdcard,因为在Android 2.2+和其他设备上,这是错误的。使用Environment.getExternalStorageDirectory()代替。
                    File file = new File(dir, "App.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);我遇到了同样的问题,经过几次尝试,它以这种方式为我解决了。我不知道为什么,但是分别设置数据和类型搞砸了我的意图。
setData()会导致类型参数被删除。setDataAndType()如果您要为两者提供值,则必须使用。在这里:developer.android.com/reference/android/content/...
                    提供给该问题的解决方案均适用于targetSdkVersion23及以下的。但是,对于Android N,即API级别24及更高版本,它们不起作用并崩溃,并出现以下异常:
android.os.FileUriExposedException: file:///storage/emulated/0/... exposed beyond app through Intent.getData()这是由于以下事实:从Android 24开始,Uri用于解决下载文件的更改。例如,安装文件命名appName.apk存储在应用的主要外部文件系统产品包名称com.example.test将作为
file:///storage/emulated/0/Android/data/com.example.test/files/appName.apk
对于API 23和以下,而类似
content://com.example.test.authorityStr/pathName/Android/data/com.example.test/files/appName.apk对于API 24以上。
关于此的更多详细信息可以在这里找到,我将不进行介绍。
要回答这个问题的targetSdkVersion的24以上,就必须按照下列步骤操作:将以下内容添加到AndroidManifest.xml中:
<application
        android:allowBackup="true"
        android:label="@string/app_name">
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.authorityStr"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/paths"/>
        </provider>
</application>2.将以下paths.xml文件添加到src main中的xml文件夹res中:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="pathName"
        path="pathValue"/>
</paths>的pathName是,示于上面的示例性内容的URI示例,并且pathValue是在系统上的实际路径。放置“。”将是一个好主意。如果您不想添加任何额外的子目录,请使用上面的pathValue(不带引号)。
编写以下代码,以将名称appName.apk安装在主外部文件系统上的apk :
File directory = context.getExternalFilesDir(null);
File file = new File(directory, fileName);
Uri fileUri = Uri.fromFile(file);
if (Build.VERSION.SDK_INT >= 24) {
    fileUri = FileProvider.getUriForFile(context, context.getPackageName(),
            file);
}
Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setDataAndType(fileUri, "application/vnd.android" + ".package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
activity.finish();在外部文件系统上写入自己的应用程序的私有目录时,也不需要权限。
.authorityStr,context.getPackageName()然后它应该可以工作了。
                    好吧,我进行了更深入的研究,并从Android Source找到PackageInstaller应用程序的源。
https://github.com/android/platform_packages_apps_packageinstaller
从清单我发现它需要许可:
    <uses-permission android:name="android.permission.INSTALL_PACKAGES" />并在确认后进行实际的安装过程
Intent newIntent = new Intent();
newIntent.putExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO, mPkgInfo.applicationInfo);
newIntent.setData(mPackageURI);
newIntent.setClass(this, InstallAppProgress.class);
String installerPackageName = getIntent().getStringExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME);
if (installerPackageName != null) {
   newIntent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, installerPackageName);
}
startActivity(newIntent);我只想分享一个事实,即我的apk文件已保存到我的应用程序“数据”目录中,并且我需要将apk文件的权限更改为世界可读以便允许以这种方式安装,否则系统抛出“解析错误:解析程序包时出现问题”;所以使用@Horaceman的解决方案可以:
File file = new File(dir, "App.apk");
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);这可以帮助别人很多!
第一:
private static final String APP_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyAppFolderInStorage/";
private void install() {
    File file = new File(APP_DIR + fileName);
    if (file.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri downloadedApk = FileProvider.getUriForFile(getContext(), "ir.greencode", file);
            intent.setDataAndType(downloadedApk, type);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        getContext().startActivity(intent);
    } else {
        Toast.makeText(getContext(), "ّFile not found!", Toast.LENGTH_SHORT).show();
    }
}第二:对于android 7及更高版本,您应在清单中定义一个提供者,如下所示!
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="ir.greencode"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/paths" />
    </provider>第三:在res / xml文件夹中定义path.xml,如下所示!如果您要将其更改为其他内容,则可以使用此路径进行内部存储!您可以转到此链接: FileProvider
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="your_folder_name" path="MyAppFolderInStorage/"/>
</paths>第四:您应该在清单中添加此权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>允许应用程序请求安装软件包。定位到大于25的API的应用必须拥有此权限才能使用Intent.ACTION_INSTALL_PACKAGE。
请确保提供者的权限相同!
是的,有可能。但是为此,您需要手机安装未验证的源。例如,slideMe做到了。我认为您最好的办法是检查应用程序是否存在,并向Android Market发送意向书。您应该为Android Market使用url方案。
market://details?id=package.name我不确切地知道如何开始活动,但是如果您使用这种网址开始活动。它应该会打开android市场,并让您选择安装应用程序。
值得注意的是,如果您使用DownloadManager开始下载,请确保将其保存到外部位置,例如setDestinationInExternalFilesDir(c, null, "<your name here>).apk";。带有包归档类型的意图似乎不喜欢content:用于下载到内部位置的方案,但是喜欢file:。(尝试将内部路径包装到File对象中,然后获取路径也不起作用,即使它会导致产生file:url,因为该应用程序也不会解析apk;看起来它必须是外部的。)
例:
int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
String downloadedPackageUriString = cursor.getString(uriIndex);
File mFile = new File(Uri.parse(downloadedPackageUriString).getPath());
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
        .setDataAndType(Uri.fromFile(mFile), "application/vnd.android.package-archive")
        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(promptInstall);不要忘记请求权限:
android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
android.Manifest.permission.READ_EXTERNAL_STORAGE在AndroidManifest.xml中添加提供者和权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
...
<application>
    ...
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>创建XML文件提供程序res / xml / provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>使用以下示例代码:
   public class InstallManagerApk extends AppCompatActivity {
    static final String NAME_APK_FILE = "some.apk";
    public static final int REQUEST_INSTALL = 0;
     @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // required permission:
        // android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
        // android.Manifest.permission.READ_EXTERNAL_STORAGE
        installApk();
    }
    ...
    /**
     * Install APK File
     */
    private void installApk() {
        try {
            File filePath = Environment.getExternalStorageDirectory();// path to file apk
            File file = new File(filePath, LoadManagerApkFile.NAME_APK_FILE);
            Uri uri = getApkUri( file.getPath() ); // get Uri for  each SDK Android
            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData( uri );
            intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK );
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
            intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, getApplicationInfo().packageName);
            if ( getPackageManager().queryIntentActivities(intent, 0 ) != null ) {// checked on start Activity
                startActivityForResult(intent, REQUEST_INSTALL);
            } else {
                throw new Exception("don`t start Activity.");
            }
        } catch ( Exception e ) {
            Log.i(TAG + ":InstallApk", "Failed installl APK file", e);
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG)
                .show();
        }
    }
    /**
     * Returns a Uri pointing to the APK to install.
     */
    private Uri getApkUri(String path) {
        // Before N, a MODE_WORLD_READABLE file could be passed via the ACTION_INSTALL_PACKAGE
        // Intent. Since N, MODE_WORLD_READABLE files are forbidden, and a FileProvider is
        // recommended.
        boolean useFileProvider = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
        String tempFilename = "tmp.apk";
        byte[] buffer = new byte[16384];
        int fileMode = useFileProvider ? Context.MODE_PRIVATE : Context.MODE_WORLD_READABLE;
        try (InputStream is = new FileInputStream(new File(path));
             FileOutputStream fout = openFileOutput(tempFilename, fileMode)) {
            int n;
            while ((n = is.read(buffer)) >= 0) {
                fout.write(buffer, 0, n);
            }
        } catch (IOException e) {
            Log.i(TAG + ":getApkUri", "Failed to write temporary APK file", e);
        }
        if (useFileProvider) {
            File toInstall = new File(this.getFilesDir(), tempFilename);
            return FileProvider.getUriForFile(this,  BuildConfig.APPLICATION_ID, toInstall);
        } else {
            return Uri.fromFile(getFileStreamPath(tempFilename));
        }
    }
    /**
     * Listener event on installation APK file
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_INSTALL) {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this,"Install succeeded!", Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this,"Install canceled!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this,"Install Failed!", Toast.LENGTH_SHORT).show();
            }
        }
    }
    ...
}试试这个
String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
String title = filePath.substring( filePath.lastIndexOf('/')+1, filePath.length() );
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
MainActivity.this.startActivity(intent);首先将以下行添加到AndroidManifest.xml:
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
    tools:ignore="ProtectedPermissions" />然后使用以下代码安装apk:
File sdCard = Environment.getExternalStorageDirectory();
            String fileStr = sdCard.getAbsolutePath() + "/MyApp";// + "app-release.apk";
            File file = new File(fileStr, "TaghvimShamsi.apk");
            Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            startActivity(promptInstall);UpdateNode为Android提供了一个API,可以从另一个应用程序内部安装APK软件包。
您只需在线定义更新,然后将API集成到您的App中即可。
目前,API处于Beta状态,但您已经可以自己进行一些测试。
除此之外,UpdateNode还提供了通过系统显示消息的功能-如果您想告诉用户一些重要信息,这将非常有用。
我是客户开发团队的一员,并且至少在自己的Android应用程序中使用了消息功能。
试试这个-在清单上写:
uses-permission android:name="android.permission.INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions"编写代码:
File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/Download";// + "app-release.apk";
File file = new File(fileStr, "app-release.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");
startActivity(promptInstall);