Search code examples
javaandroidinstallationpackagepermission-denied

Programmatically Install APK on Android 12 - " Permission to access file: /storage/emulated/0/xxxx.apk is denied "


With Android Studio, Java language, I write an application that install a package which APK is /eduphone/eduphone.apk On Android 12 I get the following error on Logcat : Permission to access file: /storage/emulated/0/Download/eduphone/eduphone.apk is denied

I tried several solutions proposed in Stak Overflow, but none works.

Here is the manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
    <uses-permission android:name="com.termux.permission.RUN_COMMAND"/>



    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:exported="true"
        android:theme="@style/Theme.Test4"
        tools:targetApi="31">
        <activity
            android:name="eu.eduphone.install.MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:permission="android.permission.MANAGE_DOCUMENTS"
        android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
    <queries>
        <package android:name="com.termux" />
        <package android:name="eu.edduphone" />
    </queries>
</manifest>`

Here is provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

Here is the Java code for permission :

public void getdroits () {

        if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, 1);
        }

        if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE}, 1);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if(!getPackageManager().canRequestPackageInstalls()){
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                        .setData(Uri.parse(String.format("package:%s", getPackageName()))), 1);
            }
        }
    }

Here is Java code for the APK insttallation. The argument passed to this code is String PATH = "/sdcard/Download/eduphone/eduphone.apk"

  private  void instApp(String PATH){
        Context context = getActivity().getBaseContext();
        File file = new File(PATH);

        if(file.exists()) {

            Uri  uri ;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
            } else {
                uri = Uri.fromFile(file);
            }

            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE, uri);

            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                Log.e("TAG", "Error in opening the file!");
            }
        }else{
            Toast.makeText(context,"APK "+PATH+" not found",Toast.LENGTH_LONG).show();
        }
    }

Thank you for your help ! Thierry


Solution

  • The answer of @Commonsware is rigth. But in my case I do not plan to publish this app on a store. This app is an installer for very few people which will want to install a specific environment on their smartphone (a Moodle server + a Nextcloud running thanks to Termux App). They will have to validate my global conditions before anything else.

    That why I solve my problem by allowing MANAGE_EXTERNAL_STORAGE

    For that :

    I add in the manifest.xml :

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

    At the early beginning of my app, I check and request permissions as seen in How to obtain MANAGE_EXTERNAL_STORAGE permission and How to check if Manifest.permission.MANAGE_EXTERNAL_STORAGE is granted? :

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                //request for the permission
                Log.d("Thierry", "Request ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION");
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        }
    

    Then for app installation :

        private  void instApp(String PATH){
        Context context = getActivity().getBaseContext();
        Log.d("Thierry", "Install PATH : "+PATH);
        File file = new File(PATH);
    
        if(file.exists()) {
            Uri  uri ;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Log.d("Thierry", "Build.VERSION.SDK_INT >= Build.VERSION_CODES");
    
                uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
            } else {
                uri = Uri.fromFile(file);
                Log.d("Thierry", "Build.VERSION.SDK_INT < Build.VERSION_CODES");
            }
            Log.d("Thierry", "INSTAPK  URI="+uri.toString());
            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE, uri);
            intent.setData(uri);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
    
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                Log.d("TAG", "Error in opening the file!");
            }
        }else{
            Log.d("Thierry", "INSTAPP , Not existe"+PATH);
        }
    }