简体   繁体   English

如何将Google Assistant集成到Android的本机应用程序中?

[英]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. 我已经看过很多有关API.AI的教程,但没有得到确切的解决方案。 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 API

  2. Actions on Google 在Google上的操作

  3. Tutorial of Google Assistant Google Assistant教程

First of all you need to train your model on API.AI to respond upon some text given to the model. 首先,您需要在API.AI上训练模型以响应提供给模型的一些文本。

Some code with API.AI FYI: 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());
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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