How to install Android apk from code in unity

Viewed 16021

I found snippet for Java. How can I write such a code in C# Unity?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File("link to downloaded file")),"application/vnd.android.package-archive");
startActivity(intent);
5 Answers

I just wanted to add an update to the fantastic answer given by @Programmer, to reflect changes to the Android SDK and Unity. I hope it can be useful to someone else. I am working with SDK version 26 and Unity 2017.3.1. I am new to almost all of this so please do correct me if I've missed or misunderstood anything!

  1. The android-support-v4.jar (used to get the FileProvider class) is no longer available. For versions up to 24.1.1 it is located at Android\sdk\extras\android\m2repository\com\android\support\support-v4\24.1.1 but for versions after that you must instead use support-core-utils at Android\sdk\extras\android\m2repository\com\android\support\support-core-utils. Instead of a jar file use the relevant .aar file and drag that into a Plugins folder in your Unity project.
  2. You need to add android.permission.REQUEST_INSTALL_PACKAGES to your AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.productsomethingelse" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal" android:versionName="1.0" android:versionCode="1">
      <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
      <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true">
        <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name">
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
          <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>
    
        <provider
              android:name="android.support.v4.content.FileProvider"
              android:authorities="com.company.product.fileprovider"
              android:exported="false"
              android:grantUriPermissions="true">
          <meta-data
              android:name="android.support.FILE_PROVIDER_PATHS"
              android:resource="@xml/provider_paths"/>
        </provider>
    
      </application>
      <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
      <uses-sdk android:minSdkVersion="24" android:targetSdkVersion="26" />
    </manifest>
    

    Note that I've also changed the first instance of com.company.product to com.company.productsomethingelse

  3. That should now build ok and work, although during the build process Unity is giving the warning OBSOLETE - Providing Android resources in Assets/Plugins/Android/res is deprecated, please move your resources to an AAR or an Android Library.. To get round this create a new zip file and put your AndroidManifest.xml at the top level of the zip. Then add the provider_paths.xml detailed by @Programmer into the zip in the folder structure res/xml/provider_paths.xml. Rename the zip to give it a .aar file extension and then drag it into your Unity project Assets/Plugins folder. The reason I changed the AndroidManifest.xml entry to com.company.productsomethingelse is that when I used com.company.product the Unity build process was throwing up a naming conflict. I think because the manifest is now in a separate aar it needs to have a distinct package name.

With later versions of Unity, it gets a bit more complicated. Assets/Plugins/Android/res got deprecated. And with Android 9.0 android.support.v4 got merged into androidx.core and everything got renamed and moved around. Fortunately Unity is a bit better about supporting Android plugins now, so with this solution you no longer have to add any jar or aar to your project.

Note that Android has a bunch of nag screens associated with this install process. There's a one-time accept screen for untrusted builds per app, and if you have google play on the device, play protect adds a bunch of screens that make your app look like malware. (Which is a good thing, as you should only be doing this stuff on kiosk-mode style devices you own, where you can turn off Play Protect.)

Adding to Programmer's answer. In Unity 2019 and 2020, you can compile a plugin directly in Unity, and you no longer need the jar file. In 2019, it needs to be in Assets/Plugins/Android and have a couple extra files. In 2020, the folder just needs the suffix .androidlib and can be located anywhere in Assets/.

package.androidlib
  src
    main
      res
        xml
          provider_paths.xml
      AndroidManifest.xml
  build.gradle
  AndroidManifest.xml  (only for 2019)
  project.properties  (only for 2019)

provider_paths.xml: As explained by Programmer.

AndroidManifest.xml: is mainly there to give this new library a bundle ID. This should not match any other IDs; it can be anything and usually it's com.companyname.packagename. Note that it's within the main/ folder

We can also do the rest of the AndroidManifest.xml stuff here, because all AndroidManifest.xml files will get merged in the final APK nowadays. The FileProvider package has changed to androidx.core.content.FileProvider.

I've noticed you need android.permission.REQUEST_INSTALL_PACKAGES; but I'm not sure whether you need READ_EXTERNAL_STORAGE/WRITE_EXTERNAL_STORAGE like Kaushix suggests. (Maybe on certain devices? I think this is covered by Project Settings->Write Permission.)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.anything.anythingelse">
    <application>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
</manifest>

build.gradle: This should probably match your project target and min SDK version. It's OK if it's less, but target needs to be at least 28 to use androidx.

apply plugin: 'com.android.library'

android {
    compileSdkVersion 28


    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 28
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
}

For 2019, the extra AndroidManifest.xml and project.properties files purely exist to tell Unity to build this folder. In 2020, Unity's smart enough to not need them.

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This extra manifest, as well as project.properties in this folder shouldn't be necessary with the newer gradle project format. Can remove if you upgrade to 2020.1. -->
</manifest>

project.properties:

android.library=true

AndroidPostProcess.cs:

We also need an editor script to enable AndroidX support in the main gradle file, and turn on Jetifier, which should fix any other plugins compiled against the old android.support libraries.

using UnityEditor.Android;

public class AndroidPostProcess : IPostGenerateGradleAndroidProject
{
    public int callbackOrder => 0;
    public void OnPostGenerateGradleAndroidProject(string path)
    {
        string gradlePropertiesPath = path + "/gradle.properties";
        string[] lines = File.ReadAllLines(gradlePropertiesPath);

        StringBuilder builder = new StringBuilder();
        foreach (string line in lines)
        {
            if (line.Contains("android.useAndroidX"))
            {
                continue;
            }
            if (line.Contains("android.enableJetifier"))
            {
                continue;
            }
            builder.AppendLine(line);
        }
        builder.AppendLine("android.useAndroidX=true");
        builder.AppendLine("android.enableJetifier=true");
        File.WriteAllText(gradlePropertiesPath, builder.ToString());
    }
}

Here we have to change your manifest file. We have to give Read & Write permissions. after change this we can easily install downloaded application file.

Without these permissions we can't access Android External Files.

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.product" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal" android:versionName="1.0" android:versionCode="1">
      <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
      <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true">
        <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name">
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
          <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>

        <provider
              android:name="android.support.v4.content.FileProvider"
              android:authorities="com.company.product.fileprovider"
              android:exported="false"
              android:grantUriPermissions="true">
          <meta-data
              android:name="android.support.FILE_PROVIDER_PATHS"
              android:resource="@xml/provider_paths"/>
        </provider>

      </application>
      <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-sdk android:minSdkVersion="16"   android:maxSdkVersion="29"  />
    </manifest>

After all these great answers I still had an issue: App immidiatly closes on start. In my case adding the Fileprovider code to the manifest causes this issue.

Fix: I manually added the androidx.core library to the Unity Project.

  1. Download the library (https://mvnrepository.com/artifact/androidx.core/core/1.0.1)
  2. Copy the aar-file into the folder "Assets\Plugins\Android\libs"
  3. In Unity click on the aar- file and check the "Android" Checkmark

I'm still finding some other issues, but at least the app starts now. Maybe i could help someone else with this Information

Related