简体   繁体   中英

how to integrate google assistant in android for native application?

I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.

  1. API.AI

  2. Actions on Google

  3. Tutorial of Google Assistant

First of all you need to train your model on API.AI to respond upon some text given to the model.

Some code with API.AI FYI:

//Initialize Service

private void initService(final LanguageConfig selectedLanguage) {
        try {
            final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
            final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
                    lang,
                    AIConfiguration.RecognitionEngine.System);
            aiDataService = new AIDataService(this, config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
        Log.w(TAG, "Sending" + textToSend);
        final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
            private AIError aiError;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showHideProgressBar(true);
                if (mVoiceRecorder != null) {
                    mVoiceRecorder.pauseRecording();
                }
            }

            @Override
            protected AIResponse doInBackground(final String... params) {
                final AIRequest request = new AIRequest();
                String query = params[0];
                String event = params[1];

                if (!TextUtils.isEmpty(query))
                    request.setQuery(query);
                if (!TextUtils.isEmpty(event)) {
                    request.setEvent(new AIEvent(event));
                }

                final String contextString = params[2];
                RequestExtras requestExtras = null;
                if (!TextUtils.isEmpty(contextString)) {
                    final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
                    requestExtras = new RequestExtras(contexts, null);
                }

                try {
                    Log.i("API AI Request", "" + request.toString());
                    return aiDataService.request(request, requestExtras);
                } catch (final AIServiceException e) {
                    aiError = new AIError(e);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(final AIResponse response) {
                showHideProgressBar(false);
                speechSentStatus = false;
                okSentStatus = false;
                if (response != null) {
                    onResult(response, flag, textToSend);
                } else {
                    onError(aiError);
                }
            }
        };
        if (flag == OPEN_COMPLAIN_CODE) {
            task.execute("", Config.Events[0], Config.Events[0]);
        } else if (flag == OPEN_DIAGNOSIS_CODE) {
            task.execute("", Config.Events[1], Config.Events[1]);
        } else if (flag == Constants.OPEN_MEDICATION_CODE) {
            task.execute("", Config.Events[2], Config.Events[2]);
        } else if (flag == Constants.OPEN_LABTEST_CODE) {
            task.execute("", Config.Events[3], Config.Events[3]);
        } else if (flag == Constants.COMPLAINTS_ADDED) {
            task.execute("", Config.Events[0], Config.Events[0]);
        } else if (flag == Constants.DIAGNOSIS_ADDED) {
            task.execute("", Config.Events[1], Config.Events[1]);
        } else {
            task.execute(textToSend, null, "");
        }
    }

//Based on result you can handle the business logic

 private void onResult(final AIResponse response, final int flag, final String textToSend) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                apiAiResponseCounter = apiAiResponseCounter + 1;
                isLast = false;
                final Result result = response.getResult();
                Log.w(TAG, "" + result.getFulfillment().getSpeech());
                if (flag == Constants.COMPLAINTS_ADDED) {
                    //method you want to execute on receiving certain text from model
                    send(textToSend.toLowerCase(), DONTTEXT);
                } else if (flag == Constants.DIAGNOSIS_ADDED) {
                    send(textToSend.toLowerCase(), DONTTEXT);
                } else {
                    String error = "";
                    final String speech = result.getFulfillment().getSpeech();
                    if (speech.contains("?")) {
                        if (!result.getAction().equalsIgnoreCase("input.unknown")) {
                            if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
                                //DONOTHING
                            } else {
                                digiMessage(speech, YESNO);
                            }
                        } else {
                            digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
                        }
                    } else {
                        if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
                            digiMessage(speech, ChatMessageAdapter.DURATION);
                        } else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
                            digiMessage(speech, ChatMessageAdapter.FREQUENCY);
                        } else {
                            digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
                        }
                    }

                    if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
                        if (result.isActionIncomplete() == true) {
                            playSpeech(speech);
                        } else {
                            speechBuffer = "";
                            speechBuffer = speech;
                        }
                    } else {
                        if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
                            isLast = true;
                            if (mVoiceRecorder != null) {
                                stopVoiceRecording();
                            }
                        } else {
                            playSpeech(speech);
                        }
                    }
                }
            }
        });
        if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
            Log.w(TAG, "Skipped");
        } else {
            inflateUI(response.getResult());
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM