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

Android Studio中为WebView应用集成二维码扫描并实现谷歌搜索跳转

实现扫描二维码后用Google搜索的方案

步骤说明

  • 先确保你的布局文件(activity_main.xml)中已添加WebView控件,示例代码如下:
<WebView
    android:id="@+id/web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  • 修改MainActivity代码,在弹窗确认按钮的点击事件中,将扫描结果传入Google搜索并通过WebView加载页面

修改后的完整代码

public class MainActivity extends AppCompatActivity {
    Button btn_scan;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_scan = findViewById(R.id.btn_scan);
        webView = findViewById(R.id.web_view);
        
        // 配置WebView支持JavaScript(Google搜索页面需要)
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        btn_scan.setOnClickListener(v -> scanCode());
    }

    private void scanCode() {
        ScanOptions options = new ScanOptions();
        options.setPrompt("Volume up to flash on");
        options.setBeepEnabled(true);
        options.setOrientationLocked(true);
        options.setCaptureActivity(CaptureAct.class);
        barlaucher.launch(options);
    }

    ActivityResultLauncher<ScanOptions> barlaucher = registerForActivityResult(new ScanContract(), result -> {
        if (result.getContents() != null) {
            String scanResult = result.getContents();
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Result");
            builder.setMessage(scanResult);
            builder.setPositiveButton("搜索", (dialogInterface, i) -> {
                dialogInterface.dismiss();
                // 处理扫描结果:区分URL和普通文本
                String targetUrl;
                if (scanResult.startsWith("http://") || scanResult.startsWith("https://")) {
                    targetUrl = scanResult;
                } else {
                    // 构造Google搜索链接,用Uri.encode处理特殊字符
                    targetUrl = "https://www.google.com/search?q=" + Uri.encode(scanResult);
                }
                // 用WebView加载目标页面
                webView.loadUrl(targetUrl);
            });
            builder.setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss());
            builder.show();
        }
    });
}

关键代码解释

  1. WebView初始化与配置:在类中声明并初始化WebView,启用JavaScript保证Google搜索页面正常交互。
  2. 弹窗按钮逻辑修改:将原"ok"按钮改为"搜索",点击时判断扫描内容类型:
    • 如果是合法URL(以http/https开头),直接加载该链接
    • 如果是普通文本,将内容编码后拼接到Google搜索链接中,避免特殊字符导致链接失效
  3. WebView加载页面:调用webView.loadUrl()方法加载处理后的链接,完成搜索或网页跳转功能

内容的提问来源于stack exchange,提问作者Bilal Alkahalaifeh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:21:07