JS调用onBackPressed

Posted 嘉禾世兴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS调用onBackPressed相关的知识,希望对你有一定的参考价值。

需求:

安卓页面webview加载H5页面,H5页面能能返回到安卓页面

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.outfit7.talkingfriends.gui.view.wardrobe.R;
import com.outfit7.talkingfriends.gui.view.wardrobe.utils.TelecomUrl;

public class TelecomActivity extends AppCompatActivity {

    /**
     * 自定义的,当js调用history.go时加载的链接,以监听history.go方法的调用
     */
    private final static String ON_BACK_PRESSED = "onBackPressed";
    private static final String RETURN_FLAG = "ShijilongBack";

    private ImageView telecomBack;
    private ImageView phoneClear;
    private EditText phoneNumber;
    private TextView telecomNext;
    private LinearLayout inputLayout;
    private String phone;
    private boolean payState = false;
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_telecom);
        telecomBack = findViewById(R.id.telecomBack);
        phoneClear = findViewById(R.id.phoneClear);
        phoneNumber = findViewById(R.id.phoneNumber);
        telecomNext = findViewById(R.id.telecomNext);
        inputLayout = findViewById(R.id.inputLayout);

        //监听输入
        phoneNumber.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (temp.length() == 0) {
                    phoneClear.setVisibility(View.INVISIBLE);
                    telecomNext.setEnabled(false);
                } else if (temp.length() > 0 && temp.length() < 11) {
                    phoneClear.setVisibility(View.VISIBLE);
                    telecomNext.setEnabled(false);
                } else if (temp.length() == 11) {
                    phoneClear.setVisibility(View.VISIBLE);
                    telecomNext.setEnabled(true);
                }
            }
        });

        //清空输入
        phoneClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneNumber.setText("");
                phoneClear.setVisibility(View.INVISIBLE);
                telecomNext.setEnabled(false);
            }
        });

        //返回
        telecomBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //跳转
        telecomNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftKeyboard();
                phone = phoneNumber.getText().toString();
                inputLayout.setVisibility(View.GONE);
                loadWebView();
            }
        });
    }

    /**
     * 加载支付页面
     */
    private void loadWebView() {
        webView = new WebView(this);
        webView.getSettings().setjavascriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                pageFinished();
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("wanglei", "url=" + url);
                overrideUrlLoading(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        webView.loadUrl(TelecomUrl.assembleUrl(phone));
        setContentView(webView);
    }

    /**
     * 重写js页面window.history.go方法
     */
    public void pageFinished() {
        String script = "javascript:(function(){window.history.go = function(){window.location.href=\'" + ON_BACK_PRESSED + "\';}})()";
        webView.loadUrl(script);
    }

    /**
     * 拦截url加载
     */
    public void overrideUrlLoading(String url) {
        if (url.contains(ON_BACK_PRESSED)) {//拦截返回和取消按钮http://cemp.189.cn:8080/pay/web/onBackPressed
            onBackPressed();
        } else if (url.contains(RETURN_FLAG)) {//拦截支付返回结果,成功和失败都会包含ShijilongBack
            int beginIndex = url.indexOf("code=") + 5;
            String code = url.substring(beginIndex, beginIndex + 1);
            Log.i("wanglei", "code=" + code);
            if (!TextUtils.isEmpty(code)) {
                payState = ("0".equals(code) ? true : false);
                onBackPressed();
            }
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void onBackPressed() {
        //测试支付成功
        if (payState) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }
}

代码中有些业务逻辑,可以自行删除

以上是关于JS调用onBackPressed的主要内容,如果未能解决你的问题,请参考以下文章

片段的条件自定义 OnBackPress

JS调用onBackPressed

在onBackPressed之外的活动中获取当前片段?

在活动中使用 OnBackPressed 方法的一个片段到另一个片段

onBackPressed 上的 Android 片段 NullPointerException

使用 onBackPressed 仅从第一个片段退出 App