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

The following examples show how to use android.webkit.WebView#getContext() . 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: HostJsScope.java    From v9porn with MIT License 6 votes vote down vote up
/**
 * 系统弹出提示框
 *
 * @param webView 浏览器
 * @param message 提示信息
 */
public static void alert(WebView webView, String message) {
    // 构建一个Builder来显示网页中的alert对话框
    AlertDialog.Builder builder = new AlertDialog.Builder(webView.getContext());
    builder.setTitle(webView.getContext().getString(R.string.dialog_title_system_msg));
    builder.setMessage(message);
    builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.setCancelable(false);
    builder.create();
    builder.show();
}
 
Example 2
Source File: ANJAMImplementation.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
private static void callExternalBrowser(WebView webView, Uri uri) {
    String urlParam = uri.getQueryParameter("url");

    if ((webView.getContext() == null)
            || (urlParam == null)
            || (!urlParam.startsWith("http"))) {
        return;
    }
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Uri.decode(urlParam)));
        webView.getContext().startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(webView.getContext(),
                R.string.action_cant_be_completed,
                Toast.LENGTH_SHORT).show();
    }
}
 
Example 3
Source File: ANJAMImplementation.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
private static void callDeepLink(WebView webView, Uri uri) {
    String cb = uri.getQueryParameter("cb");
    String urlParam = uri.getQueryParameter("url");

    LinkedList<Pair<String, String>> list = new LinkedList<Pair<String, String>>();
    list.add(new Pair(KEY_CALLER, CALL_DEEPLINK));

    if ((webView.getContext() == null)
            || (urlParam == null)) {
        loadResult(webView, cb, list);
        return;
    }
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Uri.decode(urlParam)));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        webView.getContext().startActivity(intent);
    } catch (ActivityNotFoundException e) {
        loadResult(webView, cb, list);
    }
}
 
Example 4
Source File: ANJAMImplementation.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
private static void callMayDeepLink(WebView webView, Uri uri) {
    boolean mayDeepLink;
    String cb = uri.getQueryParameter("cb");
    String urlParam = uri.getQueryParameter("url");

    if ((webView.getContext() == null)
            || (webView.getContext().getPackageManager() == null)
            || (urlParam == null)) {
        mayDeepLink = false;
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Uri.decode(urlParam)));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mayDeepLink = intent.resolveActivity(webView.getContext().getPackageManager()) != null;
    }

    LinkedList<Pair<String, String>> list = new LinkedList<Pair<String, String>>();
    list.add(new Pair(KEY_CALLER, CALL_MAYDEEPLINK));
    list.add(new Pair("mayDeepLink", String.valueOf(mayDeepLink)));
    loadResult(webView, cb, list);
}
 
Example 5
Source File: WawlOverrides.java    From kimai-android with MIT License 6 votes vote down vote up
public static void loadWebapp(WebView webView, AppSettings appSettings, boolean doLogin) {
    Context context = webView.getContext();
    Uri url;
    try {
        url = Uri.parse(appSettings.getProfilePathFull());
    } catch (Exception e) {
        webView.loadData(context.getString(R.string.no_valid_path), "text/html", "UTF-16");
        return;
    }

    String url_s = url.toString();
    if (appSettings.isProfileEmpty()) {
        webView.loadData(context.getString(R.string.no_valid_path), "text/html", "UTF-16");
    } else {
        webView.loadUrl(url_s);
        if (doLogin) {
            url_s += "?a=checklogin";
            String postData = "name=" + appSettings.getProfileLoginUsername() + "&password=" + appSettings.getProfileLoginPassword();
            webView.postUrl(url_s, EncodingUtils.getBytes(postData, "base64"));
        }
    }
}
 
Example 6
Source File: CBrowserMainFrame.java    From appcan-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
    if (!((EBrowserActivity) view.getContext()).isVisable()) {
        result.confirm();
    }
    AlertDialog.Builder dia = new AlertDialog.Builder(view.getContext());
    dia.setTitle(EUExUtil.getResStringID("prompt"));
    dia.setMessage(message);
    dia.setCancelable(false);
    dia.setPositiveButton(EUExUtil.getResStringID("confirm"), new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            result.confirm();
        }
    });
    dia.create();
    dia.show();
    return true;
}
 
Example 7
Source File: KCWebViewClient.java    From kerkee_android with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private WebResourceResponse handleImageRequest(final WebView aWebView, final String aUrl, String strMimeType)
{
    KCWebView webView = (KCWebView) aWebView;
    if (mImageDownloader == null)
        mImageDownloader = new KCWebImageDownloader(aWebView.getContext(), webView.getWebPath());
    if (mWebImageHandler==null)
        mWebImageHandler = new KCWebImageHandler(mWebImageListener);

    KCWebImage webImage = mImageDownloader.downloadImageFile(aUrl, mWebImageHandler.add(aUrl));
    InputStream stream = webImage.getInputStream();
    if (stream == null)
    {
        Log.e("image", "current stream is null,download image from net");
        return null;
    }
    return new WebResourceResponse(strMimeType, "utf-8", stream);
}
 
Example 8
Source File: RexxarWebChromeClient.java    From rexxar-android with MIT License 6 votes vote down vote up
@Override
public void onReceivedTitle(WebView view, String title) {
    super.onReceivedTitle(view, title);
    if (TextUtils.isEmpty(title)) {
        return;
    }
    Matcher matcher = Patterns.WEB_URL.matcher(title);
    if (matcher.matches()) {
        return;
    }
    // 部分系统会优先用页面的location作为title,这种情况需要过滤掉
    if (Patterns.WEB_URL.matcher(title).matches()) {
        return;
    }
    // Hack:过滤掉rexxar页面
    if (title.contains(".html?uri=")) {
        return;
    }
    // 设置title
    if (view.getContext() instanceof Activity) {
        ((Activity) view.getContext()).setTitle(Uri.decode(title));
    }
}
 
Example 9
Source File: HostJsScope.java    From v9porn with MIT License 6 votes vote down vote up
/**
 * 系统弹出提示框
 *
 * @param webView 浏览器
 * @param message 提示信息
 */
public static void alert(WebView webView, String message) {
    // 构建一个Builder来显示网页中的alert对话框
    AlertDialog.Builder builder = new AlertDialog.Builder(webView.getContext());
    builder.setTitle(webView.getContext().getString(R.string.dialog_title_system_msg));
    builder.setMessage(message);
    builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.setCancelable(false);
    builder.create();
    builder.show();
}
 
Example 10
Source File: BaseWebActivity.java    From MarkdownEditors with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
    builder.setTitle("注意").setMessage(message).setPositiveButton("确定", null);
    builder.setCancelable(false);
    AlertDialog dialog = builder.create();
    dialog.show();
    result.confirm();
    return true;
}
 
Example 11
Source File: TitleWidget.java    From rexxar-android with MIT License 5 votes vote down vote up
@Override
public boolean handle(WebView view, String url) {
    if (TextUtils.isEmpty(url)) {
        return false;
    }
    Uri uri = Uri.parse(url);
    if (TextUtils.equals(uri.getPath(), getPath())) {
        String title = uri.getQueryParameter(KEY_TITLE);
        if (null != view && view.getContext() instanceof Activity) {
            ((Activity)view.getContext()).setTitle(Uri.decode(title));
        }
        return true;
    }
    return false;
}
 
Example 12
Source File: AbsAgentWebSettings.java    From AgentWeb with Apache License 2.0 4 votes vote down vote up
private void settings(WebView webView) {
    mWebSettings = webView.getSettings();
    mWebSettings.setJavaScriptEnabled(true);
    mWebSettings.setSupportZoom(true);
    mWebSettings.setBuiltInZoomControls(false);
    mWebSettings.setSavePassword(false);
    if (AgentWebUtils.checkNetwork(webView.getContext())) {
        //根据cache-control获取数据。
        mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    } else {
        //没网,则从本地获取,即离线加载
        mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        //适配5.0不允许http和https混合使用情况
        mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
    mWebSettings.setTextZoom(100);
    mWebSettings.setDatabaseEnabled(true);
    mWebSettings.setAppCacheEnabled(true);
    mWebSettings.setLoadsImagesAutomatically(true);
    mWebSettings.setSupportMultipleWindows(false);
    // 是否阻塞加载网络图片  协议http or https
    mWebSettings.setBlockNetworkImage(false);
    // 允许加载本地文件html  file协议
    mWebSettings.setAllowFileAccess(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // 通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
        mWebSettings.setAllowFileAccessFromFileURLs(false);
        // 允许通过 file url 加载的 Javascript 可以访问其他的源,包括其他的文件和 http,https 等其他的源
        mWebSettings.setAllowUniversalAccessFromFileURLs(false);
    }
    mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    } else {
        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    }
    mWebSettings.setLoadWithOverviewMode(false);
    mWebSettings.setUseWideViewPort(false);
    mWebSettings.setDomStorageEnabled(true);
    mWebSettings.setNeedInitialFocus(true);
    mWebSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
    mWebSettings.setDefaultFontSize(16);
    mWebSettings.setMinimumFontSize(12);//设置 WebView 支持的最小字体大小,默认为 8
    mWebSettings.setGeolocationEnabled(true);
    String dir = AgentWebConfig.getCachePath(webView.getContext());
    LogUtils.i(TAG, "dir:" + dir + "   appcache:" + AgentWebConfig.getCachePath(webView.getContext()));
    //设置数据库路径  api19 已经废弃,这里只针对 webkit 起作用
    mWebSettings.setGeolocationDatabasePath(dir);
    mWebSettings.setDatabasePath(dir);
    mWebSettings.setAppCachePath(dir);
    //缓存文件最大值
    mWebSettings.setAppCacheMaxSize(Long.MAX_VALUE);
    mWebSettings.setUserAgentString(getWebSettings()
            .getUserAgentString()
            .concat(USERAGENT_AGENTWEB)
            .concat(USERAGENT_UC)
    );
    LogUtils.i(TAG, "UserAgentString : " + mWebSettings.getUserAgentString());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        // 安卓9.0后不允许多进程使用同一个数据目录,需设置前缀来区分
        // 参阅 https://blog.csdn.net/lvshuchangyin/article/details/89446629
        Context context = webView.getContext();
        String processName = ProcessUtils.getCurrentProcessName(context);
        if (!context.getApplicationContext().getPackageName().equals(processName)) {
            WebView.setDataDirectorySuffix(processName);
        }
    }
}
 
Example 13
Source File: ReactWebViewManager.java    From react-native-GPay with MIT License 4 votes vote down vote up
protected static void dispatchEvent(WebView webView, Event event) {
  ReactContext reactContext = (ReactContext) webView.getContext();
  EventDispatcher eventDispatcher =
    reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
  eventDispatcher.dispatchEvent(event);
}
 
Example 14
Source File: Web3WebviewManager.java    From react-native-web3-webview with MIT License 4 votes vote down vote up
protected static void dispatchEvent(WebView webView, Event event) {
    ReactContext reactContext = (ReactContext) webView.getContext();
    EventDispatcher eventDispatcher =
            reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
    eventDispatcher.dispatchEvent(event);
}
 
Example 15
Source File: FocusWebViewClient.java    From firefox-echo-show with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
    if (url.equals("file:///android_asset/" + LocalizedContent.licensesUrl)) {
        final Context context = view.getContext();

        context.startActivity(new Intent(context, OssLicensesMenuActivity.class));
        return true;
    }

    // If this is an internal URL like focus:about then we load the content ourselves here.
    if (LocalizedContent.handleInternalContent(url, view)) {
        return true;
    }

    // Allow pages to blank themselves by loading about:blank. While it's a little incorrect to let pages
    // access our internal URLs, Chrome allows loads to about:blank and, to ensure our behavior conforms
    // to the behavior that most of the web is developed against, we do too.
    if (url.equals(URLs.ABOUT_BLANK.toString())) {
        return false;
    }

    // shouldOverrideUrlLoading() is called for both the main frame, and iframes.
    // That can get problematic if an iframe tries to load an unsupported URL.
    // We then try to either handle that URL (ask to open relevant app), or extract
    // a fallback URL from the intent (or worst case fall back to an error page). In the
    // latter 2 cases, we explicitly open the fallback/error page in the main view.
    // Websites probably shouldn't use unsupported URLs in iframes, but we do need to
    // be careful to handle all valid schemes here to avoid redirecting due to such an iframe
    // (e.g. we don't want to redirect to a data: URI just because an iframe shows such
    // a URI).
    // (The API 24+ version of shouldOverrideUrlLoading() lets us determine whether
    // the request is for the main frame, and if it's not we could then completely
    // skip the external URL handling.)
    final Uri uri = Uri.parse(url);
    if (!UrlUtils.isSupportedProtocol(uri.getScheme()) &&
            callback != null &&
            IntentUtils.handleExternalUri(view.getContext(), (IWebView) view, url)) {
        return true;
    }

    return super.shouldOverrideUrlLoading(view, url);
}
 
Example 16
Source File: HostJsScope.java    From v9porn with MIT License 4 votes vote down vote up
/**
 * 结束当前窗口
 *
 * @param view 浏览器
 */
public static void goBack(WebView view) {
    if (view.getContext() instanceof Activity) {
        ((Activity) view.getContext()).finish();
    }
}
 
Example 17
Source File: HostJsScope.java    From v9porn with MIT License 4 votes vote down vote up
/**
 * 结束当前窗口
 *
 * @param view 浏览器
 */
public static void goBack(WebView view) {
    if (view.getContext() instanceof Activity) {
        ((Activity) view.getContext()).finish();
    }
}
 
Example 18
Source File: HybirdImpl.java    From PoupoLayer with MIT License 4 votes vote down vote up
@Override
public void injectJsBridge(WebView webView,String JsName) {
    webView.loadUrl("javascript:" + PopUtils.getJsCode(webView.getContext(),JsName));
    mContext=webView.getContext();
    Log.d(POP_TAG,"注入JSBrige成功");
}