Example usage for android.webkit WebViewClient WebViewClient

List of usage examples for android.webkit WebViewClient WebViewClient

Introduction

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

Prototype

WebViewClient

Source Link

Usage

From source file:net.bluecarrot.lite.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // setup the sharedPreferences
    savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // if the app is being launched for the first time
    if (savedPreferences.getBoolean("first_run", true)) {
        //todo presentation
        // save the fact that the app has been started at least once
        savedPreferences.edit().putBoolean("first_run", false).apply();
    }// w w  w . ja v  a  2  s  .c  om

    setContentView(R.layout.activity_main);//load the layout

    //**MOBFOX***//

    banner = (Banner) findViewById(R.id.banner);
    final Activity self = this;

    banner.setListener(new BannerListener() {
        @Override
        public void onBannerError(View view, Exception e) {
            //Toast.makeText(self, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerLoaded(View view) {
            //Toast.makeText(self, "banner loaded", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClosed(View view) {
            //Toast.makeText(self, "banner closed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerFinished(View view) {
            // Toast.makeText(self, "banner finished", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClicked(View view) {
            //Toast.makeText(self, "banner clicked", Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onCustomEvent(JSONArray jsonArray) {
            return false;
        }
    });

    banner.setInventoryHash(appHash);
    banner.load();

    // setup the refresh layout
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setColorSchemeResources(R.color.officialBlueFacebook, R.color.darkBlueSlimFacebookTheme);// set the colors
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    /** get a subject and text and check if this is a link trying to be shared */
    String sharedSubject = getIntent().getStringExtra(Intent.EXTRA_SUBJECT);
    String sharedUrl = getIntent().getStringExtra(Intent.EXTRA_TEXT);

    // if we have a valid URL that was shared by us, open the sharer
    if (sharedUrl != null) {
        if (!sharedUrl.equals("")) {
            // check if the URL being shared is a proper web URL
            if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) {
                // if it's not, let's see if it includes an URL in it (prefixed with a message)
                int startUrlIndex = sharedUrl.indexOf("http:");
                if (startUrlIndex > 0) {
                    // seems like it's prefixed with a message, let's trim the start and get the URL only
                    sharedUrl = sharedUrl.substring(startUrlIndex);
                }
            }
            // final step, set the proper Sharer...
            urlSharer = String.format("https://m.facebook.com/sharer.php?u=%s&t=%s", sharedUrl, sharedSubject);
            // ... and parse it just in case
            urlSharer = Uri.parse(urlSharer).toString();
            isSharer = true;
        }
    }

    // setup the webView
    webViewFacebook = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewFacebook);
    //fits images to screen

    if (isSharer) {//if is a share request
        webViewFacebook.loadUrl(urlSharer);//load the sharer url
        isSharer = false;
    } else
        goHome();//load homepage

    //        webViewFacebook.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
    //            public void onSwipeLeft() {
    //                webViewFacebook.loadUrl("javascript:try{document.querySelector('#messages_jewel > a').click();}catch(e){window.location.href='" +
    //                        getString(R.string.urlFacebookMobile) + "messages/';}");
    //            }
    //
    //        });

    //WebViewClient that is the client callback.
    webViewFacebook.setWebViewClient(new WebViewClient() {//advanced set up

        // when there isn't a connetion
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            String summary = "<h1 style='text-align:center; padding-top:15%; font-size:70px;'>"
                    + getString(R.string.titleNoConnection) + "</h1> <h3 "
                    + "style='text-align:center; padding-top:1%; font-style: italic;font-size:50px;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='font-size:30px; text-align:center; padding-top:80%; "
                    + "opacity: 0.3;'>" + getString(R.string.awards) + "</h5>";
            webViewFacebook.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page

            noConnectionError = true;
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
        }

        // when I click in a external link
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null || Uri.parse(url).getHost().endsWith("facebook.com")
                    || Uri.parse(url).getHost().endsWith("m.facebook.com") || url.contains(".gif")) {
                //url is ok
                return false;
            } else {
                if (Uri.parse(url).getHost().endsWith("fbcdn.net")) {
                    //TODO add the possibility to download and share directly

                    Toast.makeText(getApplicationContext(), getString(R.string.downloadOrShareWithBrowser),
                            Toast.LENGTH_LONG).show();
                    //TODO get bitmap from url

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

                //if the link doesn't contain 'facebook.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } //https://www.facebook.com/dialog/return/close?#_=_
        }

        //START management of loading
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //TODO when I push on messages, open messanger
            //                if(url!=null){
            //                    if (url.contains("soft=messages") || url.contains("facebook.com/messages")) {
            //                        Toast.makeText(getApplicationContext(),"Open Messanger",
            //                                Toast.LENGTH_SHORT).show();
            //                        startActivity(new Intent(getPackageManager().getLaunchIntentForPackage("com.facebook.orca")));//messanger
            //                    }
            //                }

            // show you progress image
            if (!swipeRefresh) {
                if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                    final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                    refreshItem.setActionView(R.layout.circular_progress_bar);
                }
            }
            swipeRefresh = false;
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                refreshItem.setActionView(null);
            }

            //load the css customizations
            String css = "";
            if (savedPreferences.getBoolean("pref_blackTheme", false)) {
                css += getString(R.string.blackCss);
            }
            if (savedPreferences.getBoolean("pref_fixedBar", true)) {

                css += getString(R.string.fixedBar);//get the first part

                int navbar = 0;//default value
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//get id
                if (resourceId > 0) {//if there is
                    navbar = getResources().getDimensionPixelSize(resourceId);//get the dimension
                }
                float density = getResources().getDisplayMetrics().density;
                int barHeight = (int) ((getResources().getDisplayMetrics().heightPixels - navbar - 44)
                        / density);

                css += ".flyout { max-height:" + barHeight + "px; overflow-y:scroll;  }";//without this doen-t scroll

            }
            if (savedPreferences.getBoolean("pref_hideSponsoredPosts", false)) {
                css += getString(R.string.hideSponsoredPost);
            }

            //apply the customizations
            webViewFacebook.loadUrl(
                    "javascript:function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = "
                            + "str; document.body.appendChild(node); } addStyleString('" + css + "');");

            //finish the load
            super.onPageFinished(view, url);

            //when the page is loaded, stop the refreshing
            swipeRefreshLayout.setRefreshing(false);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewFacebook.setWebChromeClient(new WebChromeClient() {
        //to the Geolocation
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            //todo notify when the gps is used
        }

        //to upload files
        //!!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
        // for >= Lollipop, all in one
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            /** Request permission for external storage access.
             *  If granted it's awesome and go on,
             *  otherwise just stop here and leave the method.
             */
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            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
                    Toast.makeText(getApplicationContext(), "Error occurred while creating the File",
                            Toast.LENGTH_LONG).show();
                }

                // 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;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            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, getString(R.string.chooseAnImage));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

            return true;
        }

        // creating image files (Lollipop only)
        private File createImageFile() throws IOException {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            if (!imageStorageDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                imageStorageDir.mkdirs();
            }

            // create an image file name
            imageStorageDir = new File(imageStorageDir + File.separator + "IMG_"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            return imageStorageDir;
        }

        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            mUploadMessage = uploadMsg;

            try {
                File imageStorageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        appDirectoryName);

                if (!imageStorageDir.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    imageStorageDir.mkdirs();
                }

                File file = new File(imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis()) + ".jpg");

                mCapturedImageURI = Uri.fromFile(file); // save to the private variable

                final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                //captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");

                Intent chooserIntent = Intent.createChooser(i, getString(R.string.chooseAnImage));
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });

                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), ("Camera Exception"), Toast.LENGTH_LONG).show();
            }
        }

        // openFileChooser for other Android versions

        /**
         * may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
         * https://code.google.com/p/android/issues/detail?id=62220
         * however newer versions of KitKat fixed it on some devices
         */
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

    });

    // OnLongClickListener for detecting long clicks on links and images
    // !!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
    webViewFacebook.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // activate long clicks on links and image links according to settings
            if (true) {
                WebView.HitTestResult result = webViewFacebook.getHitTestResult();
                if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE
                        || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    Message msg = linkHandler.obtainMessage();
                    webViewFacebook.requestFocusNodeHref(msg);
                    return true;
                }
            }
            return false;
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:nirwan.cordova.plugin.printer.Printer.java

private void loadContentAsBitmapIntoPrintController(String content, final Intent intent) {
    Activity ctx = cordova.getActivity();
    final WebView page = new WebView(ctx);
    final Printer self = this;

    page.setVisibility(View.INVISIBLE);
    page.getSettings().setJavaScriptEnabled(false);

    page.setWebViewClient(new WebViewClient() {
        @Override/*www  .  j  a va  2s.co  m*/
        public void onPageFinished(final WebView page, String url) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Bitmap screenshot = self.takeScreenshot(page);
                    File tmpFile = self.saveScreenshotToTmpFile(screenshot);
                    ViewGroup vg = (ViewGroup) (page.getParent());

                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tmpFile));

                    vg.removeView(page);
                }
            }, 1000);
        }
    });

    //Set base URI to the assets/www folder
    String baseURL = webView.getUrl();
    baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);

    ctx.addContentView(page, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    page.loadDataWithBaseURL(baseURL, content, "text/html", "UTF-8", null);
}

From source file:com.github.dfa.diaspora_android.activity.ShareActivity.java

void handleSendText(Intent intent) {
    final String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    final String sharedBy = getString(R.string.shared_by_diaspora_android);

    if (sharedText != null) {
        webView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {

                webView.setWebViewClient(new WebViewClient() {
                    @Override//from  ww w . j a  va  2  s.  c  o m
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {

                        finish();

                        Intent i = new Intent(ShareActivity.this, MainActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);

                        return false;
                    }
                });

                webView.loadUrl("javascript:(function() { "
                        + "document.getElementsByTagName('textarea')[0].style.height='110px'; "
                        + "document.getElementsByTagName('textarea')[0].innerHTML = '> " + sharedText + " "
                        + sharedBy + "'; " + "    if(document.getElementById(\"main_nav\")) {"
                        + "        document.getElementById(\"main_nav\").parentNode.removeChild("
                        + "        document.getElementById(\"main_nav\"));"
                        + "    } else if (document.getElementById(\"main-nav\")) {"
                        + "        document.getElementById(\"main-nav\").parentNode.removeChild("
                        + "        document.getElementById(\"main-nav\"));" + "    }" + "})();");
            }
        });
    }
}

From source file:com.roger.lineselectionwebview.LSWebView.java

/**
 * Setups up the web view.// www.  jav  a 2s  .  c o  m
 * 
 * @param context
 */
@SuppressLint("SetJavaScriptEnabled")
protected void setup(Context context) {

    // On Touch Listener
    setOnLongClickListener(this);
    setOnTouchListener(this);

    // Webview setup
    getSettings().setJavaScriptEnabled(true);
    getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    getSettings().setPluginState(WebSettings.PluginState.ON);
    // getSettings().setBuiltInZoomControls(true);

    // Webview client.
    setWebViewClient(new WebViewClient() {
        // This is how it is supposed to work, so I'll leave it in, but this
        // doesn't get called on pinch
        // So for now I have to use deprecated getScale method.
        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
            mCurrentScale = newScale;
        }
    });

    // Zoom out fully
    // getSettings().setLoadWithOverviewMode(true);
    // getSettings().setUseWideViewPort(true);

    // Javascript interfaces
    mTextSelectionJSInterface = new TextSelectionJavascriptInterface(context, this);
    addJavascriptInterface(mTextSelectionJSInterface, mTextSelectionJSInterface.getInterfaceName());

    // Create the selection handles
    createSelectionLayer(context);

    // Set to the empty region
    Region region = new Region();
    region.setEmpty();
    mLastSelectedRegion = region;

    // Load up the android asset file
    // String filePath = "file:///android_asset/content.html";

    // Load the url
    // this.loadUrl(filePath);

}

From source file:felixwiemuth.lincal.ui.HtmlDialogFragment.java

@NonNull
@SuppressLint("InflateParams")
@Override// w  w  w.j a  va2 s. co  m
public Dialog onCreateDialog(Bundle savedInstanceState) {
    View content = LayoutInflater.from(getActivity()).inflate(R.layout.html_dialog_fragment, null);
    webView = (WebView) content.findViewById(R.id.html_dialog_fragment_web_view);
    // Set the WebViewClient (in API <24 have to parse URI manually)
    if (Build.VERSION.SDK_INT >= 24) {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                Uri uri = webResourceRequest.getUrl(); // @TargetApi(Build.VERSION_CODES.N_MR1)
                return HtmlDialogFragment.this.loadUrl(webView, uri);
            }
        });
    } else { //TODO test on an API < 24 device
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                Uri uri = Uri.parse(url);
                return HtmlDialogFragment.this.loadUrl(webView, uri);
            }
        });
    }

    indeterminateProgress = (ProgressBar) content
            .findViewById(R.id.html_dialog_fragment_indeterminate_progress);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    Bundle arguments = getArguments();
    // if argument for title is given (string or int referencing a string resource) set the title
    if (arguments.getString(ARG_TITLE) != null) {
        builder.setTitle(arguments.getString(ARG_TITLE));
    } else {
        builder.setTitle(getArguments().getInt(ARG_TITLE)); //TODO error handling
    }
    builder.setView(content);
    return builder.create();
}

From source file:com.quarterfull.newsAndroid.NewsDetailFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void init_webView() {
    int backgroundColor = ColorHelper.getColorFromAttribute(getContext(), R.attr.news_detail_background_color);
    mWebView.setBackgroundColor(backgroundColor);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
    webSettings.setSupportMultipleWindows(false);
    webSettings.setSupportZoom(false);//from  w w w  .j  a  va 2  s .com
    webSettings.setAppCacheEnabled(true);

    registerForContextMenu(mWebView);

    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.v(TAG, cm.message() + " at " + cm.sourceId() + ":" + cm.lineNumber());
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress < 100 && mProgressbarWebView.getVisibility() == ProgressBar.GONE) {
                mProgressbarWebView.setVisibility(ProgressBar.VISIBLE);
            }
            mProgressbarWebView.setProgress(progress);
            if (progress == 100) {
                mProgressbarWebView.setVisibility(ProgressBar.GONE);

                //The following three lines are a workaround for websites which don't use a background color
                int bgColor = ContextCompat.getColor(getContext(),
                        R.color.slider_listview_text_color_dark_theme);
                NewsDetailActivity ndActivity = ((NewsDetailActivity) getActivity());
                mWebView.setBackgroundColor(bgColor);
                ndActivity.mViewPager.setBackgroundColor(bgColor);

                if (ThemeChooser.isDarkTheme(getActivity())) {
                    mWebView.setBackgroundColor(
                            ContextCompat.getColor(getContext(), android.R.color.transparent));
                }
            }
        }
    });

    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (changedUrl) {
                changedUrl = false;

                if (!url.equals("file:///android_asset/") && (urls.isEmpty() || !urls.get(0).equals(url))) {
                    urls.add(0, url);

                    Log.v(TAG, "Page finished (added): " + url);
                }
            }

            super.onPageStarted(view, url, favicon);
        }
    });

    mWebView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (v.getId() == R.id.webview && event.getAction() == MotionEvent.ACTION_DOWN) {
                changedUrl = true;
            }

            return false;
        }
    });
}

From source file:com.pdftron.pdf.controls.ReflowPagerAdapter.java

public void initialize() {
    // set loading file depending on night mode
    if (sIsNightMode) {
        mLoadingFile = NIGHT_MODE_LOADING_FILE;
    } else {/*  w w w . j  a v a 2 s.  c om*/
        mLoadingFile = NORMAL_MODE_LOADING_FILE;
    }

    if (mWebViewRepository != null) {
        mWebViewRepository.reset();
    }

    ReflowWebView[] webViews = mWebViewRepository.getWebViews();
    for (final ReflowWebView webView : webViews) {
        webView.clearCache(true); // reset reading css file
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWillNotCacheDrawing(false);
        if (sIsNightMode) {
            webView.setBackgroundColor(Color.BLACK);
        } else {
            webView.setBackgroundColor(Color.WHITE);
        }
        webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        webView.loadUrl("about:blank");
        webView.setListener(this);

        webView.setWebChromeClient(new WebChromeClient()); // enable the use of methods like alert in javascript
        webView.setWebViewClient(new WebViewClient() {
            // now all links the user clicks load in your WebView
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log.e(TAG, description + " url: " + failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                Log.e(TAG, error.toString());
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("file:///") && url.endsWith(".html")) {
                    int slashPos = url.lastIndexOf('/');
                    try {
                        int objNum = Integer.parseInt(url.substring(slashPos + 1, url.length() - 5));
                        int pageNum = 0;
                        for (int i = 1; i <= mPageCount; i++) {
                            try {
                                Page page = mDoc.getPage(i);
                                if (page.getSDFObj().getObjNum() == objNum) {
                                    pageNum = i;
                                    break;
                                }
                            } catch (Exception e) {
                            }
                        }
                        if (pageNum != 0) {
                            mViewPager.setCurrentItem(pageNum - 1);
                        }
                    } catch (NumberFormatException e) {
                        return true;
                    }
                } else {
                    if (url.startsWith("mailto:")
                            || android.util.Patterns.EMAIL_ADDRESS.matcher(url).matches()) {
                        if (url.startsWith("mailto:")) {
                            url = url.substring(7);
                        }
                        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", url, null));
                        mContext.startActivity(Intent.createChooser(intent,
                                mContext.getResources().getString(R.string.tools_misc_sendemail)));
                    } else {
                        // ACTION_VIEW needs the address to have http or https
                        if (!url.startsWith("https://") && !url.startsWith("http://")) {
                            url = "http://" + url;
                        }
                        if (DEBUG)
                            Log.d(TAG, url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        mContext.startActivity(Intent.createChooser(intent,
                                mContext.getResources().getString(R.string.tools_misc_openwith)));
                    }
                }
                return true;
            }
        });
    }
}

From source file:com.nextgis.mobile.fragment.AttributesFragment.java

private void setAttributes() {
    if (mAttributes == null)
        return;/*from  www  .  j a v a  2  s  .  c om*/

    mAttributes.removeAllViews();

    int[] attrs = new int[] { android.R.attr.textColorPrimary };
    TypedArray ta = getContext().obtainStyledAttributes(attrs);
    String textColor = Integer.toHexString(ta.getColor(0, Color.BLACK)).substring(2);
    ta.recycle();

    final WebView webView = new WebView(getContext());
    webView.setVerticalScrollBarEnabled(false);
    String data = "<!DOCTYPE html><html><head><meta charset='utf-8'><style>body{word-wrap:break-word;color:#"
            + textColor
            + ";font-family:Roboto Light,sans-serif;font-weight:300;line-height:1.15em}.flat-table{table-layout:fixed;margin-bottom:20px;width:100%;border-collapse:collapse;border:none;box-shadow:inset 1px -1px #ccc,inset -1px 1px #ccc}.flat-table td{box-shadow:inset -1px -1px #ccc,inset -1px -1px #ccc;padding:.5em}.flat-table tr{-webkit-transition:background .3s,box-shadow .3s;-moz-transition:background .3s,box-shadow .3s;transition:background .3s,box-shadow .3s}</style></head><body><table class='flat-table'><tbody>";

    FragmentActivity activity = getActivity();
    if (null == activity)
        return;

    ((MainActivity) activity).setSubtitle(String.format(getString(R.string.features_count_attributes),
            mItemPosition + 1, mFeatureIDs.size()));
    checkNearbyItems();

    try {
        data = parseAttributes(data);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }

    data += "</tbody></table></body></html>";
    webView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
    mAttributes.addView(webView);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.setBackgroundColor(Color.TRANSPARENT);
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });

    IGISApplication app = (GISApplication) getActivity().getApplication();
    final Map<String, Integer> mAttaches = new HashMap<>();
    PhotoGallery.getAttaches(app, mLayer, mItemId, mAttaches, false);

    if (mAttaches.size() > 0) {
        final PhotoPicker gallery = new PhotoPicker(getActivity(), true);
        int px = ControlHelper.dpToPx(16, getResources());
        gallery.setDefaultPreview(true);
        gallery.setPadding(px, 0, px, 0);
        gallery.post(new Runnable() {
            @Override
            public void run() {
                gallery.restoreImages(new ArrayList<>(mAttaches.keySet()));
            }
        });

        mAttributes.addView(gallery);
    }
}

From source file:com.normalexception.app.rx8club.view.threadpost.PostView.java

/**
 * Setup our view here.  After the view has been inflated and all of the
 * view objects have been initialized, we can inflate our view here
 * @param post      The model we are going to use to populate the view
 * @param position   Get the position of this view on the window
 * @param listener  The listener object to attach to the view
 *///from   w  w  w .  ja v  a2s .  com
public void setPost(final PostModel post, final int position, final OnClickListener listener) {
    username.setText(post.getUserName());
    userTitle.setText(post.getUserTitle());
    userPosts.setText(post.getUserPostCount());
    userJoin.setText(post.getJoinDate());
    postDate.setText(post.getPostDate());
    reportbutton.setVisibility(View.VISIBLE);

    if (PreferenceHelper.isShowLikes(getContext())) {
        if (post.getLikes().size() > 0) {
            String delim = "", likes = "Liked by: ";
            for (String like : post.getLikes()) {
                likes += delim + like;
                delim = ", ";
            }
            likeText.setText(likes);
        } else {
            likeText.setVisibility(View.GONE);
        }
    } else {
        likeText.setVisibility(View.GONE);
    }

    // Lets make sure we remove any font formatting that was done within
    // the text
    String trimmedPost = post.getUserPost().replaceAll("(?i)<(/*)font(.*?)>", "");

    // Show attachments if the preference allows it
    if (PreferenceHelper.isShowAttachments(getContext()))
        trimmedPost = appendAttachments(trimmedPost, post.getAttachments());

    // Show signatures if the preference allows it
    if (PreferenceHelper.isShowSignatures(getContext()) && post.getUserSignature() != null)
        trimmedPost = appendSignature(trimmedPost, post.getUserSignature());

    // Set html Font color
    trimmedPost = Utils.postFormatter(trimmedPost, getContext());
    postText.setBackgroundColor(Color.DKGRAY);
    postText.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    postText.getSettings().setAppCachePath(Cache.getExternalCacheDir(getContext()).getAbsolutePath());
    postText.getSettings().setAllowFileAccess(false);
    postText.getSettings().setAppCacheEnabled(true);
    postText.getSettings().setJavaScriptEnabled(false);
    postText.getSettings().setSupportZoom(false);
    postText.getSettings().setSupportMultipleWindows(false);
    postText.getSettings().setUserAgentString(WebUrls.USER_AGENT);
    postText.getSettings().setDatabaseEnabled(false);
    postText.getSettings().setDomStorageEnabled(false);
    postText.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
    postText.setOnTouchListener(new View.OnTouchListener() {
        @SuppressLint("ClickableViewAccessibility")
        public boolean onTouch(View v, MotionEvent event) {
            return (event.getAction() == MotionEvent.ACTION_MOVE);
        }
    });
    postText.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Check if the URL for the site, and if it is a thread or a category
            Log.d(TAG, "User Clicked Embedded url");
            boolean isThread = false;
            if (url.contains("rx8club.com")) {
                isThread = url.matches(".*\\-\\d+\\/$");
                Log.d(TAG, String.format("The Link (%s) is %sa thread", url, (isThread) ? "" : "NOT "));

                Bundle args = new Bundle();
                args.putString("link", url);

                if (isThread) {
                    FragmentUtils.fragmentTransaction((FragmentActivity) view.getContext(),
                            ThreadFragment.newInstance(), false, true, args);
                    return true;
                }
            }

            // 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));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MainApplication.getAppContext().startActivity(intent);
            return true;
        }
    });

    postText.loadDataWithBaseURL(WebUrls.rootUrl, trimmedPost, "text/html", "utf-8", "");

    // Load up the avatar of hte user, but remember to remove
    // the dateline at the end of the file so that we aren't
    // creating multiple images for a user.  The image still
    // gets returned without a date
    if (PreferenceHelper.isShowAvatars(getContext())) {
        String nodate_avatar = post.getUserImageUrl().indexOf('?') == -1 ? post.getUserImageUrl()
                : post.getUserImageUrl().substring(0, post.getUserImageUrl().indexOf('?'));

        if (!nodate_avatar.isEmpty()) {
            imageLoader.DisplayImage(nodate_avatar, avatar);
        } else {
            avatar.setImageResource(R.drawable.rotor_icon);
        }
    }

    // Display the right items if the user is logged in
    setUserIcons(this, post.isLoggedInUser());

    downButton.setOnClickListener(listener);

    // Set click listeners if we are logged in, hide the buttons
    // if we are not logged in
    if (LoginFactory.getInstance().isGuestMode()) {
        quoteButton.setVisibility(View.GONE);
        editButton.setVisibility(View.GONE);
        pmButton.setVisibility(View.GONE);
        deleteButton.setVisibility(View.GONE);
        reportbutton.setVisibility(View.GONE);
    } else {
        quoteButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Quote Clicked");
                String txt = Html.fromHtml(post.getUserPost()).toString();
                String finalText = String.format("[quote=%s]%s[/quote]", post.getUserName(), txt);
                postBox.setText(finalText);
                postBox.requestFocus();
            }
        });

        editButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Edit Clicked");

                // Create new fragment and transaction
                Bundle args = new Bundle();
                args.putString("postid", post.getPostId());
                args.putString("securitytoken", post.getToken());
                Fragment newFragment = new EditPostFragment();

                FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment, true, true,
                        args);
            }
        });

        reportbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Report Clicked");
                new ReportPostDialog(getContext(), post.getToken(), post.getPostId()).show();
            }
        });

        linkbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Link Clicked");
                ClipboardManager clipboard = (android.content.ClipboardManager) getContext()
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("thread link",
                        post.getRootThreadUrl());
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getContext(), "Thread Link Copied To Clipboard", Toast.LENGTH_LONG).show();
            }
        });

        pmButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "PM Clicked");

                // Create new fragment and transaction
                Bundle args = new Bundle();
                args.putString("user", post.getUserName());
                Fragment newFragment = new NewPrivateMessageFragment();
                FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment, false, true,
                        args);
            }
        });

        final boolean isFirstPost = (position == 0);
        deleteButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case DialogInterface.BUTTON_POSITIVE:
                            // Create new fragment and transaction
                            Bundle args = new Bundle();
                            args.putString("postid", post.getPostId());
                            args.putString("securitytoken", post.getToken());
                            args.putBoolean("delete", true);
                            args.putBoolean("deleteThread", isFirstPost && post.isLoggedInUser());
                            Fragment newFragment = new EditPostFragment();
                            FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment,
                                    false, true, args);
                            break;
                        }
                    }
                };

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setMessage("Are you sure you want to delete your post?")
                        .setPositiveButton("Yes", dialogClickListener)
                        .setNegativeButton("No", dialogClickListener).show();
            }
        });
    }
}

From source file:net.olejon.spotcommander.WebViewActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Google API client
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build();

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Hide status bar?
    if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR"))
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Power manager
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    //noinspection deprecation
    mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock");

    // Settings/* w ww  . j a v  a2 s.  com*/
    mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false);

    // Current network
    mCurrentNetwork = mTools.getCurrentNetwork();

    // Computer
    final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID");

    final String[] computer = mTools.getComputer(computerId);

    final String uri = computer[0];
    final String username = computer[1];
    final String password = computer[2];

    // Layout
    setContentView(R.layout.activity_webview);

    // Status bar color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mStatusBarPrimaryColor = getWindow().getStatusBarColor();
        mStatusBarCoverArtColor = mStatusBarPrimaryColor;
    }

    // Notification
    mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN);

    if (mPersistentNotificationIsSupported) {
        final Intent launchActivityIntent = new Intent(mContext, MainActivity.class);
        launchActivityIntent.setAction("android.intent.action.MAIN");
        launchActivityIntent.addCategory("android.intent.category.LAUNCHER");
        mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class);
        hideIntent.setAction("hide_notification");
        hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class);
        previousIntent.setAction("previous");
        previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class);
        playPauseIntent.setAction("play_pause");
        playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class);
        nextIntent.setAction("next");
        nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeDownIntent.setAction("adjust_spotify_volume_down");
        volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeUpIntent.setAction("adjust_spotify_volume_up");
        volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        mNotificationManager = NotificationManagerCompat.from(mContext);
        mNotificationBuilder = new NotificationCompat.Builder(mContext);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            mNotificationBuilder.setPriority(Notification.PRIORITY_MAX);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
            mNotificationBuilder.setCategory(Notification.CATEGORY_TRANSPORT);
        }
    }

    // Web view
    mWebView = (WebView) findViewById(R.id.webview_webview);

    mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background));
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    mWebView.setWebViewClient(new WebViewClient() {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && !url.contains(uri)
                    && !url.contains("olejon.net/code/spotcommander/api/1/spotify/")
                    && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }

            return false;
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host,
                String realm) {
            if (handler.useHttpAuthUsernamePassword()) {
                handler.proceed(username, password);
            } else {
                handler.cancel();

                mWebView.stopLoading();

                mTools.showToast(getString(R.string.webview_authentication_failed), 1);

                mTools.navigateUp(mActivity);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest webResourceRequest,
                WebResourceError webResourceError) {
            mWebView.stopLoading();

            mTools.showToast(getString(R.string.webview_error), 1);

            mTools.navigateUp(mActivity);
        }

        @Override
        public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) {
            handler.cancel();

            mWebView.stopLoading();

            new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title)
                    .content(getString(R.string.webview_dialog_ssl_error_message))
                    .positiveText(R.string.webview_dialog_ssl_error_positive_button)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog materialDialog,
                                @NonNull DialogAction dialogAction) {
                            finish();
                        }
                    }).contentColorRes(R.color.black).show();
        }
    });

    // User agent
    mProjectVersionName = mTools.getProjectVersionName();

    final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : "";
    final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : "";
    final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT
            && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS"))
                    ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D "
                    : "";

    // Web settings
    final WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(false);
    webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(),
            mProjectVersionName, uaAppend1, uaAppend2, uaAppend3));

    // Load app
    if (savedInstanceState != null) {
        mWebView.restoreState(savedInstanceState);
    } else {
        mWebView.loadUrl(uri);
    }

    // JavaScript interface
    mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
}