Build an application with the Watson Android SDK in Android Studio
IBM Watson may be best known for competing on the US quiz show Jeopardy, but the technology goes far beyond simple questions and answers. Watson is an entirely new form of computing, one that promises to discover hitherto undiscovered insights based on the wealth of data all around us. While traditional computer models have relied on rigid mathematic principles, utilizing software built upon rules and logic, Watson instead relies on what IBM is calling “cognitive computing”. IBM Watson has multiple services that includes Assistant, Discovery, Personality Insights and
The Watson team also provides multiple software development kits (SDKs) to help developers use Watson with various programming languages. The watson-developer-cloud GitHub organization has a full listing of available SDKs.
Learning Objectives
After completing this guide the reader will know how to:
- Download and Install the Watson Android SDK
- Use Android Studio with the Watson Android SDK
- Use Watson services through their service credentials and APIs in Android Studio
- Build and run a sample Android application that uses Watson
Prerequisites
To follow this How-to guide, you need to have:
- An IBM Cloud Account –
- Android Studio installed on a local machine.
- A provisioned Language Translator service on IBM Cloud.
- A provisioned Speech to Text service on IBM Cloud
- A provisioned Text to Speech service on IBM Cloud.
Estimated time
To complete the how-to should take about one hour. Thirty minutes for the prerequisites and another thirty minutes for the guide.
Steps
Note: This how-to was tested with Android Studio 3.0.1, Watson Android SDK v0.4.3, and macOS High Sierra
Download the Watson Android SDK
Navigate to the Watson Android SDK on Github and click the Clone or Download button to download the repository as a ZIP file.
Optionally, we encourage the reader to check out the watson-developer-cloud GitHub organization that the Watson team maintains to see all other available SDKs.
Create a new Watson Android SDK project in Android Studio
We’ll now use the example folder in the Watson Android SDK as a starting base.
- Unzip the newly downloaded ZIP file (probably named
android-sdk.zip
) into a new workspace folder. - Launch Android Studio.
- Click File > Open in the menu bar and provide the
example
folder of the un-zipped file. - Android Studio will now build the project using Gradle
Note: If you see a Install missing platform(s) and sync project
error or Install Build-Tools 26.0.1 and sync project
error, then click the hyperlink provided to install the missing platform or tools. Once installed the build should restart and complete successfully.
Exploring the sample application
Let’s now take a look at the sample application provided in the SDK. Specifically, let’s open the file MainActivity.java
, which is located at example > java > com.ibm.watson.developer_cloud.android.myapplication > MainActivity
.
Here you will see that there are plenty of libraries already imported for the sample application. To use other available libraries, you can import them as shown below:
By expanding the import section at the top of the file (clicking on import ...
) you’ll be able to see the various imports used in MainActivity.java
. Note the ones used by the watson_developer_cloud
package, the Watson Android SDK. To quickly see a complete list of other Watson services you can use, type in import com.ibm.watson.developer_cloud.
and let the auto-complete show you what is available.
Now let’s check out activity_main.xml
, which is located at example > res > layout > activity_main.xml
. This XML file contains the layout for MainActivity.java
. By double-clicking activity_main.xml
Android Studio will automatically generate a sample design of the activity for the application. You can also edit this design by clicking Text at the bottom left corner of the tab to see the XML written.
Lastly, let’s check out credentials.xml
, which is located at example > res > values > credentials.xml
. This XML file contains a template for providing the credentials for the various Watson services that are used by the application. In this case, there are three different Watson Services used; Watson Language Translator, Speech to text, Text to speech. Each value in the XML file contains a resource name that can then be referenced from MainActivity.java
.
Adding service credentials to credentials.xml
We now copy and paste the credentials for each Watson service to credentials.xml
. Refer back to the Prerequisites section for instructions on how to create specific Watson services.
To find the service credential value, log into IBM Cloud and find the service in your dashboard, once selected go to the Service Credentials tab. The image below is the Service Credentials tab for a Language Translator service.
Copy the url
, username
and password
for each service and paste them in into credentials.xml
in Android Studio as shown below. Do the same for other services as well.
Build and run the application
Build the application
After providing the credentials for all three Watson services (Language Translator, Speech to Text, Text to Speech) we can now build and run the project. We can either run the application via a connected device or build the APK first and transfer it to a mobile phone to be installed manually. Let’s look at both methods.
Transfer the application to a connected device
Running an Android project on a connected device is an efficient way of debugging projects. It requires the relevant drivers to be installed on both the mobile device and Android Studio. It also requires the user to enable developer mode on your mobile device.
We must first download and install Google USB Driver on Android Studio. Note, that if you are developing on macOS or Linux then you do not need to install the USB driver, instead refer to Using Hardware Devices.
In some cases, additional drivers are needed. When creating this guide, which was tested on Samsung Galaxy S8+ running Android version 7.0, we had to install USB drivers for Samsung on Windows.
Finally, the last step we need to complete to use our device as a connected debugging device is to enable USB debugging. To do so, we need to enable “Developer Mode”. We do this by going into the device’s Settings selecting About Phone, then Software Information, and tapping Build number seven (7) times. Now go to Settings and a new menu, Developer Options will appear, enable USB Debugging to continue.
Now we’re all set for running and debugging on your connected device. Simply click the Play button on the menu bar of Android Studio, shown below in a screenshot:
You should see your connected device in the Select Deployment Target dialog as shown below.
Click OK and the project will start building and run on the connected device.
Generate and install APK
To install the application as an APK we must first generate the APK. To do so, go to Build and select Build APK. Android Studio will start building the project and generate an APK. After the process is complete, you can go to the APK location by clicking Show in Explorer
in the Event Log shown below.
Transfer this APK file on your mobile device by any means you like (E-mail, sd card, Google Drive, etc). Open a file explorer on your mobile navigate to the location of the transferred APK. Open the APK file. Android may promt you to allow installing from an unknown source, confirm this choice and the application will start installing on your phone.
Running application
In the screenshot below a sample text is translated using the Watson Language Translator service. You can choose which language you want to translate your text into.
You can also use the microphone to record your input using the Watson Speech to Text service. To do this, click the microphone button next to the text box, say a few words, and click the button again to stop the recording. You can also click the play button to hear the translated text, which uses the Watson Text to Speech service.
Understanding the back-end and API calls
In this section, we shall see how our input is being translated and how the APIs are being called for translating the text into the selected language. We shall see the case of calling the LanguageTranslator
API.
We’ll start by importing the Language Translator class by doing:
import com.ibm.watson.developer_cloud.language_translator.v2.LanguageTranslator;
Now let’s create an instance of this class by doing:
private LanguageTranslator translationService;
Now we need to initialize it with the credentials. Note the use of username
, password
and endpoint
/url
:
private LanguageTranslator initLanguageTranslatorService() {
LanguageTranslator service = new LanguageTranslator();
String username = getString(R.string.language_translator_username);
String password = getString(R.string.language_translator_password);
service.setUsernameAndPassword(username, password);
service.setEndPoint(getString(R.string.language_translator_url));
return service;
}
Now we will see what is going on at the back-end of the Translate button. When a user clicks the Translate button, the following function is called:
translate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new TranslationTask().execute(input.getText().toString());
}
});
The click event calls the TranslationTask() which is implementing the AsyncTask with the following code:
private class TranslationTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
showTranslation(translationService.translate(params[0], Language.ENGLISH, selectedTargetLanguage).execute()
.getFirstTranslation());
return "Did translate";
}
}
If you see closely to this background async task, there is an API being called within the function that is setting the text of the translation shown below:
translationService.translate(params[0], Language.ENGLISH, selectedTargetLanguage).execute()
.getFirstTranslation()
This is the call to the Language Translator Service where we are providing 1) the input text, 2) its language of input (default is set to English), and 3) the selected target language.
This Translator API call returns the result of the translation in the string format, which we are providing to the function showTranslation(final string translation)
shown below:
private void showTranslation(final String translation) {
runOnUiThread(new Runnable() {
@Override
public void run() {
translatedText.setText(translation);
}
});
}
As the showTranslation
function is on another thread, separate from the Translation API call we have to add runOnUiThread
, which puts it in the queue and executes after the Translation API call and sets the returned text of translation.
Other API calls work in a similar fashion. Kindly refer to link provided in the resources for the documentation of the Watson Services and their API References.
Summary
In this guide, we learned how to: get started with the Watson Android SDK, build a sample application using Android Studio and Watson services, and we did a deep dive into the code base. Please refer to the the links provided in the resources to see other SDKs and Watson API references. Thanks for reading!
相關推薦
Build an application with the Watson Android SDK in Android Studio
IBM Watson may be best known for competing on the US quiz show Jeopardy, but the technology goes far beyond simple questions and answ
[Angular] Extract Implementation Details of ngrx from an Angular Application with the Facade Pattern
and role module hid change roles trac imp ini Extracting away the implementation details of ngrx from your components using the facade pa
[Nuxt] Setup a "Hello World" Server-Rendered Vue.js Application with the Vue-CLI and Nuxt
clas red eat side pre obj sta ted blog Install: npm install -g vue-cli Init project: vue init nuxt/starter . Run: n
I wanted limits in an experience with the infinite:
In the days and hours prior to totality, our travels took us to several natural spaces to scout out a good location for witnessing the eclipse. We followed
Android sdk在android studio中消失且編譯不了程式
今天開啟Android Studio發現所有的工程開啟後都沒有了Android選項,而且頁面上的除錯按鈕是灰色的,這說明不能除錯程式了,如下圖。萬幸的是後來靜下心來仔細分析問題,最後終於解決了。真的是嚇死寶寶了。 通過排查,發現setting->plugins中的Andro
搬家、備份後啟動Android PANIC :Could not open D:\java2\android\android-sdk-windows\.android\avdtest.ini問題的解決
附圖說明:搬家、備份後啟動Android虛擬機器出現 PANIC : Could not open D:\java2\android\android-sdk-windows\.android\avd\test.ini問題的解決 前幾天,我在整理一些檔案時,將以前好不容易
ubuntu x64安裝Android SDK以及Android studio
安裝32位庫 Android SDK中的adb程式是32位的,Ubuntu x64系統需要安裝32位庫檔案,用於相容32位的程式。 sudo apt-get install -y libc6-i386 lib32stdc++6 lib32gcc1 lib
在PC上安裝Android SDK與Android模擬器
最近重新安裝了一下Android環境,發現現在已經在Google官網找不到獨立的Android SDK可以下載了,而網上的其它教程比較舊,還是描述怎麼SDK Manager裡設定使用國內的映象站點以下載需要的SDK,然而如果因為wall, Android Studio未能在安裝過程中下載安裝好SDK Mana
[已解決]eclipse+ADT+Android SDK 搭建Android 開發環境
目前安卓開發常用的IDE: 1. Android Studio,Android Stuido是Google推出,專門為Android“量身訂做”的,是Google大力支援的一款基於IntelliJ IDEA改造的IDE。 2. eclipse+ADT+And
IDE0006 Error running Xamarin Android project in Visual Studio
del str 耐心 get running 需要 一個 mod uget 這個報錯一般發生在剛創建了一個cross-platform時候發生; 解決方法: 在解決方案上右擊--管理解決方案的nuget程序包; 選擇更新標簽--勾選xamarin.form--然後點擊更新
Using the AWS Lambda Project in Visual Studio
Last week we launched C# and .NET Core support for AWS Lambda. That release provided updated tooling for Visual Studio to help you get started wri
[Android] SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment
從網路上下載了一個範例,開啟時會顯示這個錯誤: I recently tried to import sample Android games I downloaded from Google’s developer website. After importing them into Android St
【已解決】mac上appium報錯:“Could not find aapt Please set the ANDROID_HOME environment variable with the Android SDK root directory path”
resource sset root could not fun ror 環境 apt direct 按照網上教程配置完appium環境後,真機跑自動化過程,遇到如下報錯: appium報錯如下: [ADB] Checking whether aapt is present
eclipse升級Android SDK Tool版本到25.2.5後運行項目報錯Unable to build: the file dx.jar was not loaded from the SDK folder
com 但是 概述 details bsp 更新 href unable 解決辦法 概述 由於最近通過SDK-Manager更新了build-tools,當要用到dx.jar這個包時,自動調用最新版本Android SDK build-tools中dx.jar,但是運行a
android-sdk-windows\build-tools\26.0.0\aapt.exe'' finished with non-zero exit value 1
android-sdk-windows\build-tools\26.0.0\aapt.exe’’ finished with non-zero exit value 1 沒改動程式碼,專案編譯的時候報了這個錯誤 com.android.ide.common.p
[iOS] Application Loader stuck at “Authenticating with the iTunes store” when uploading an iOS app
You have to agree to a new sign up in Application Loader. Select “Application Loader” under the “Xcode -> Open Developer Tool” menu (the first menu to
this android sdk requires an e adt to the latest version
Android平臺與SDK Tools版本、ADT版本的對應關係 Android平臺 SDK Tools的版本 ADT版本 Android 2.2 R7 ADT-0.9.9 Android 2.3
The specified Android SDK Build Tools version (23.0.2) is ignored,
The specified Android SDK Build Tools version (23.0.2) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.2
升級到Android Studio 3.2.1,報The specified Android SDK Build Tools version (25.0.0) is ignored, as it is
升級到Android Studio 3.2.1 ,引入以前公司專案,報 The specified Android SDK Build Tools version (25.0.0) is ignored, as it is below the minimum supported versio
Build A Voice Enabled Cognitive Application with Watson
The new IBM Voice Agent with Watson service links your telephone network with Waston as a self-service call centre agent. In this webcast, Ronan Dalt