Add AI Voice Assistant to Android Apps

What is Voice Experience?

How do you add a Voice Experience to your android app?

What will you learn?

  • How to get started with Alan Platform
  • How to add a voice assistant to our Todo android app
  • Advanced Alan functionalities

What are the prerequisites?

  • Stable internet connection
  • Android Studio
  • Knowledge in Java, Android framework, and basic JavaScript

Step 1: Create a new Android Studio Project

  • Open Android Studio and create a new project. Select Basic Activity as it comes with a Floating Action Button. You can also select a different activity if you want a different layout for your home screen.
Create a new project with Basic Activity
  • Name your project, select a location to save your project, and select the min SDK for your android app (API 26 or above is recommended). Click on Finish.
Naming the Project
  • A code template for Basic Activity is provided by default. Delete or modify the unnecessary files in the project. In order to make the application effective, the entire application must run on a single activity with multiple fragments as per the requirement.
MainActivity.java

Step 2: Sign up on Alan Studio

  • Open your browser and head over to Alan Studio and sign up. If you already have an account, sign in instead.
  • Create an Empty project. Name your Todo project
    Note: Android Studio and Alan Studio project names need not to be same
Create an empty project
  • Alan comes with a lot of predefined scripts which helps you add some of the most popular functionalities with a few clicks. Click on Add Script and add as many scripts you want.
Add predefined scripts

Step 3: Add Alan dependency to your Todo app

  • Click on Integrations button in Alan Studio for the instructions to add Alan to your project. Under Android tab, a list of options are provided for customization. A sample code template is also provided there.
  • Copy the implementation and paste it in module level build.gradle file in Android Studio and click on Sync now.
dependencies {
...
// Add Alan dependency
implementation 'app.alan:sdk:4.12.0'
}
Module level build.gradle
  • Add Alan Button to activity_main.xml as shown below. In this code snippet Coordinator Layout is used. A few attributes may differ from user to user depending on the parent layout used and other components in the layout.
<com.alan.alansdk.button.AlanButton
android:id="@+id/alan_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="5dp"
android:layout_marginBottom="70dp"
android:visibility="visible"
app:button_horizontal_align="right" />
activity_main.xml
  • Now lets add the logic to activate Alan Button in our app. Go to MainActivity.java and add the following script to connect to your Alan project. Find your SDK Key in Alan Studio Integrations page and paste it in place of “YOUR SDK KEY”.
public class MainActivity extends AppCompatActivity {
...
private ActivityMainBinding binding;
private static final String SDK_KEY = "YOUR SDK KEY"; @Override
protected void onCreate(Bundle savedInstanceState) {
... AlanButton alanButton = binding.alanButton;
AlanConfig config = AlanConfig.builder()
.setProjectId(SDK_KEY).build();
alanButton.initWithConfig(config);
}
}
Hello world

Step 4: Add custom voice commands

intent('What can you do?', p => {
p.play('I can add a task and read them for you');
});intent('Say hurrah', p => {
p.play('Hurrah!');
});
Custom voice command

Step 5: Add core logic to your app

Step 6: Add Voice navigation to your app

Add Navigation commands in Alan Studio

//In Alan console
intent('(Go|take me) back', p => {
p.play('Sure');
p.play({ commandName: "go_back" });
});intent('Add a todo task (named|with title|) $(TASK_TITLE* (.+))', p => {
p.play('Adding the task');
p.play({ commandName: "add_todo", title: p.TASK_TITLE.value });
});
Alan Studio console

Catch the command on your client

AlanCallback alanCallback = new AlanCallback() {
/// Handle commands from Alan Studio
@Override
public void onCommand(final EventCommand eventCommand) {
try {
JSONObject command = eventCommand.getData();
1 //data object is the JSON Object returned in p.play() method
JSONObject data = command.getJSONObject("data");
String commandName = data.getString("command");
//based on commandName we can perform different tasks
executeCommand(commandName, data);
} catch (JSONException e) {
Log.e("AlanButton", e.getMessage());
}
}
};
alanButton.registerCallback(alanCallback);
private void executeCommand(String commandName, JSONObject data) {
if (commandName.equals("go_back")) {
onBackPressed(); //android lifecycle method
}
if (commandName.equals("log_out")) {
logOut();
}
if (commandName.equals("add_todo")) {
try {
String title = data.getString("title");
addTodoItem(title);
} catch (JSONException e) {
Log.e("AlanButton", e.getMessage());
alanButton.playText("I'm sorry I'm unable to do this at the moment");
}
}
}private void logOut() {
//code to log out
}private void addTodoItem(String title) {
//code to add a Todo Item
}
MainActivity.java

What else can you do with Alan?

Client API Methods

  • One of the most useful methods is callProjectApi() method. This method can be used to store server functions in Alan Studio and execute them on the client side with an API call. This provides an extra layer of abstraction and security to our code. Let’s look at how we can implement it.
//Alan script
projectAPI.greetUser = function(p, param, callback) {
p.userData.nameOfUser = param.userName;
p.play(`Hey ${p.userData.nameOfUser}, this is Alan. The voice assistant for Todo app. Here, you can store your daily tasks and prioritize them`);
};
public void greetUser(String name) {
binding.alanButton.activate();//parameters to be passed
JSONObject object = new JSONObject();
try {
object.put("userName", name);
binding.alanButton.callProjectApi("greetUser", object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
  • playText() method can be used to play text at any point of execution from client side using Alan Button object.
private void speakText(String text, AlanButton alanButton) {
//if the function is written outside MainActivity.java
//pass alanButton in parameter as shown and instead write
//alanButton.playText(text); binding.alanButton.playText(text);
}

Alan Handlers

  • onCommand handler: We already used this handler in the above steps to listen to different intents and get data from Alan. It handles commands sent from the voice scripts to the app.
  • onButtonState handler: This handler is used to get different states of Alan Button in your app. It can be helpful when you want to execute a set of tasks based on the button state. For example, you want to greet the user when the button is connected.
  • onEvent handler: As we discussed earlier that all the communication between the client and Alan happens through JSON Objects. While Alan interacts with the user and interprets the user’s input, it emits a series of events. You can intercept the event information and use it in your app logic if needed.
Handler Methods

Test the Todo app

Conclusion

Don’t forget to give us your 👏 !

--

--

--

Alan is a B2B Voice AI platform for developers to deploy and manage Voice Interfaces for Enterprise Apps.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Intermediate: OneSignal Push Notification Integration in Xamarin (Android)

Creating a Gmail like Navigation Drawer (Part II): Adding that final Ripple touch

Recover Your Lost Android Keystore File

Expert: Integration of Android Google Map and Huawei Map

Resources to learn and implement in Base Support Package(BSP) and Device Drivers Projects.

Personal “Request changes” Materials Starter Pack (Kotlin ver.) (Part 2)

How to add Google Pay as a payment method to your Android App ?

Android Tutorial: Learning How to CRUD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alan AI

Alan AI

Alan is a B2B Voice AI platform for developers to deploy and manage Voice Interfaces for Enterprise Apps.

More from Medium

Overcome Android Talkback’s Disabilities

How I Can Love Android Development

Material You Dynamic Colors in Android 12

Source — https://material.io/blog/announcing-material-you

Custom UI Components in Android