WebView调用手机拨号和短信功能(非自己写的网页)

该博客介绍了如何在WebView中处理链接,以便当用户点击`tel:`和`sms:`链接时,能够触发手机的拨号和短信功能。通过`shouldOverrideUrlLoading`方法拦截URL,并根据URL的类型调用`ACTION_CALL`或`ACTION_SENDTO` Intent来实现相应的功能。在Android 6.0及以上版本,还需要检查权限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 webView.setWebViewClient(new WebViewClient() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            String tag;
            String mobile = url.substring(url.lastIndexOf("/") + 1);//获取网页的电话号码
            Uri uri = Uri.parse( mobile);
            if (url.contains("tel:")) {
                tag = "tel:";
                usePhone(tag,uri);
                Log.e("===",mobile);
            }else if (url.contains("sms:")){
                tag = "sms:";
                usePhone(tag,uri);
            }else {
                view.loadUrl(url);
            }
            return true;
        }
    });

}

public void usePhone(String tag , Uri uri){

        if(tag.equals("tel:")){
            Intent intent = new Intent(Intent.ACTION_CALL, uri);//拨打电话
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断手机系统是不是6.0及以上
                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1);
                } else {
                    startActivity(intent);
                }
            }else {
                startActivity(intent);
            }
        }else if (tag.equals("sms:")){
            Intent mIntent = new Intent(Intent.ACTION_SENDTO,uri);//发送短信(号码自动导入)
            startActivity(mIntent);
        }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值