Programmatically install an apk in Android 7 / api24

后端 未结 8 1852
夕颜
夕颜 2020-12-31 07:39

I am trying to get my app to automatically install an apk. This works fine for api<24. But for 24, it is failing. Android has implemented extra security:

8条回答
  •  天涯浪人
    2020-12-31 08:21

    Here is the solution I have found

    val newFile = File(dirPath, "$fileNameWithoutExtn.apk")
                            var fileUri = Uri.fromFile(newFile)
                            //use the fileProvider to get the downloaded from sdcard
                            if (Build.VERSION.SDK_INT >= 24) {
                                fileUri = FileProvider.getUriForFile(this@SettingAcitivity, applicationContext.packageName + ".provider", newFile)
                             val intent=Intent(Intent.ACTION_VIEW)
                                intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
                                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                startActivity(intent)
                            }else{
                                newFile.setReadable(true, false)
                                val intent = Intent(Intent.ACTION_VIEW)
                                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
                                intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                startActivity(intent)
                            }
    

    and write in manifest

    
                
    

    and also set the permission

    
    

    and in xml folder paths will be

    
        
    
    

提交回复
热议问题