Android与JS交互

简介

本文旨在大致介绍Android和JS的交互,并进行了实现。
废话不说直接上代码:

Android与JS交互_第1张图片
图片.png
public class MainActivity extends AppCompatActivity{
    WebView mwebview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mwebview = (WebView) findViewById(R.id.mwebview);
        mwebview.getSettings().setJavaScriptEnabled(true);
        mwebview.loadUrl("file:///android_asset/web.html");
        mwebview.addJavascriptInterface(MainActivity.this,"android");
        mwebview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mwebview.loadUrl(url);
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
    }
    @JavascriptInterface
    public void call_Android(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                startActivityForResult(new Intent(MainActivity.this,LoginActivity.class),100);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 1000:
                String data2 = "我是孩子的ID";
                mwebview.loadUrl("javascript:postInfo('" + data2  + "')");
                break;
        }
    }
}


    

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Button btn_back = (Button) findViewById(R.id.btn_back);

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(1000);
                finish();
            }
        });

    }


}


    


    
    


HTML 内容显示 

内容显示


你可能感兴趣的:(Android与JS交互)