Android 8.0 安装APK

因为8.0添加了新的安全措施,不允许应用内安装未经过Google play验证的应用,但是又有更新应用的需求

那么首先要加入权限

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
添加provider
<manifest>
    ...
    <application>
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.mydomain.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            ...
        </provider>
       <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
    </application>
</manifest>
在resources文件夹中添加一个xml文件夹,名字对应file_paths,在file_paths中添加
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_storage_root" path="." />
</paths>
path="."其实是对应外置SD卡的根目录

原文在此:https://developer.android.com/reference/android/support/v4/content/FileProvider.html

判断是否有权限    
val REQUEST_INSTALL_PACKAGES = 3
override fun onCreate(savedInstanceState: Bundle?) {
...
requestPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES, REQUEST_INSTALL_PACKAGES)
...
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            REQUEST_INSTALL_PACKAGES->startActivity(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES))
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
   protected fun requestPermission(permission: String, requestCode: Int) {
        if (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED || !packageManager.canRequestPackageInstalls()
        } else {
            ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED
        }) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode)
            } else {
                ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode)
            }
        } else {
            //直接执行操作
            when (requestCode) {
                REQUEST_INSTALL_PACKAGES -> //执行安装操作
            }
        }
    }
packageManager.canRequestPackageInstalls()这一行用于判断是否已经获取到允许安装未知应用,返回值Boolean


展开阅读全文

没有更多推荐了,返回首页