android项目嵌套uniapp页面及交互

之前说过会更新一期,原生android代码里怎么嵌套uniapp页面,以及两者之间怎么交互数据。今天它来了~

如果是早期的android开发工程师,一定记得当初android+webview+h5混合开发的那个阶段,这次也是类似,废话不多说,上代码,简单明了。

准备工作:

自行准备好androidstudio及安卓项目,hbuilder及uniapp项目

1. 把uniapp项目打包成后h5

对着uniapp项目,鼠标右键 -> 发行 -> 网站PC Web或者手机H5 

然后点击发行

 

经过短暂的 “真男人就5秒” 之后,控制台会打印出生成的h5工程位置

 点击就可以看到在磁盘中的位置以及内容

 

 2. 把打包的h5工程,放到android项目的assets目录下

如图所示,放在放到assets目录下,因为我是做了三个部分,转诊(referral),远程会诊(remote), 交流学习(study) 三个模块(名字是我自己自由命名的),所以只需要按上面的步骤生成三个h5工程就行。你们应该就一个,而且外层的名字可以自己命名。

 如果你发现你的android工程的目录结构跟我不一样,看一下上图,我设置箭头的位置,选择project视图模式就行了。如果你的main文件夹下没有asset目录,不会创建的话,就对着main文件夹,鼠标右键选择 New -> Folder -> Assets Folder 就可以了

 

3. 在需要嵌入uniapp页面的android页面里,使用webview并嵌套

android页面代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

android嵌套代码

private void initView() {
        //要嵌套的uniapp页面所在安卓下的路径(也就是assets下的路径,记得
        //assets路径就是要写成android_asset,不要改)
        String url = "file:///android_asset/remote/index.html";
        WebSettings webSettings = webView.getSettings();
        //可以访问https
        webSettings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //开启JavaScript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //下面这些都是设置,自行结合项目需要删减    
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadsImagesAutomatically(true);
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        String dir = getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setGeolocationDatabasePath(dir);
        webSettings.supportMultipleWindows();
        webSettings.setAllowContentAccess(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDomStorageEnabled(true);
        //这一行代码很重要,先往下看,这个就是调用传值的方法,后面会解释
        //webView.addJavascriptInterface(WebUtil.getInstance(),"webUtil");
        //加载url
        webView.loadUrl(url);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            @SuppressWarnings("deprecation")
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
                super.onReceivedSslError(view, handler, error);
            }
        });
    }

至此为止,你的android项目就可以成功加载uniapp打包后的页面了。但是我们肯定不只是加载个页面这么简单,还要交互数据,传值。接着往下看

1. 创建工具类,把传值操作方法放进去

public class WebUtil {

    private static WebUtil instance=new WebUtil();

    public static WebUtil getInstance(){
        if(instance == null){
            instance = new WebUtil();
        }
        return instance;
    }

    private Context context;

    public void setContext(Context context) {
        this.context = context;
    }

    @JavascriptInterface
    public String getRole(){
        Integer identity = (Integer) SPUtils.getData(context, "identity", -1);
        return String.valueOf(identity);
    }

    @JavascriptInterface
    public String getUserToken() {
        String token = (String) SPUtils.getData(context, "token", "");
        return token;
    }

    @JavascriptInterface
    public void joinMeet(String data){
        Gson gson=new Gson();
        TodayConsultationBean bean = gson.fromJson(data, TodayConsultationBean.class);
        enterMeeting(bean);
    }


    @JavascriptInterface
    public void toLogin(){
        Intent intent=new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @JavascriptInterface
    public void toBook(){
        Intent intent=new Intent(context, RemoteConsultBookActivity.class);
        context.startActivity(intent);
    }

    @JavascriptInterface
    public void toTrain(String meetId,String topic,String ownerName){
        Intent intent=new Intent(context, TrainVideoActivity.class);
        intent.putExtra("meetID",Integer.parseInt(meetId));
        intent.putExtra("topic",topic);
        intent.putExtra("ownerName",ownerName);
        intent.putExtra("meetPwd","");
        context.startActivity(intent);
    }

    private void enterMeeting(TodayConsultationBean bean) {
        int meetID = -1;
        try {
            meetID = TextUtils.isEmpty(bean.getConference_number())?0:Integer.parseInt(bean.getConference_number());
        } catch (Exception e) {
        }
        if (!TextUtils.isEmpty(bean.getConference_number())){
            if (meetID < 0 || bean.getConference_number().length() != 8) {
                Toast.makeText(context, R.string.err_meetid_prompt, Toast.LENGTH_SHORT).show();
                return;
            }
        }
        boolean isCreateMeeting=false;
        if (bean.getIsCreateUser()==0 && TextUtils.isEmpty(bean.getConference_number())){
            isCreateMeeting=true;
        }
        enterMeetingActivity(meetID, "", isCreateMeeting,bean);
    }

    private void enterMeetingActivity(int meetID, String meetPswd,
                                      boolean createMeeting,TodayConsultationBean bean) {
        Intent intent = new Intent(context, MeetingsActivity.class);
        intent.putExtra("meetID",meetID);
        intent.putExtra("meetPwd",meetPswd);
        intent.putExtra("createMeeting",createMeeting);
        intent.putExtra("bean",bean);
        context.startActivity(intent);
    }
}

可以看到,这里我就用到的一些方法。我来说明下什么意思哈

如果你希望你的这个方法能够被uniapp调用,那么就在这个方法上面加上一个注解@JavascriptInterface 即可,就标记这个方法可以被网页调用了

如果你想uniapp给android传值,你就可以在这个方法里加上入参就行,比如我这里的joinMeet方法和toTrain方法,方法的参数就是uniapp传值给android

如果你想android传值给uniapp,你就给这个方法加上返回值,如我这里的getRole和getUserToken方法

2. 把工具类对象放入到webview中(就是上面代码我注释的地方)

 这个就是把我们的工具类放入到webview中,供uniapp调用,第一个参数是工具类对象,第二个字符串参数就是给这个对象起的名字,自由命名,我起的名字叫webUtil

3. 在uniapp端调用

比如像token啊,role啊,你希望在uniapp页面一加载就要获取到,所以在工程下的App.vue里写上如下代码

<script>
	export default {
		globalData:{
			token:null,
			role:-1
		},
		onLaunch: function() {
			let token=window.webUtil.getUserToken();
			let role=window.webUtil.getRole();
		    uni.setStorageSync('token',token);
			uni.setStorageSync('role',role);
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>

就可以拿到了token和role了,放到缓存里就可以各个页面自由调用了

又或者其他页面的methods中调用

 但是注意,必须使用   window.你起的工具类对象名.方法  这样的格式来操作

好了,到此为止,android原生工程里嵌套uniapp页面,并且互相传值就搞定了

本人个人原创,如有雷同,纯属巧合,或者与本人联系,做改动。请转载或者CV组合标明出处,谢谢!(如有疑问或错误欢迎指出,本人QQ:752231513)

  • 2
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值