# Quickstart in Android Java

In this quickstart guide, we will be integrating the ARwayKit SDK with Android Java. This example will be using [Unity as a Library](https://github.com/Unity-Technologies/uaal-example/blob/uaal-example/19LTS-21LTS/docs/android.md) to integrate into an Android app.

## Installed Versions

In this guide, we will be using the following versions:

* Android Studio: 2022.1.1
* Unity: 2022.3.29f1 LST
* Android Min API Level 24

## Download the ARwayKit SDK

**Steps**

1. Download the ARwayKit SDK project from GitHub as a **ZIP**. You can [contact us](https://www.arway.ai/contact) for access to the ARwayKit SDK.

## Create a Basic Project in Android Studio

Create a new sample Android Project, for this example a new project using the Empty Activity template will be used with the language set to Java and the minimum SDK set to API 24.

## Generate the Gradle Project for the Android Platform

{% hint style="info" %}
Make sure to add the Account ID and Secret Key variables to the Unity project. Follow the guide for [Building from the Source Code](https://docs.arway.ai/arway-sdk/building-from-the-source-code) for instructions.
{% endhint %}

{% hint style="info" %}
The package name in the Unity Editor will need to match the package name of the Kotlin app.
{% endhint %}

## **Build Steps**

1. In Unity select File -> Build Settings.
2. Switch the Platform to Android.
3. Select option "Export Project".<br>

   <figure><img src="https://4128853559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlDytDSBRx8P4ZZXD57DA%2Fuploads%2FJjAebQIffBPe3xdmGu2i%2Fimage.png?alt=media&#x26;token=5ae132ff-1d5f-4c93-abbd-4ffa6f103ada" alt=""><figcaption><p>Export the project.</p></figcaption></figure>
4. Export the ARwayKit Unity SDK to a new folder and name it "androidBuild" and place it in the base directory for the Android Java project.

### Add the Unity Android Build to the Android App

**Steps**

1. Open the Android sample app in Android Studio.
2. Open the `settings.gradle` file and make the following changes to the code as shown below. Ensure that the line `'androidBuild\\unityLibrary'` matches the path to the ARwayKit Unity SDK export.

   ```git
   + include ':unityLibrary'
   + project(':unityLibrary').projectDir=new File('androidBuild\\unityLibrary')
   + include ':unityLibrary:xrmanifest.androidlib'
   dependencyResolutionManagement {
       repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
       repositories {
           google()
           mavenCentral()
   +       flatDir {
   +            dirs "${project(':unityLibrary').projectDir}/libs"
   +       }
       }
   }
   ```
3. Open `build.gradle`(Module: app) file, then add the following in the dependencies block.

   <pre class="language-git"><code class="lang-git">dependencies {
   ...
   <strong>+    implementation project(':unityLibrary')
   </strong>+    implementation fileTree(dir: project(':unityLibrary').getProjectDir().toString() + ('\\libs'), include: ['*.jar'])
   }
   </code></pre>
4. Open `gradle.properties` and add the code below to the end of the file.

   <pre class="language-git"><code class="lang-git"><strong>+ unityStreamingAssets=.unity3d
   </strong></code></pre>
5. In the file /app/src/main/AndroidManifest.xml add `tools:replace="android:allowBackup"` to line 6.

   <pre class="language-git"><code class="lang-git">&#x3C;?xml version="1.0" encoding="utf-8"?>
   &#x3C;manifest xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools">

       &#x3C;application
   <strong>++      tools:replace="android:allowBackup"
   </strong>        android:allowBackup="true"
           android:dataExtractionRules="@xml/data_extraction_rules"
           android:fullBackupContent="@xml/backup_rules"
   </code></pre>
6. You will be notified that changes have been made to the grade files, click the 'Sync Now' button to continue.&#x20;

<figure><img src="https://4128853559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlDytDSBRx8P4ZZXD57DA%2Fuploads%2F4A9juLg4D4ydxBemR1zJ%2Fimage.png?alt=media&#x26;token=b325ef35-ad7e-4479-ae89-4249f7147339" alt=""><figcaption><p>Sync the gradle files.</p></figcaption></figure>

7. If everything succeeds you should be able to see the unityLibrary module added in the Android view.

## Preparing the Sample Project

To run the ARwayKit Unity SDK on Android, we need to integrate Unity as a library in our Android project. This will allow us to use the Unity engine within our app and run Unity scenes alongside native Android activities. In this section, we will go through the steps to set up Unity as a library and add the ARwayKit Unity SDK to the project.

1. For this we will be creating a **new** blank Activity in the project called `MainUnityActiviy`. Make sure the generate the layout file as well.

{% code title="MainUnityActiviy" %}

```kotlin
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.FrameLayout;
import com.unity3d.player.UnityPlayerActivity;

public class MainUnityActivity extends UnityPlayerActivity {
    private MainUnityActivity instance;

    // Setup activity layout
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        addControlsToUnityFrame();
        Intent intent = getIntent();
        handleIntent(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
        setIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (intent == null || intent.getExtras() == null) return;
        if (intent.getExtras().containsKey("doQuit")) {
            if (mUnityPlayer != null) {
                finish();
            }
        }
    }

    private void showMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    @Override
    public void onUnityPlayerUnloaded() {
        showMainActivity();
    }

    private void addControlsToUnityFrame() {
        FrameLayout layout = mUnityPlayer;

        Button myButton = new Button(this);
        myButton.setText("Show Main");
        myButton.setX(10f);
        myButton.setY(500f);
        myButton.setOnClickListener(v -> showMainActivity());
        layout.addView(myButton, 300, 200);

        Button unloadButton = new Button(this);
        unloadButton.setText("Unload");
        unloadButton.setX(630f);
        unloadButton.setY(500f);
        unloadButton.setOnClickListener(v -> mUnityPlayer.unload());
        layout.addView(unloadButton, 300, 200);
    }
}
```

{% endcode %}

In the above file, the `addControlsToUnityFrame()` method sets the positions of the buttons added to the layout. These buttons are not required but showcase the methods to unload the Unity player.

To pass data to Unity, you can call the following method:

```
mUnityPlayer.UnitySendMessage("<GameObject>", "<Method>",<string value>);
```

2. The `MainActivity` file will be modified to add a button to load the activity above. The code below shows the end result.

{% code title="MainActivity" %}

```kotlin
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private boolean isUnityLoaded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
        setIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (intent.getExtras() == null) return;
    }

    public void btnLoadUnity(View v) {
        isUnityLoaded = true;
        Intent intent = new Intent(this, MainUnityActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) isUnityLoaded = false;
    }

    private void unloadUnity(boolean doShowToast) {
        if (isUnityLoaded) {
            Intent intent = new Intent(this, MainUnityActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            intent.putExtra("doQuit", true);
            startActivity(intent);
            isUnityLoaded = false;
        } else if (doShowToast) showToast("Show Unity First");
    }

    public void btnUnloadUnity(View v) {
        unloadUnity(true);
    }

    private void showToast(String message) {
        CharSequence text = message;
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(getApplicationContext(), text, duration);
        toast.show();
    }

    @Override
    public void onBackPressed() {
        finishAffinity();
    }
}
```

{% endcode %}

3. Next, find the newly created layout file under `src/main/res/layout` called `activity_main_unity.xml`. This adds the buttons to open the Unity activity and close the app.

{% code title="activity\_main\_unity.xml" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="36dp"
        android:onClick="btnLoadUnity"
        android:text="Show Unity"
        app:layout_constraintEnd_toStartOf="@+id/button2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:onClick="btnUnloadUnity"
        android:text="Finish"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

{% endcode %}

4. Modify the layout code of the default file `activity_main.xml` to load the `activity_main_unity.xml` file from above.

{% code title="activity\_main.xml" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <include layout="@layout/activity_main_unity" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

{% endcode %}

5. Then add a new string resource with the name `game_view_content_description`and the content `Game view` in the `strings.xml` file.

<pre class="language-git"><code class="lang-git">&#x3C;resources>
<strong>+    &#x3C;string name="game_view_content_description">Game view&#x3C;/string>
</strong>&#x3C;/resources>
</code></pre>

Once you have completed all the necessary steps to integrate the ARwayKit Unity SDK into your Android Java project, you are ready to build, run, and debug your app. If everything has been properly configured, you should be able to run the app seamlessly with the ARwayKit Unity SDK.

Unity will run in another process android:process=":Unity" (AndroidManifest.xml at app module).

{% hint style="info" %}
Additional information about integrating Unity as a library into a standard Android app can be found in the following links:&#x20;

<https://github.com/Unity-Technologies/uaal-example/blob/uaal-example/19LTS-21LTS/docs/android.md>

<https://docs.unity3d.com/2019.3/Documentation/Manual/UnityasaLibrary.html>
{% endhint %}
