登录
    Technology changes quickly but people's minds change slowly.

H5 与Android混合开发之H5调用android方法

技术宅 破玉 3149次浏览 0个评论

    迫于公司贫穷,人员较少,对于Android开发不专业,我们想着把一套H5程序打包成app,既方便又省事。但是最近需要调用语音、视频相关原生的api,没办法只能考虑打包成app后调用Android方法。
对于目前的webview来说,已经提供了相关的方法

webView.addJavascriptInterface(new JsInterface(), "android");

暴露Android方法

public class JsInterface{
    @JavascriptInterface
     public void call(String userId){
            System.out.println(userId);
     }
}

js 调用

android.call("abcde12345")

那我们就按照上述实现来设计我们的方式,首先webview方面我们使用
AgentWeb这个基于的 Android WebView ,极度容易使用以及功能强大的库,它提供了 Android WebView 一系列的问题解决方案 ,并且轻量和极度灵活。

public class MainActivity extends Activity {
   // WebView webView;
    AgentWeb mAgentWeb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout view=findViewById(R.id.test);
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) view, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go("http://192.168.1.106:3002");
        mAgentWeb.getJsInterfaceHolder().addJavaObject("testandroid",new TestVoice(this));
        IAgentWebSettings agentWebSettings = mAgentWeb.getAgentWebSettings();
        agentWebSettings.getWebSettings().setDomStorageEnabled(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        System.out.println("返回事件");
       if(keyCode==KeyEvent.KEYCODE_BACK){
            if(!mAgentWeb.back()){
                finish();
                return true;
            }else{
                mAgentWeb.back();
                return true;
            }
       }
       return false;
    }
}

然后建立一个TestVoice 类来将Android方法暴露给window对象

public class TestVoice  {

    Intent intent = null;
    private Context mContext;
    public TestVoice(Context context){
        this.mContext = context;
    }
    @JavascriptInterface
    public void hello(String username,String userid){
        System.out.println("hello"+username);
    }

    @JavascriptInterface
    public void call(){
                intent  = new Intent(mContext,TestActivity.class);
                startActivity(intent);
     }
}

然后在我们前端vue页面直接调用

// 调用方法
 window.testandroid.hello("1237","112345")
// 打开activity
 window.testandroid.call()

思路就是将java方法暴露给window对象,然后js就可以调用了


华裳绕指柔, 版权所有丨如未注明 , 均为原创|转载请注明H5 与Android混合开发之H5调用android方法
喜欢 (12)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址