You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android语音搜索中startActivityForResult替代方案求助(Java)

Android语音搜索:startActivityForResult的Java替代方案

在Android中,startActivityForResult()已被弃用,官方推荐使用Activity Result API来替代。以下是针对语音搜索功能的完整Java实现方案:

步骤1:注册ActivityResultLauncher

在你的Activity中,首先注册一个ActivityResultLauncher,用于处理语音搜索的返回结果。这个注册操作需要在onCreate()方法中完成(或在Activity创建阶段执行)。

步骤2:启动语音搜索Intent

用launcher.launch(intent)替代原来的startActivityForResult()方法,触发语音搜索。

完整代码示例

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;

public class VoiceSearchActivity extends AppCompatActivity {
    private ActivityResultLauncher<Intent> voiceSearchLauncher;
    private TextView resultTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_search);

        resultTextView = findViewById(R.id.text_view_result);
        Button voiceSearchBtn = findViewById(R.id.btn_voice_search);

        // 注册结果回调
        voiceSearchLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        ArrayList<String> matches = result.getData().getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                        if (matches != null && !matches.isEmpty()) {
                            resultTextView.setText(matches.get(0));
                        }
                    }
                }
        );

        // 绑定按钮点击事件
        voiceSearchBtn.setOnClickListener(v -> startVoiceSearch());
    }

    private void startVoiceSearch() {
        Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请说出要搜索的内容");

        try {
            voiceSearchLauncher.launch(voiceIntent);
        } catch (Exception e) {
            resultTextView.setText("当前设备不支持语音搜索功能");
        }
    }
}

注意事项

  • 确保项目依赖中包含androidx.activity:activity(Android Studio新建项目默认已添加);
  • 语音识别功能依赖设备上的语音识别服务(如Google语音识别),如果设备没有相关服务,需要捕获异常并提示用户;
  • 无需额外申请危险权限,语音搜索使用的是系统自带的识别服务。

内容的提问来源于stack exchange,提问作者Ibrahim Zaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:15:34