Alan Android SDK


Alan AI can be integrated with Android apps developed in Java and Kotlin.

Integrating with Alan AI

To add a conversational AI experience to an Android app, you need to do the following:

  1. Add the Alan AI SDK dependency

  2. Add the Alan AI button to the app layout

  3. Add the AlanConfig object

  4. Connect to the Alan AI Studio project

Step 1. Add the Alan AI SDK dependency

You need to add the Alan AI SDK dependency to the Android app. You can do it in two ways:

  • Add a reference as a Maven dependency

  • Download the aar package and include it manually

Do the following:

  1. Open the build.gradle file at the module level.

  2. In the dependencies block, add the dependency configuration for the Alan AI SDK for Android: implementation 'app.alan:sdk:<latest-version>'. To get the latest version, check out the Releases page for the Alan AI Android SDK GitHub repository.

build.gradle (module level)
dependencies {
  /// Add Alan AI SDK dependency
  implementation "app.alan:sdk:4.12.0"
}

Do the following:

  1. Download the Alan AI SDK from the releases section in the Alan AI Git repository.

  2. Put it in your <project>/app/libs folder. Create the libs folder if needed.

  3. Open the build.gradle file at the module level.

  4. In the repositories block, add the name of the folder in which the aar package resides.

  5. In the dependencies block, add the dependency configuration for the Alan AI SDK for Android. To get the latest version, check out the Releases page for the Alan AI Android SDK GitHub repository.

build.gradle (module level)
repositories {
  /// Add the following line to the repositories section
  flatDir {
    dirs 'libs'
  }
}
dependencies {
  /// Add the Alan AI SDK dependency
  implementation (name: 'AlanSdk-4.12.0', ext: 'aar')
}

Step 2. Add the Alan AI button to the app layout

To add the Alan AI button to the layout of your app, use the AlanButton class. The AlanButton class provides a view with the voice button and instance methods to communicate with Alan Studio.

In activity_main.xml, create a new AlanButton instance using the following XML layout:

activity_main.xml
<com.alan.alansdk.button.AlanButton
    android:id="@+id/alan_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:visibility="visible"
    app:button_horizontal_align="right"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

Note

The layout_width param should be set to match_parent.

Step 3. Add the AlanConfig object

You need to add the AlanConfig object to your app. This object describes the parameters that are provided for AlanButton. In the MainActivity.java file (for Android Java apps) or the MainActivity.kt file (for Android Kotlin apps), use AlanConfig.Builder to create a config with the necessary parameters:

Name

Type

Description

projectId

String

The Alan AI SDK key for a project in Alan AI Studio.

dialogId

String

(Optional) The dialog ID to connect to the necessary dialog.

dataObject

String or JSONObject

(Optional) A valid JSON string or JSON object with authentication or configuration data to be sent to the dialog script. For details, see authData.

MainActivity.java
public class MainActivity extends AppCompatActivity {

  /// Add the alanButton variable
  private AlanButton alanButton;

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

    /// Set up the Alan AI button
    AlanConfig config = AlanConfig.builder().setProjectId("").build();
    alanButton = findViewById(R.id.alan_button);
    alanButton.initWithConfig(config);
  }
}
MainActivity.kt
class MainActivity : AppCompatActivity() {

  /// Add the alanButton variable
  private var alanButton: AlanButton? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    /// Set up the Alan AI button
    val config = AlanConfig.builder().setProjectId("").build()
    alanButton = findViewById(R.id.alan_button)
    alanButton?.initWithConfig(config)
  }
}

Step 4. Connect to the Alan AI Studio project

As the last step, you need to connect the Android app to the Alan AI Studio project in which you create dialog scripts for the app. In setProjectId of MainActivity, provide the Alan AI SDK Key for your project in Alan Studio. To get the key, in Alan AI Studio, at the top of the code editor click Integrations and copy the key value from the Alan SDK Key field.

MainActivity.java
public class MainActivity extends AppCompatActivity {

  private AlanButton alanButton;

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

    /// Define the project key
    AlanConfig config = AlanConfig.builder().setProjectId("e40fc04e9aff7b4b7d43485dbc3cb44a2e956eca572e1d8b807a3e2338fdd0dc/stage").build();
    alanButton = findViewById(R.id.alan_button);
    alanButton.initWithConfig(config);
  }
}
MainActivity.kt
class MainActivity : AppCompatActivity() {

  private var alanButton: AlanButton? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    /// Define the project key
    val config = AlanConfig.builder().setProjectId("e40fc04e9aff7b4b7d43485dbc3cb44a2e956eca572e1d8b807a3e2338fdd0dc/stage").build()
    alanButton = findViewById(R.id.alan_button)
    alanButton?.initWithConfig(config)
  }
}

Your app is now integrated with Alan AI. You can now add voice commands to the script in Alan AI Studio, run the app, tap the Alan AI button and interact with the app with voice.

Using client API methods

You can use the following client API methods in your app:

setVisualState()

Use the setVisualState() method to inform the AI assistant about the app’s visual context. For details, see setVisualState().

Client app
fun setVisualState() {
  /// Providing any params
  val params = JSONObject()
  try {
    params.put("data", "your data")
  } catch (e: JSONException) {
    Log.e("AlanButton", e.message)
  }
  alanButton?.setVisualState(params.toString())
}
Client app
void setVisualState() {
  /// Providing any params
  JSONObject params = new JSONObject();
  try {
    params.put("data","your data");
  } catch (JSONException e) {
    Log.e("AlanButton", e.getMessage());
  }
  alanButton.setVisualState(params.toString());
}

callProjectApi()

Use the callProjectApi() method to send data from the client app to the dialog script and trigger activities without voice commands. For details, see callProjectApi().

Dialog script
projectAPI.setClientData = function(p, param, callback) {
  console.log(param);
};
Client app
fun callProjectApi() {
  /// Providind any params
  val params = JSONObject()
  try {
    params.put("data", "your data")
  } catch (e: JSONException) {
    Log.e("AlanButton", e.message)
  }
  alanButton?.callProjectApi("script::funcName", params.toString())
}
Client app
void callProjectApi() {
  /// Providing any params
  JSONObject params = new JSONObject();
  try {
    params.put("data","your data");
  } catch (JSONException e) {
    Log.e("AlanButton", e.getMessage());
  }
  alanButton.callProjectApi("script::funcName", params.toString());
}

playText()

Use the playText() method to play specific text in the client app. For details, see playText().

Client app
/// Playing any text message
fun playText() {
  /// Providing text as string param
  alanButton?.playText("Hi")
}
Client app
/// Playing any text message
void playText() {
  /// Providing text as string param
  alanButton.playText("Hi");
}

sendText()

Use the sendText() method to send a text message to Alan AI as the user’s input. For details, see sendText().

Client app
/// Sending any text message
fun sendText() {
  /// Providing text as string param
  alanButton?.sendText("Hello Alan, can you help me?")
}
Client app
/// Sending any text message
void sendText() {
  /// Providing text as string param
  alanButton.sendText("Hello Alan, can you help me?");
}

playCommand()

Use the playCommand() method to execute a specific command in the client app. For details, see playCommand().

Client app
/// Executing a command locally
fun playCommand() {
  /// Providing any params
  val params = JSONObject()
  try {
    params.put("action", "openSomePage")
  } catch (e: JSONException) {
    e.message?.let { Log.e("AlanButton", it) }
  }
  alanButton?.playCommand(params.toString(), null)
}
Client app
/// Executing a command locally
void playCommand() {
  /// Providing any params
  JSONObject params = new JSONObject();
  try {
    params.put("action","openSomePage");
  } catch (JSONException e) {
    Log.e("AlanButton", e.getMessage());
  }
  alanButton.playCommand(params.toString(), null);
}

activate()

Use the activate() method to activate the Alan AI button programmatically. For details, see activate().

Client app
/// Activating the Alan AI button programmatically
fun activate() {
  alanButton?.activate()
}
Client app
/// Activating the Alan AI button programmatically
void activate() {
  alanButton.activate();
}

deactivate()

Use the deactivate() method to deactivate the Alan AI button programmatically. For details, see deactivate().

Client app
/// Deactivating the Alan AI button programmatically
fun deactivate() {
  alanButton?.deactivate()
}
Client app
/// Deactivating the Alan AI button programmatically
void deactivate() {
  alanButton.deactivate();
}

isActive()

Use the isActive() method to check the Alan AI button state: active or not. For details, see isActive().

Client app
alanButton?.isActive()
Client app
alanButton.isActive();

getWakewordEnabled()

Use the getWakewordEnabled() method to check the state of the wake word for the Alan AI button. For details, see getWakewordEnabled().

Client app
var enabled = alanButton?.getWakewordEnabled()
Client app
boolean enabled = alanButton.getWakewordEnabled();

setWakewordEnabled()

Use the setWakewordEnabled() method to enable or disable the wake word for the Alan AI button. For details, see setWakewordEnabled().

Client app
alanButton?.setWakewordEnabled(true)
Client app
alanButton.setWakewordEnabled(true);

Using handlers

You can use the following Alan AI handlers in your app:

onCommand handler

Use the onCommand handler to handle commands sent from the dialog script. For details, see onCommand handler.

Client app
val alanCallback: AlanCallback = object : AlanCallback() {
  /// Handle commands from Alan AI Studio
  override fun onCommand(eventCommand: EventCommand) {
    try {
      val command = eventCommand.data
      val commandName = command.getJSONObject("data").getString("command")
      Log.d("AlanButton", "onCommand: commandName: $commandName")
    } catch (e: JSONException) {
      e.message?.let { Log.e("AlanButton", it) }
    }
  }
};

/// Register callbacks
alanButton?.registerCallback(alanCallback);
Client app
AlanCallback alanCallback = new AlanCallback() {
  /// Handle commands from Alan AI Studio
  @Override
  public void onCommand(final EventCommand eventCommand) {
    try {
      JSONObject command = eventCommand.getData();
      String commandName = command.getJSONObject("data").getString("command");
      Log.d("AlanButton", "onCommand: commandName: " + commandName);
    } catch (JSONException e) {
      Log.e("AlanButton", e.getMessage());
    }
  }
};

/// Register callbacks
alanButton.registerCallback(alanCallback);

onButtonState handler

Use the onButtonState handler to capture and handle the Alan AI button state changes. For details, see onButtonState handler.

Client app
val alanCallback: AlanCallback = object : AlanCallback() {

  /// Handle button state
  override fun onButtonState(alanState: AlanState) {
    Log.d("AlanButton", "onButtonState: $alanState")
  }
}
Client app
AlanCallback alanCallback = new AlanCallback() {

  /// Handle button state
  @Override
  public void onButtonState(AlanState alanState) {
    Log.d("AlanButton", "onButtonState: " + alanState);
  }
};

onEvent handler

Use the onEvent handler to capture and handle events emitted by Alan AI: get user’s utterances, assistant responses and so on. For details, see onEvent handler.

Client app
val alanCallback: AlanCallback = object : AlanCallback() {
  /// Handle events
  override fun onEvent(payload: String) {
    try {
      val eventDict = JSONObject(payload)
      Log.d("AlanButton", "onEvent: event: $eventDict")
    } catch (e: JSONException) {
      e.message?.let { Log.e("AlanButton", it) }
    }
  }
}
Client app
AlanCallback alanCallback = new AlanCallback() {
  /// Handle events
  @Override
  public void onEvent(String payload) {
    try {
      JSONObject eventDict = new JSONObject(payload);
      Log.d("AlanButton", "onEvent: event: " + eventDict);
    } catch (JSONException e) {
      Log.e("AlanButton", e.getMessage());
    }
  }
};

Switching between logging levels

You can switch to the extended logging level with a static enableLogging method of the Alan object:

Alan.enableLogging(true);

Troubleshooting

To troubleshoot problems you may have with your Android app, check the solutions below:

  • The minimum possible Android SDK version required by the Alan AI SDK is 21. If the version in your project is lower, you may encounter the following error: AndroidManifest.xml Error: uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library [:alan_voice]. Open the app/build.gradle file, under defaultConfig, locate minSdkVersion and change the version to 21.

  • If gradle fails to get all dependencies required by the Alan AI SDK, you will encounter the following error: Could not find <dependency-name> required by project :app > alan.app:sdk:x.xx.x.

    Make sure jcenter() is added to your project:

    1. In your project, open the settings.gradle file.

    2. Check the repositories list. If jcenter() is not in the list, add it:

      settings.gradle
      dependencyResolutionManagement {
        repositories {
          mavenCentral()
          jcenter()
        }
      }
      
    3. Sync and run your project.

    • (If running the app on an emulator) All virtual microphone options must be enabled. On the emulator settings bar, click More (…) > Microphone and make sure all toggles are set to the On position.

What’s next?

../../../_images/git-purple.svg

Example apps

Find and explore examples of voice-enabled apps on the Alan AI GitHub repository.

View on GitHub