Example usage for android.webkit WebSettings setCacheMode

List of usage examples for android.webkit WebSettings setCacheMode

Introduction

In this page you can find the example usage for android.webkit WebSettings setCacheMode.

Prototype

public abstract void setCacheMode(@CacheMode int mode);

Source Link

Document

Overrides the way the cache is used.

Usage

From source file:com.pursuer.reader.easyrss.VerticalSingleItemView.java

@SuppressLint("SetJavaScriptEnabled")
public void loadContent() {
    final WebSettings settings = webView.getSettings();
    settings.setDefaultTextEncodingName(HTTP.UTF_8);
    settings.setJavaScriptEnabled(true);
    settings.setDefaultFontSize(fontSize);
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setRenderPriority(RenderPriority.LOW);

    final StringBuffer content = new StringBuffer();
    if (item.getState().isCached()) {
        settings.setBlockNetworkImage(true);
        content.append(DataUtils.readFromFile(new File(item.getFullContentStoragePath())));
    } else {//from   w  w  w  .ja v a  2s. com
        final SettingImageFetching sImgFetch = new SettingImageFetching(dataMgr);
        if (NetworkUtils.checkImageFetchingNetworkStatus(context, sImgFetch.getData())) {
            settings.setBlockNetworkImage(false);
            content.append(DataUtils.readFromFile(new File(item.getOriginalContentStoragePath())));
        } else {
            settings.setBlockNetworkImage(true);
            content.append(DataUtils.readFromFile(new File(item.getStrippedContentStoragePath())));
        }
    }
    content.append(DataUtils.DEFAULT_JS);
    content.append(
            theme == SettingTheme.THEME_NORMAL ? DataUtils.DEFAULT_NORMAL_CSS : DataUtils.DEFAULT_DARK_CSS);
    webView.loadDataWithBaseURL("file://" + item.getStoragePath() + "/", content.toString(), null, "utf-8",
            null);
}

From source file:org.freshrss.easyrss.VerticalSingleItemView.java

@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public void loadContent() {
    final WebSettings settings = webView.getSettings();
    settings.setDefaultTextEncodingName(HTTP.UTF_8);
    settings.setJavaScriptEnabled(true);
    settings.setDefaultFontSize(fontSize);
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    //settings.setRenderPriority(RenderPriority.LOW);

    final StringBuffer content = new StringBuffer();
    if (item.getState().isCached()) {
        content.append(DataUtils.readFromFile(new File(item.getFullContentStoragePath())));
    } else {//ww w  .j  av a  2 s  .co m
        final SettingImageFetching sImgFetch = new SettingImageFetching(dataMgr);
        if (NetworkUtils.checkImageFetchingNetworkStatus(context, sImgFetch.getData())) {
            content.append(DataUtils.readFromFile(new File(item.getOriginalContentStoragePath())));
        } else {
            content.append(DataUtils.readFromFile(new File(item.getStrippedContentStoragePath())));
        }
    }
    content.append(DataUtils.DEFAULT_JS);
    content.append(
            theme == SettingTheme.THEME_NORMAL ? DataUtils.DEFAULT_NORMAL_CSS : DataUtils.DEFAULT_DARK_CSS);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    webView.loadDataWithBaseURL("file://" + item.getStoragePath() + "/", content.toString(), null, "utf-8",
            null);
}

From source file:no.digipost.android.gui.metadata.ExternalLinkWebview.java

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ((DigipostApplication) getApplication()).getTracker(DigipostApplication.TrackerName.APP_TRACKER);
    setContentView(R.layout.activity_externallink_webview);
    Bundle bundle = getIntent().getExtras();
    fileUrl = bundle.getString("url", "https://www.digipost.no");

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from  w ww.ja  v a 2  s .c o m*/
    actionBar = getSupportActionBar();
    if (actionBar != null) {
        setActionBarTitle(fileUrl);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setBackgroundDrawable(new ColorDrawable(0xff2E2E2E));

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(
                    ContextCompat.getColor(this, R.color.metadata_externalbrowser_top_background));
        }
    }

    progressSpinner = (ProgressBar) findViewById(R.id.externallink_spinner);
    webView = (WebView) findViewById(R.id.externallink_webview);
    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    settings.setDomStorageEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(true);
    enableCookies(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (firstLoad) {
                progressSpinner.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                firstLoad = false;
            }
            setActionBarTitle(view.getUrl());
        }
    });

    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(final String url, final String userAgent, final String content,
                final String mimeType, final long contentLength) {
            fileName = URLUtil.guessFileName(url, content, mimeType);
            fileUrl = url;
            onComplete = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        showDownloadSuccessDialog(context);
                    }
                }
            };

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
            if (!mimeType.equals("text/html")) {
                if (FileUtilities.isStorageWriteAllowed(getApplicationContext())) {
                    showDownloadDialog(userAgent, content, mimeType, contentLength);
                } else {
                    showMissingPermissionsDialog();
                }
            }
        }
    });

    if (FileUtilities.isStorageWriteAllowed(this)) {
        webView.loadUrl(fileUrl);
    } else {
        showPermissionsDialog();
    }
}

From source file:org.golang.app.WViewActivity.java

private void initWebView(WebView webView) {

    WebSettings settings = webView.getSettings();

    settings.setJavaScriptEnabled(true);
    settings.setAllowFileAccess(true);/*from  w  ww. java  2 s .c om*/
    settings.setDomStorageEnabled(true);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    settings.setSupportZoom(true);
    // settings.setPluginsEnabled(true);
    methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
    // settings.setPluginState(PluginState.ON);
    methodInvoke(settings, "setPluginState", new Class[] { PluginState.class },
            new Object[] { PluginState.ON });
    // settings.setPluginsEnabled(true);
    methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
    // settings.setAllowUniversalAccessFromFileURLs(true);
    methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class },
            new Object[] { true });
    // settings.setAllowFileAccessFromFileURLs(true);
    methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class },
            new Object[] { true });

    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webView.clearHistory();
    webView.clearFormData();
    webView.clearCache(true);

    webView.setWebChromeClient(new MyWebChromeClient());
    // webView.setDownloadListener(downloadListener);
}

From source file:cn.zy.ef.fragment.WebViewFragment.java

protected void configureWebView(WebSettings settings) {
    settings.setJavaScriptCanOpenWindowsAutomatically(true);//js??window.open()false
    settings.setJavaScriptEnabled(true);//??jsfalsetrue????XSS?
    settings.setSupportZoom(true);//??true
    settings.setBuiltInZoomControls(false);//?false
    settings.setUseWideViewPort(true);//???
    settings.setLoadWithOverviewMode(true);//setUseWideViewPort(true)
    settings.setAppCacheEnabled(true);//?
    settings.setDomStorageEnabled(true);//DOM Storage
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
}

From source file:au.com.wallaceit.reddinator.TabCommentsFragment.java

@SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" })
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this.getActivity();
    SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    global = (GlobalObjects) mContext.getApplicationContext();
    final boolean load = getArguments().getBoolean("load");

    // get needed activity values
    articleId = getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_ID);
    permalink = getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_PERMALINK);

    ll = new LinearLayout(mContext);
    ll.setLayoutParams(new WebView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 0, 0));
    // fixes for webview not taking keyboard input on some devices
    mWebView = new WebView(mContext);
    mWebView.setLayoutParams(new WebView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 0, 0));
    ll.addView(mWebView);/* w  w  w .  ja va  2  s . com*/
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true); // enable ecmascript
    webSettings.setDomStorageEnabled(true); // some video sites require dom storage
    webSettings.setSupportZoom(false);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setDisplayZoomControls(false);
    int fontSize = Integer.parseInt(mSharedPreferences.getString("commentfontpref", "18"));
    webSettings.setDefaultFontSize(fontSize);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    mSharedPreferences.getString("titlefontpref", "16");

    final String themeStr = global.mThemeManager.getActiveTheme("appthemepref").getValuesString();
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean redditLink = false;
            System.out.println(url);
            if (url.indexOf("file://") == 0) { // fix for short sub and user links
                url = url.replace("file://", "https://www.reddit.com") + "/.compact";
                redditLink = true;
            }
            if (redditLink || url.indexOf("https://www.reddit.com/") == 0) {
                Intent i = new Intent(mContext, WebViewActivity.class);
                i.putExtra("url", url);
                startActivity(i);
            } else {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
            }
            return true; // always override url
        }

        public void onPageFinished(WebView view, String url) {
            mWebView.loadUrl("javascript:init(\"" + StringEscapeUtils.escapeJavaScript(themeStr) + "\", \""
                    + global.mRedditData.getUsername() + "\")");
            if (load)
                load();
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient());

    mWebView.requestFocus(View.FOCUS_DOWN);
    WebInterface webInterface = new WebInterface(mContext);
    mWebView.addJavascriptInterface(webInterface, "Reddinator");

    mWebView.loadUrl("file:///android_asset/comments.html#" + articleId);
}

From source file:com.company.millenium.iwannask.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //GPS/* www.  j a v  a  2  s .c  om*/
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(this);
            }
        }

        public void onStatusChanged(String string, int integer, Bundle bundle) {

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
    }

    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    Intent mIntent = getIntent();
    URL = Constants.SERVER_URL;
    if (mIntent.hasExtra("url")) {
        myWebView = null;
        startActivity(getIntent());
        String url = mIntent.getStringExtra("url");
        URL = Constants.SERVER_URL + url;
    }

    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath());
    myWebView.getSettings().setGeolocationEnabled(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setUseWideViewPort(false);
    if (!DetectConnection.checkInternetConnection(this)) {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        showNoConnectionDialog(this);
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new webappinterface(this), "android");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);

    //location test
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            CookieSyncManager.getInstance().sync();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(Constants.HOST)
                    || Uri.parse(url).getHost().equals(Constants.WWWHOST)) {
                // This is my web site, so do not override; let my WebView load
                // the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch
            // another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });
    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) {
                        request.grant(request.getResources());
                    } else {
                        request.deny();
                    }
                }
            });
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {

            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

    });
    // setContentView(myWebView);
    //        myWebView.loadUrl(URL);
    myWebView.loadUrl(URL);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
        }
    };

    //CookieManager mCookieManager = CookieManager.getInstance();
    //Boolean hasCookies = mCookieManager.hasCookies();
    //while(!hasCookies);

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        //intent.putExtra("session", session);
        startService(intent);
    }

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity
        startActivity(new Intent(MainActivity.this, MyIntro.class));
    }
    //if (!isOnline())
    //    showNoConnectionDialog(this);
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();

    //Pull-to-refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
}

From source file:com.example.administrator.mywebviewdrawsign.SysWebView.java

/**
 * Initialize webview./*  w ww  .  j  a v  a  2 s.c  o m*/
 */
@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
private void setup() {
    this.setInitialScale(0);
    this.setVerticalScrollBarEnabled(true);
    this.setHorizontalScrollBarEnabled(true);
    this.requestFocusFromTouch();
    // Enable JavaScript
    WebSettings settings = this.getSettings();

    settings.setBuiltInZoomControls(false);// ??
    settings.setUseWideViewPort(false);
    settings.setLoadWithOverviewMode(true);
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    settings.setAllowFileAccess(true);
    settings.setAppCacheMaxSize(1024 * 1024 * 32);
    settings.setAppCachePath(mContext.getFilesDir().getPath() + "/cache");
    settings.setAppCacheEnabled(true);
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    // Set Cache Mode: LOAD_NO_CACHE is noly for debug
    //settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    //enablePageCache(settings,5);
    //enableWorkers(settings);

    // Enable database
    settings.setDatabaseEnabled(true);
    String databasePath = mContext.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    settings.setDatabasePath(databasePath);

    // Enable DOM storage
    settings.setDomStorageEnabled(true);

    // Enable built-in geolocation
    settings.setGeolocationEnabled(true);

    // Improve render performance
    settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

    if (Build.VERSION.SDK_INT >= 21) {
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
}

From source file:com.nbplus.hybrid.BasicWebViewClient.java

/**
 * ??.//from  w  w w.  j a v  a2  s  . c  om
 * @param activity : context
 * @param view : ?? 
 */
public BasicWebViewClient(Activity activity, WebView view, String alertTitleString, String confirmTitleString) {
    mWebView = view;
    mContext = activity;

    // This will handle downloading. It requires Gingerbread, though
    mDownloadManager = (DownloadManager) mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
    mWebChromeClient = new BroadcastWebChromeClient();

    // Enable remote debugging via chrome://inspect
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        mWebView.setWebContentsDebuggingEnabled(true);
    }
    mWebView.setWebChromeClient(mWebChromeClient);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setGeolocationEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    // Use WideViewport and Zoom out if there is no viewport defined
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        webSettings.setMediaPlaybackRequiresUserGesture(false);
    }

    // Enable pinch to zoom without the zoom buttons
    webSettings.setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        webSettings.setDisplayZoomControls(false);
    }

    webSettings.setAppCacheEnabled(true);
    mWebView.clearCache(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Sets whether the WebView should allow third party cookies to be set.
        // Allowing third party cookies is a per WebView policy and can be set differently on different WebView instances.

        // Apps that target KITKAT or below default to allowing third party cookies.
        // Apps targeting LOLLIPOP or later default to disallowing third party cookies.
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setAcceptThirdPartyCookies(mWebView, true);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mWebView.getSettings().setTextZoom(100);
    }

    if (StringUtils.isEmptyString(alertTitleString)) {
        mAlertTitleString = activity.getString(R.string.default_webview_alert_title);
    } else {
        mAlertTitleString = alertTitleString;
    }

    if (StringUtils.isEmptyString(confirmTitleString)) {
        mConfirmTitleString = activity.getString(R.string.default_webview_confirm_title);
    } else {
        mConfirmTitleString = confirmTitleString;
    }

    mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            mContext.startActivity(intent);

        }
    });

    Log.d(TAG, ">> user agent = " + mWebView.getSettings().getUserAgentString());
}

From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java

@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface", "NewApi" })
@Override//from  w  w  w .j a v  a  2  s.  c  o m
public void onCreate(Bundle savedInstanceState) {
    if (CloudConstants.isContentBrandingApp()) {
        super.setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.action_screen);
    mBranding = (WebView) findViewById(R.id.branding);
    WebSettings brandingSettings = mBranding.getSettings();
    brandingSettings.setJavaScriptEnabled(true);
    brandingSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        brandingSettings.setAllowFileAccessFromFileURLs(true);
    }
    mBrandingHttp = (WebView) findViewById(R.id.branding_http);
    mBrandingHttp.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    WebSettings brandingSettingsHttp = mBrandingHttp.getSettings();
    brandingSettingsHttp.setJavaScriptEnabled(true);
    brandingSettingsHttp.setCacheMode(WebSettings.LOAD_DEFAULT);

    if (CloudConstants.isContentBrandingApp()) {
        mSoundThread = new HandlerThread("rogerthat_actionscreenactivity_sound");
        mSoundThread.start();
        Looper looper = mSoundThread.getLooper();
        mSoundHandler = new Handler(looper);

        int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (cameraPermission == PackageManager.PERMISSION_GRANTED) {
            mQRCodeScanner = QRCodeScanner.getInstance(this);
            final LinearLayout previewHolder = (LinearLayout) findViewById(R.id.preview_view);
            previewHolder.addView(mQRCodeScanner.view);
        }
        mBranding.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                initFullScreenForContentBranding();
            }
        });

        mBrandingHttp.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                initFullScreenForContentBranding();
            }
        });
    }

    final View brandingHeader = findViewById(R.id.branding_header_container);

    final ImageView brandingHeaderClose = (ImageView) findViewById(R.id.branding_header_close);
    final TextView brandingHeaderText = (TextView) findViewById(R.id.branding_header_text);
    brandingHeaderClose
            .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text)));

    brandingHeaderClose.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mQRCodeScanner != null) {
                mQRCodeScanner.onResume();
            }
            brandingHeader.setVisibility(View.GONE);
            mBrandingHttp.setVisibility(View.GONE);
            mBranding.setVisibility(View.VISIBLE);
            mBrandingHttp.loadUrl("about:blank");
        }
    });

    final View brandingFooter = findViewById(R.id.branding_footer_container);

    if (CloudConstants.isContentBrandingApp()) {
        brandingHeaderClose.setVisibility(View.GONE);
        final ImageView brandingFooterClose = (ImageView) findViewById(R.id.branding_footer_close);
        final TextView brandingFooterText = (TextView) findViewById(R.id.branding_footer_text);
        brandingFooterText.setText(getString(R.string.back));
        brandingFooterClose
                .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text)));

        brandingFooter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mQRCodeScanner != null) {
                    mQRCodeScanner.onResume();
                }
                brandingHeader.setVisibility(View.GONE);
                brandingFooter.setVisibility(View.GONE);
                mBrandingHttp.setVisibility(View.GONE);
                mBranding.setVisibility(View.VISIBLE);
                mBrandingHttp.loadUrl("about:blank");
            }
        });
    }

    final RelativeLayout openPreview = (RelativeLayout) findViewById(R.id.preview_holder);

    openPreview.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mQRCodeScanner != null) {
                mQRCodeScanner.previewHolderClicked();
            }
        }
    });

    mBranding.addJavascriptInterface(new JSInterface(this), "__rogerthat__");
    mBranding.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            if (sourceID != null) {
                try {
                    sourceID = new File(sourceID).getName();
                } catch (Exception e) {
                    L.d("Could not get fileName of sourceID: " + sourceID, e);
                }
            }
            if (mIsHtmlContent) {
                L.i("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message);
            } else {
                L.d("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message);
            }
        }
    });
    mBranding.setWebViewClient(new WebViewClient() {
        private boolean isExternalUrl(String url) {
            for (String regularExpression : mBrandingResult.externalUrlPatterns) {
                if (url.matches(regularExpression)) {
                    return true;
                }
            }
            return false;
        }

        @SuppressLint("DefaultLocale")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            L.i("Branding is loading url: " + url);
            Uri uri = Uri.parse(url);
            String lowerCaseUrl = url.toLowerCase();
            if (lowerCaseUrl.startsWith("tel:") || lowerCaseUrl.startsWith("mailto:") || isExternalUrl(url)) {
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                return true;
            } else if (lowerCaseUrl.startsWith(POKE)) {
                String tag = url.substring(POKE.length());
                poke(tag);
                return true;
            } else if (lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://")) {
                if (mQRCodeScanner != null) {
                    mQRCodeScanner.onPause();
                }
                brandingHeaderText.setText(getString(R.string.loading));
                brandingHeader.setVisibility(View.VISIBLE);
                if (CloudConstants.isContentBrandingApp()) {
                    brandingFooter.setVisibility(View.VISIBLE);
                }
                mBranding.setVisibility(View.GONE);
                mBrandingHttp.setVisibility(View.VISIBLE);
                mBrandingHttp.loadUrl(url);
                return true;
            } else {
                brandingHeader.setVisibility(View.GONE);
                brandingFooter.setVisibility(View.GONE);
                mBrandingHttp.setVisibility(View.GONE);
                mBranding.setVisibility(View.VISIBLE);
            }
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            L.i("onPageFinished " + url);
            if (!mInfoSet && mService != null && mIsHtmlContent) {
                Map<String, Object> info = mFriendsPlugin.getRogerthatUserAndServiceInfo(mServiceEmail,
                        mServiceFriend);

                executeJS(true, "if (typeof rogerthat !== 'undefined') rogerthat._setInfo(%s)",
                        JSONValue.toJSONString(info));
                mInfoSet = true;
            }
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            L.i("Checking access to: '" + url + "'");
            final URL parsedUrl;
            try {
                parsedUrl = new URL(url);
            } catch (MalformedURLException e) {
                L.d("Webview tried to load malformed URL");
                return new WebResourceResponse("text/plain", "UTF-8", null);
            }
            if (!parsedUrl.getProtocol().equals("file")) {
                return null;
            }
            File urlPath = new File(parsedUrl.getPath());
            if (urlPath.getAbsolutePath().startsWith(mBrandingResult.dir.getAbsolutePath())) {
                return null;
            }
            L.d("404: Webview tries to load outside its sandbox.");
            return new WebResourceResponse("text/plain", "UTF-8", null);
        }
    });

    mBrandingHttp.setWebViewClient(new WebViewClient() {
        @SuppressLint("DefaultLocale")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            L.i("BrandingHttp is loading url: " + url);
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            brandingHeaderText.setText(view.getTitle());
            L.i("onPageFinished " + url);
        }
    });

    Intent intent = getIntent();
    mBrandingKey = intent.getStringExtra(BRANDING_KEY);
    mServiceEmail = intent.getStringExtra(SERVICE_EMAIL);
    mItemTagHash = intent.getStringExtra(ITEM_TAG_HASH);
    mItemLabel = intent.getStringExtra(ITEM_LABEL);
    mItemCoords = intent.getLongArrayExtra(ITEM_COORDS);
    mRunInBackground = intent.getBooleanExtra(RUN_IN_BACKGROUND, true);
}