webview与Android的交互的完整简单案例(真实项目)

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

*首先先说一下业务需求,现在有个微信版的社区,想要原生做微信登录,然后进行传微信版社区想要拿到的值,大体功能就是这样的。下面上代码。
1、关联相关的包

compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:1.1.6'
compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.google.code.gson:gson:2.5'
compile 'org.xutils:xutils:3.5.0'

2、微信登陆
必须在项目包下简历wyxapi.WXEntryActivity

<activity
            android:exported="true"
            android:name=".wxapi.WXEntryActivity"/>

这块做过微信的都懂吧,我就不介绍了

 wxAPI = WXAPIFactory.createWXAPI(this, Constant.WECHAT_APPID, true);
            wxAPI.registerApp(Constant.WECHAT_APPID);
             SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = String.valueOf(System.currentTimeMillis());//这个随便写,你给啥返回给你啥
        wxAPI.sendReq(req);
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI mWeixinAPI;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWeixinAPI = WXAPIFactory.createWXAPI(this, Constant.WECHAT_APPID, true);
        mWeixinAPI.registerApp(Constant.WECHAT_APPID);
        mWeixinAPI.handleIntent(this.getIntent(), this);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWeixinAPI.handleIntent(intent, this);//必须调用此句话
    }
    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        if(resp.getType()== ConstantsAPI.COMMAND_SENDAUTH){//登陆
            SendAuth.Resp authResp = (SendAuth.Resp) resp;
            WeiXin weiXin=new WeiXin(1,resp.errCode,authResp.code);
            EventBus.getDefault().post(weiXin);
        }
        finish();
    }


}
@Subscribe
    public void onEventMainThread(WeiXin weiXin){
        Log.i("ansen","收到eventbus请求 type:"+weiXin.getType());
        if(weiXin.getType()==1){//登录
            getAccessToken(weiXin.getCode());
        }
    }
    public void getAccessToken(String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid="+Constant.WECHAT_APPID+"&secret="+Constant.WECHAT_SECRET+
                "&code="+code+"&grant_type=authorization_code";
        RequestParams params = new RequestParams(url);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                WeiXinToken weiXinToken = gson.fromJson(result, WeiXinToken.class);

                wxif.setOpenid(weiXinToken.getOpenid());
                wxif.setUnionid(weiXinToken.getUnionid());
                getWeiXinUserInfo(weiXinToken);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public void getWeiXinUserInfo(WeiXinToken weiXinToken){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+
                weiXinToken.getAccess_token()+"&openid="+weiXinToken.getOpenid();
        RequestParams params = new RequestParams(url);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                WeiXinInfo weiXinInfo = gson.fromJson(result, WeiXinInfo.class);
                wxif.setHeadimgurl(weiXinInfo.getHeadimgurl());
                wxif.setNickname(weiXinInfo.getNickname());
                wxif.setAge(weiXinInfo.getAge());
                String s = gson.toJson(wxif);
                sp.edit().putString("unionid",s).commit();
                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

3、给webview传值

public class MainActivity extends AppCompatActivity {

    public  WebView webview;
    private boolean isSuccess = false;
    private boolean isError = false;
    private String mobile;
    private LinearLayout loading_over,ll_control_error;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences userInfo = getSharedPreferences("userInfo", MODE_PRIVATE);
        unionid = userInfo.getString("unionid", "");
        webview = (WebView) findViewById(R.id.tv_login);
        loading_over= (LinearLayout)findViewById(R.id.loading_over);
        ll_control_error = (LinearLayout)findViewById(R.id.ll_control_error);
        webview.setWebViewClient(new WebViewClient() {
                                     @Override
                                     public void onPageStarted(WebView view, String url, Bitmap favicon) {
                                         loading_over.setVisibility(View.VISIBLE);
                                         super.onPageStarted(view, url, favicon);
                                     }

                                     @Override
                                     public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                                         super.onReceivedError(view, request, error);
                                         isError = true;
                                         isSuccess = false;
                                         //6.0以上执行
                                         webview.setVisibility(View.GONE);
                                         ll_control_error.setVisibility(View.VISIBLE);
                                     }

                                     @Override
                                     public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                                         super.onReceivedError(view, errorCode, description, failingUrl);
                                         isError = true;
                                         isSuccess = false;
                                         //6.0以下执行
                                         webview.setVisibility(View.GONE);
                                         ll_control_error.setVisibility(View.VISIBLE);
                                     }

                                     @Override
                                     public void onPageFinished(WebView view, String url) {
                                         if (!isError) {
                                             isSuccess = true;
                                             //回调成功后的相关操作
                                             loading_over.setVisibility(View.GONE);
                                             ll_control_error.setVisibility(View.GONE);
                                             webview.setVisibility(View.VISIBLE);
                                         } else {
                                             isError = false;
                                             loading_over.setVisibility(View.GONE);
                                             ll_control_error.setVisibility(View.VISIBLE);
                                         }
                                        webview.clearHistory();
                                     }

                                     @Override
                                     public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                         if (url.contains("tel")) {
                                             mobile = url.substring(url.lastIndexOf("/") + 1);
                                             //检测权限
                                             requestSdcardSuccess();
                                             //这个超连接,java已经处理了,webview不要处理了
                                             return true;
                                         }
                                         return super.shouldOverrideUrlLoading(view, url);
                                     }


                                 }
        );
        webview.setWebChromeClient(new WebChromeClient());
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setBlockNetworkImage(false);
        webview.getSettings().setBlockNetworkLoads(false);
        webview.getSettings().setDatabaseEnabled(true);
        webview.addJavascriptInterface(new JavaToHtml(), "java");//对象的大小写一定要注意
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webview.loadUrl("http://xxxxxxx");

    }
    /**
     * 返回键返回上一网页
     */
    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    public void requestSdcardSuccess() {
        Uri uri = Uri.parse(mobile);
        Intent intent = new Intent(Intent.ACTION_CALL, uri);
        startActivity(intent);
    }


    private String unionid;
    private class JavaToHtml{
        JavaToHtml(){

        }
        //网页中的js调用window.java.getUinion就可以了,我直接把所有信息转化成json格式了,大家看需求弄自己的
        @JavascriptInterface
        public String getUinion(){
            return unionid;
        }

    }
}

4、切记

webSettings.setJavaScriptEnabled(true);//这个必须加
 @JavascriptInterface//注解必须加
        public String getUinion(){
            return unionid;
        }

可能有的人说为啥我微信的头像的信息拿不到啊,原因签名不对,签名对了的话,就是你用的debug版本的,记住用正式版的才能拿到微信的头像等信息,还有需要注意的就是授权只进行一次,有的人就会说微商登陆页面就看到一次,下次就吊不起来了,不是吊不起来了,而是授权一次,下次直接就自动获取信息了,所以不要困惑。

猜你喜欢

转载自blog.csdn.net/qq939782569/article/details/79674896