Java Code Examples for android.webkit.WebView#post()

The following examples show how to use android.webkit.WebView#post() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UIApi.java    From quickhybrid-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 弹出日期选择对话框
 * <p>
 * 参数:
 * title: 标题
 * datetime: 指定日期 yyyy-MM-dd
 * 返回:
 * date: 格式:yyyy-MM-dd
 */
public static void pickDate(final IQuickFragment webLoader, WebView wv, JSONObject param, final Callback callback) {
    final String title = param.optString("title");
    String date = param.optString("datetime");
    final Calendar calendar = Calendar.getInstance();
    if (!TextUtils.isEmpty(date)) {
        calendar.setTime(DateUtil.convertString2Date(date, "yyyy-MM-dd"));
    }
    wv.post(new Runnable() {
        public void run() {
            DialogUtil.pickDate(webLoader.getPageControl().getActivity(), title, calendar, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, monthOfYear);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    String chooseDate = DateUtil.convertDate(calendar.getTime(), "yyyy-MM-dd");
                    Map<String, Object> map = new HashMap<>();
                    map.put("date", chooseDate);
                    callback.applySuccess(map);
                }
            });
        }
    });
}
 
Example 2
Source File: KCDefaultBrowser.java    From kerkee_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onProgressChanged(WebView view, int newProgress)
{
    if (mLoadingProgressIndicator != null && mLoadingProgressIndicator.getVisibility() == View.VISIBLE)
    {
        int curWidth = view.getWidth() * newProgress / 100;
        mLoadingProgressIndicator.getLayoutParams().width = curWidth;
        mLoadingProgressIndicator.requestLayout();
        if (curWidth == view.getWidth())
        {
            view.post(new Runnable()
            {
                @Override
                public void run()
                {
                    mLoadingProgressIndicator.getLayoutParams().width = 0;
                    mLoadingProgressIndicator.requestLayout();
                }
            });
        }
    }
}
 
Example 3
Source File: BrowserActivity2.java    From MyBlogDemo with Apache License 2.0 6 votes vote down vote up
@Override
    public View initView(Bundle savedInstanceState) {
        View v = LayoutInflater.from(this).inflate(R.layout.activity_browser2, null);
        final String host = getIntent().getStringExtra("HOST");
        final WebView mWeb = (WebView) v.findViewById(R.id.web);
        mWeb.getSettings().setJavaScriptEnabled(true);
        mWeb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWeb.post(new Runnable() {
            @Override
            public void run() {
//                mWeb.loadDataWithBaseURL(Constants.BASE_URL, host, Constants.MIME_TYPE, Constants.ENCODING, Constants.FAIL_URL);
                mWeb.loadUrl("http://svpano.oss-cn-hangzhou.aliyuncs.com/test/pinan/20066_20160527090324857/index.html?from=singlemessage&isappinstalled=0");

            }
        });

        return v;
    }
 
Example 4
Source File: VRActivity.java    From MyBlogDemo with Apache License 2.0 6 votes vote down vote up
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vr);
        mWeb = (WebView) findViewById(R.id.wb);
        mWeb.getSettings().setJavaScriptEnabled(true);
        mWeb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWeb.post(new Runnable() {
            @Override
            public void run() {
//                mWeb.loadDataWithBaseURL(Constants.BASE_URL, host, Constants.MIME_TYPE, Constants.ENCODING, Constants.FAIL_URL);
                mWeb.loadUrl("http://svpano.oss-cn-hangzhou.aliyuncs.com/test/pinan/20066_20160527090324857/index.html?from=singlemessage&isappinstalled=0");

            }
        });
    }
 
Example 5
Source File: JavascriptEvaluation.java    From android-test with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates a script on a given WebView.
 *
 * <p>Scripts are only evaluated when a WebView is deemed sane. That is:
 *
 * <ul>
 *   <li>The WebView's back/forward list's last item agrees with the WebView
 *   <li>The WebView's reported content height is non-zero
 *   <li>The WebView's reported progress is 100
 *   <li>The document.documentElement object for the DOM of the selected window is non-null
 *       <ul>
 *         Scripts are evaluated on the WebKit/Chromium thread (that is - not the Main thread). A
 *         Future is returned which contains the result of the evaluation.
 */
static ListenableFuture<Evaluation> evaluate(
    final WebView view,
    final String script,
    final List<Object> arguments,
    @Nullable final WindowReference window) {
  UnpreparedScript unprepared = new UnpreparedScript(view, script, arguments, window);
  SanitizerTask sanitizer = new SanitizerTask(unprepared);
  view.post(sanitizer);
  ListenableFuture<PreparedScript> preparedScript =
      transform(sanitizer, SCRIPT_PREPARER, directExecutor());
  ListenableFuture<String> rawEvaluation =
      transformAsync(preparedScript, RAW_EVALUATOR, directExecutor());
  ListenableFuture<Evaluation> parsedEvaluation =
      transform(rawEvaluation, DECODE_EVALUATION, directExecutor());
  return parsedEvaluation;
}
 
Example 6
Source File: PopWebViewClient.java    From PoupoLayer with MIT License 5 votes vote down vote up
@Override
public WebResourceResponse shouldInterceptRequest(final WebView webView, String url) {
    //运行在子线程
    Log.d(POP_TAG,"接收的url是:"+url);
    //hrzapi.invoke("printService",{'name':'123','param1':'123'})

    if(url.contains("__HRZ_QUEUE_HAS_MESSAGE_V1")){
        return null;
    }

    if (url.contains("hrz_client_msg")) {
        webView.post(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void run() {
                //必须运行在主线程
                webView.evaluateJavascript("javascript:__HRZCJSBridgeObject.drainMessageQueue();", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        Log.d(POP_TAG,"onReceiveValue:"+value);
                        String postJson = value.replaceAll("\\\\", "");
                        if (!TextUtils.isEmpty(postJson)) {
                            if (mHybirdImpl != null) {
                                mHybirdImpl.invokeAppServices(postJson);
                            }
                        }
                    }
                });
            }
        });
        return null;
    }

    return shouldInterceptRequest(webView, url);
}
 
Example 7
Source File: Web3ViewClient.java    From Web3View with GNU General Public License v3.0 5 votes vote down vote up
private void injectScriptFile(WebView view) {
    String js = jsInjectorClient.assembleJs(view.getContext(), "%1$s%2$s");
    byte[] buffer = js.getBytes();
    String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);

    view.post(() -> view.loadUrl("javascript:(function() {" +
            "var parent = document.getElementsByTagName('head').item(0);" +
            "var script = document.createElement('script');" +
            "script.type = 'text/javascript';" +
            // Tell the browser to BASE64-decode the string into your script !!!
            "script.innerHTML = window.atob('" + encoded + "');" +
            "parent.appendChild(script)" +
            "})()"));
}
 
Example 8
Source File: Web3ViewClient.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private void injectScriptFile(WebView view) {
    String js = jsInjectorClient.assembleJs(view.getContext(), "%1$s%2$s");
    byte[] buffer = js.getBytes();
    String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);

    view.post(() -> view.loadUrl("javascript:(function() {" +
            "var parent = document.getElementsByTagName('head').item(0);" +
            "var script = document.createElement('script');" +
            "script.type = 'text/javascript';" +
            // Tell the browser to BASE64-decode the string into your script !!!
            "script.innerHTML = window.atob('" + encoded + "');" +
            "parent.appendChild(script)" +
            "})()"));
}
 
Example 9
Source File: UIApi.java    From quickhybrid-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 隐藏loading图标
 */
public static void closeWaiting(final IQuickFragment webLoader, WebView wv, JSONObject param, final Callback callback) {
    wv.post(new Runnable() {
        public void run() {
            webLoader.getPageControl().hideLoading();
            callback.applySuccess();
        }
    });
}
 
Example 10
Source File: MessageHandler.java    From OsmGo with MIT License 5 votes vote down vote up
public void sendResponseMessage(PluginCall call, PluginResult successResult, PluginResult errorResult) {
  try {
    PluginResult data = new PluginResult();
    data.put("save", call.isSaved());
    data.put("callbackId", call.getCallbackId());
    data.put("pluginId", call.getPluginId());
    data.put("methodName", call.getMethodName());

    if (errorResult != null) {
      data.put("success", false);
      data.put("error", errorResult);
      Log.d(LogUtils.getCoreTag(), "Sending plugin error: " + data.toString());
    } else {
      data.put("success", true);
      data.put("data", successResult);
    }

    // Only eval the JS code if this is a valid callback id
    if (!call.getCallbackId().equals(PluginCall.CALLBACK_ID_DANGLING)) {
      final String runScript = "window.Capacitor.fromNative(" + data.toString() + ")";

      final WebView webView = this.webView;
      webView.post(new Runnable() {
        @Override
        public void run() {
          webView.evaluateJavascript(runScript, null);
        }
      });
    } else {
      bridge.storeDanglingPluginResult(call, data);
    }

  } catch (Exception ex) {
    Log.e(LogUtils.getCoreTag(), "sendResponseMessage: error: " + ex);
  }
}
 
Example 11
Source File: FocusWebViewClient.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
    // Only update the user visible URL if:
    // 1. The purported site URL has actually been requested
    // 2. And it's being loaded for the main frame (and not a fake/hidden/iframe request)
    // Note also: shouldInterceptRequest() runs on a background thread, so we can't actually
    // query WebView.getURL().
    // We update the URL when loading has finished too (redirects can happen after a request has been
    // made in which case we don't get shouldInterceptRequest with the final URL), but this
    // allows us to update the URL during loading.
    if (request.isForMainFrame()) {

        // WebView will always add a trailing / to the request URL, but currentPageURL may or may
        // not have a trailing URL (usually no trailing / when a link is entered via UrlInputFragment),
        // hence we do a somewhat convoluted test:
        final String requestURL = request.getUrl().toString();
        final String currentURL = currentPageURL;

        if (UrlUtils.urlsMatchExceptForTrailingSlash(currentURL, requestURL)) {
            view.post(new Runnable() {
                @Override
                public void run() {
                    if (callback != null) {
                        callback.onURLChanged(currentURL);
                    }
                }
            });
        }

        if (callback != null) {
            callback.onRequest(request.hasGesture());
        }
    }

    return super.shouldInterceptRequest(view, request);
}
 
Example 12
Source File: JSBridge.java    From JSBridge with MIT License 5 votes vote down vote up
private static JSONObject callAPICallbackComplete(final WebView wv, JSONObject inJsonObj, final JSONObject outJsonObj) {
    final String callbackID = JSBridge.getString(inJsonObj, "callbackID");
    if(callbackID != null) {
        String str = JSBridge.getString(inJsonObj, "removeAfterExecute");
        if(str == null) str = "true";
        final String removeAfterExecute = str;
        wv.post(new Runnable() {
            @Override
            public void run() {
            	wv.loadUrl("javascript: JSBridge._invokeJSCallback('"+callbackID+"',"+removeAfterExecute+",'"+outJsonObj.toString()+"');");
            }
        });
    }
    return outJsonObj;
}
 
Example 13
Source File: AdViewUtils.java    From prebid-mobile-android with Apache License 2.0 4 votes vote down vote up
static void fixZoomIn(final WebView webView, final int expectedWidth, final int expectedHeight) {

        final int minViewHeight = 10;

        //500 millis to find a webViewContentHeight
        //usually it takes 200 millis
        final int contentHeightDelayMillis = 100;
        int queueLimit = 5;

        final LimitedQueueContainer<Integer> contentHeightQueue = new LimitedQueueContainer<>(queueLimit);
        final Set<Integer> contentHeightSet = new HashSet<>(queueLimit);

        webView.post(new Runnable() {
            @Override
            public void run() {

                int webViewHeight = webView.getHeight();

                //case: check if a publisher have called PublisherAdView.setAdSizes()
                //if publisher does not call PublisherAdView.setAdSizes() it is less then 10(e.g 3 instead of 750)
                if (webViewHeight > minViewHeight) {
                    int webViewContentHeight = webView.getContentHeight();

                    //case: wait when webView.getContentHeight() >= expected height from HTML
                    //webView does not contain getContentWidth()
                    if (webViewContentHeight < expectedHeight) {
                        LogUtil.d("fixZoomIn" + " webViewContentHeight:" + webViewContentHeight);
                        contentHeightQueue.add(webViewContentHeight);
                        if (contentHeightQueue.isFull()) {

                            contentHeightSet.clear();
                            contentHeightSet.addAll(contentHeightQueue.getList());

                            if (contentHeightSet.size() == 1) {

                                //case: if it is not possible to get an expected height se scale as is
                                setWebViewScale(webView, webViewHeight, webViewContentHeight);
                                return;
                            }
                        }
                        webView.postDelayed(this, contentHeightDelayMillis);
                    } else {
                        setWebViewScale(webView, webViewHeight, webViewContentHeight);
                    }
                }

            }
        });
    }