Calling Api.ai From Android
I am building an android app in which I am calling api.ai. I want to parse the response and display it to users. Earlier I had written code in node.js which is as below: functi
Solution 1:
I'm connecting with api.ai from android app.
The steps to do are the following
1. Add the dependencies:
compile'ai.api:libai:1.2.2'compile'ai.api:sdk:2.0.1@aar'
2. Create an activity implementing AIListener.
3. Declare AIService,and AIDataService:
private AIService aiService;
private AIDataService aiDataService;
4. Initialize config, services and add listener:
final ai.api.android.AIConfigurationconfig=newai.api.android.AIConfiguration("API_KEY",
ai.api.android.AIConfiguration.SupportedLanguages.Spanish,
ai.api.android.AIConfiguration.RecognitionEngine.System);
// Use with text search
aiDataService = newAIDataService(this, config);
// Use with Voice input
aiService = AIService.getService(this, config);
aiService.setListener(this);
5. Execute async task to make request:
AIRequestaiRequest=newAIRequest();
aiRequest.setQuery(request);
//request--any string you want to send to chat bot to get there corresponding response.
if(aiRequest==null) {
thrownewIllegalArgumentException("aiRequest must be not null");
}
final AsyncTask<AIRequest, Integer, AIResponse> task =
newAsyncTask<AIRequest, Integer, AIResponse>() {
private AIError aiError;
@Overrideprotected AIResponse doInBackground(final AIRequest... params) {
finalAIRequestrequest= params[0];
try {
finalAIResponseresponse= aiDataService.request(request);
// Return response return response;
} catch (final AIServiceException e) {
aiError = newAIError(e);
returnnull;
}
}
@OverrideprotectedvoidonPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
};
task.execute(aiRequest);
6. onResult method
Resultresult= response.getResult();
If the result is a string, the string with the response will be in:
Stringspeech= result.getFulfillment().getSpeech();
Regards. Nuria
Solution 2:
You can refer the official documentation of integrating API.AI here -
https://github.com/api-ai/apiai-android-client
Happy coding.
Post a Comment for "Calling Api.ai From Android"