tianyizhang0315 2018-03-21 15:42 采纳率: 50%
浏览 2179
已结题

Android华为荣耀8上无法运行google voice recognition的code

想学习一下android studio上面的google voice recognition的code, 在网上找了
sample code之后, 在华为荣耀8实机上运行,button上显示“recognizer not present”.
显示这个实机的Android version 是 7.0,API level 27
图片说明
下面是MainActivity.java

```public class MainActivity extends Activity {
private static final String TAG = "VoiceRecognition";
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private final int AUDIO_REQUEST_CODE = 3;

private TextView textView;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initWidget();

    // Check to see if a recognition activity is present
    PackageManager pm = getPackageManager();
    List<ResolveInfo> activities = pm.queryIntentActivities(
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    if (activities.size() != 0) {
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "You have already granted this permission!",
                            Toast.LENGTH_SHORT).show();
                } else {
                    requestStoragePermission();
                }
                startVoiceRecognitionActivity();
            }
        });
    } else {
        button.setEnabled(false);
        button.setText("Recognizer not present");
    }
}
private void requestStoragePermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.RECORD_AUDIO)) {

        new AlertDialog.Builder(this)
                .setTitle("Permission needed")
                .setMessage("This permission is needed because of this and that")
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[] {Manifest.permission.RECORD_AUDIO}, AUDIO_REQUEST_CODE);
                    }
                })
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();

    } else {
        ActivityCompat.requestPermissions(this,
                new String[] {Manifest.permission.RECORD_AUDIO}, AUDIO_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == AUDIO_REQUEST_CODE)  {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
        }
    }
}


private void initWidget()
{
    textView = (TextView)findViewById(R.id.tv);
    button = (Button)findViewById(R.id.btn);
}

/**
 * Fire an intent to start the speech recognition activity.
 */
private void startVoiceRecognitionActivity() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

    // Display an hint to the user about what he should say.
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please speak now");//注意不要硬编码

    // Given an hint to the recognizer about what the user is going to say
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

    // Specify how many results you want to receive. The results will be sorted
    // where the first result is the one with   higher confidence.
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);//通常情况下,第一个结果是最准确的。

    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
        // Fill the list view with the strings the recognizer thought it could have heard
        ArrayList<String> matches = data.getStringArrayListExtra(
                RecognizerIntent.EXTRA_RESULTS);
        StringBuilder stringBuilder = new StringBuilder();
        int Size = matches.size();
        for(int i=0;i<Size;++i)
        {
            stringBuilder.append(matches.get(i));
            stringBuilder.append("\n");
        }
        textView.setText(stringBuilder);
    }

    super.onActivityResult(requestCode, resultCode, data);
}}
    ```

顺带一提,这个code在上图的API level 22,Android 5.1的虚拟机是可以运行的,但是
在API level 27,Android 8.0就出现了直接跳到“try again”界面(下图)
在Android 5.1
图片说明
在Android 8.0
图片说明
总结一下,其实是两个问题,这个code在华为Android 7.0的实机上无法加载google voice recognition的dialog, 在虚拟机Android8.0 虽然可以加载dialog, 但是无法正常运行voice recognition, 在Android 5.1上可以正常运行。之前有提问过一次,有回答说是6.0后permission的问题,这个code已经加了runtime permission确保麦克风是有permission的,但是问题依然存在。请大神帮忙看下问题到底出在哪。谢谢。

  • 写回答

1条回答 默认 最新

  • threenewbee 2018-03-21 15:44
    关注

    是否安装了支持RecognizerIntent.ACTION_RECOGNIZE_SPEECH

    评论

报告相同问题?

悬赏问题

  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题