Quickstart in Android Java

Integrate the ARwayKit SDK with 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 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 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

Make sure to add the Account ID and Secret Key variables to the Unity project. Follow the guide for Building from the Source Code for instructions.

The package name in the Unity Editor will need to match the package name of the Kotlin app.

Build Steps

  1. In Unity select File -> Build Settings.

  2. Switch the Platform to Android.

  3. Select option "Export Project".

  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.

    + 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.

    dependencies {
    ...
    +    implementation project(':unityLibrary')
    +    implementation fileTree(dir: project(':unityLibrary').getProjectDir().toString() + ('\\libs'), include: ['*.jar'])
    }
  4. Open gradle.properties and add the code below to the end of the file.

    + unityStreamingAssets=.unity3d
  5. In the file /app/src/main/AndroidManifest.xml add tools:replace="android:allowBackup" to line 6.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">
    
        <application
    ++      tools:replace="android:allowBackup"
            android:allowBackup="true"
            android:dataExtractionRules="@xml/data_extraction_rules"
            android:fullBackupContent="@xml/backup_rules"
  6. You will be notified that changes have been made to the grade files, click the 'Sync Now' button to continue.

  1. 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.

MainUnityActiviy
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);
    }
}

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>);
  1. The MainActivity file will be modified to add a button to load the activity above. The code below shows the end result.

MainActivity
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();
    }
}
  1. 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.

activity_main_unity.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>
  1. Modify the layout code of the default file activity_main.xml to load the activity_main_unity.xml file from above.

activity_main.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>
  1. Then add a new string resource with the name game_view_content_descriptionand the content Game view in the strings.xml file.

<resources>
+    <string name="game_view_content_description">Game view</string>
</resources>

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).

Additional information about integrating Unity as a library into a standard Android app can be found in the following links:

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

Last updated