移动端+html=混合开发(1)js调用移动端方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liyuali2012/article/details/78971548

android写出来的图文混排的页面确实不如html写出来的好看,所以集百家之所长,这种时候还是学习一下混合开发喽!
学了一段时间 html+css+js。简单搭出了html页面,今天要放到移动端,做的一个交互是点击html中的按钮跳转到另一个移动端的页面。记录下简单做法,日后慢慢更新修改。

js写法

这里用了 jQuery-2.1.4.min.js 所以点击事件这样写。

<script type="text/javascript">
    $(function () {
        //判断是ios还是android的方法
        var u = navigator.userAgent.toLowerCase();
        var isApple = /(iphone|ipad|ipod|ios)/i.test(u);
        var isAndroid = /android/i.test(u);

        $("#ok").click(function () {
            if (isApple) {
                //apple终端
                window.location = 'close://';
            } else if (isAndroid) {
                //安卓终端
                Mobile.toJump();
            }
        });
    });
</script>

android端写法

    private void initView() {
        webview = (WebView) findViewById(R.id.webview);

        WebSettings settings = webview.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);
        //禁止使用外部浏览器打开网页
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webview.loadUrl("http://192.168.1.175:8080/api/toExamTest?");
        webview.addJavascriptInterface(this, "Mobile");
    }

    @JavascriptInterface
    public void toJump() {
        Intent intent = new Intent(this, FinishActivity.class);
        startActivity(intent);
    }

ios端写法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //JS发起一个假的URL请求,然后拦截这次请求,再做相应的处理️
    NSString *scheme = [request.URL scheme];
    scheme = [scheme lowercaseString];

    if ([scheme isEqualToString:@"close"]) {
        NSLog(@"拦截了close操作");
        NextViewController *next = [[NextViewController alloc] init];
        [self.navigationController pushViewController:next animated:YES];
        return NO;
    }
    return YES;
}

现在只是ios和android一人写了一个小demo,发现可以实现调起移动端方法。项目还在进行,以后会渐渐成型。

猜你喜欢

转载自blog.csdn.net/liyuali2012/article/details/78971548