Search in sources :

Example 66 with WebViewClient

use of android.webkit.WebViewClient in project Notepad by farmerbb.

the class NoteViewFragment method onActivityCreated.

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Set values
    setRetainInstance(true);
    setHasOptionsMenu(true);
    // Get filename of saved note
    filename = getArguments().getString("filename");
    // Change window title
    String title;
    try {
        title = listener.loadNoteTitle(filename);
    } catch (IOException e) {
        title = getResources().getString(R.string.view_note);
    }
    getActivity().setTitle(title);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, null, ContextCompat.getColor(getActivity(), R.color.primary));
        getActivity().setTaskDescription(taskDescription);
    }
    // Show the Up button in the action bar.
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // Animate elevation change
    if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        LinearLayout noteViewEdit = (LinearLayout) getActivity().findViewById(R.id.noteViewEdit);
        LinearLayout noteList = (LinearLayout) getActivity().findViewById(R.id.noteList);
        noteList.animate().z(0f);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land));
        else
            noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation));
    }
    // Set up content view
    TextView noteContents = (TextView) getActivity().findViewById(R.id.textView);
    markdownView = (MarkdownView) getActivity().findViewById(R.id.markdownView);
    // Apply theme
    SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences", Context.MODE_PRIVATE);
    ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scrollView);
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;
    int textColor = -1;
    String fontFamily = null;
    if (theme.contains("light")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary));
            noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
        }
        if (markdownView != null) {
            markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary);
        }
        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
    }
    if (theme.contains("dark")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark));
            noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
        }
        if (markdownView != null) {
            markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark);
        }
        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
    }
    if (theme.contains("sans")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SANS_SERIF);
        if (markdownView != null)
            fontFamily = "sans-serif";
    }
    if (theme.contains("serif")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SERIF);
        if (markdownView != null)
            fontFamily = "serif";
    }
    if (theme.contains("monospace")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.MONOSPACE);
        if (markdownView != null)
            fontFamily = "monospace";
    }
    switch(pref.getString("font_size", "normal")) {
        case "smallest":
            textSize = 12;
            break;
        case "small":
            textSize = 14;
            break;
        case "normal":
            textSize = 16;
            break;
        case "large":
            textSize = 18;
            break;
        case "largest":
            textSize = 20;
            break;
    }
    if (noteContents != null)
        noteContents.setTextSize(textSize);
    String css = "";
    if (markdownView != null) {
        String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom) / getResources().getDisplayMetrics().density) + "px";
        String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right) / getResources().getDisplayMetrics().density) + "px";
        String fontSize = " " + Integer.toString(textSize) + "px";
        String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff");
        String linkColor = " #" + StringUtils.remove(Integer.toHexString(new TextView(getActivity()).getLinkTextColors().getDefaultColor()), "ff");
        css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor + "; " + "}" + "a { " + "color:" + linkColor + "; " + "}";
        markdownView.getSettings().setJavaScriptEnabled(false);
        markdownView.getSettings().setLoadsImagesAutomatically(false);
        markdownView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (!request.hasGesture())
                    return super.shouldOverrideUrlLoading(view, request);
                Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException | FileUriExposedException e) {
                    /* Gracefully fail */
                    }
                else
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                    /* Gracefully fail */
                    }
                return true;
            }
        });
    }
    // Load note contents
    try {
        contentsOnLoad = listener.loadNote(filename);
    } catch (IOException e) {
        showToast(R.string.error_loading_note);
        // Add NoteListFragment or WelcomeFragment
        Fragment fragment;
        if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal"))
            fragment = new NoteListFragment();
        else
            fragment = new WelcomeFragment();
        getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment").setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
    }
    // Set TextView contents
    if (noteContents != null)
        noteContents.setText(contentsOnLoad);
    if (markdownView != null)
        markdownView.loadMarkdown(contentsOnLoad, "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));
    // Show a toast message if this is the user's first time viewing a note
    final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    firstLoad = sharedPref.getInt("first-load", 0);
    if (firstLoad == 0) {
        // Show dialog with info
        DialogFragment firstLoad = new FirstViewDialogFragment();
        firstLoad.show(getFragmentManager(), "firstloadfragment");
        // Set first-load preference to 1; we don't need to show the dialog anymore
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("first-load", 1);
        editor.apply();
    }
    // Detect single and double-taps using GestureDetector
    final GestureDetector detector = new GestureDetector(getActivity(), new GestureDetector.OnGestureListener() {

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }
    });
    detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true)) {
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean("show_double_tap_message", false);
                editor.apply();
            }
            Bundle bundle = new Bundle();
            bundle.putString("filename", filename);
            Fragment fragment = new NoteEditFragment();
            fragment.setArguments(bundle);
            getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment").commit();
            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) {
                showToastLong(R.string.double_tap);
                showMessage = false;
            }
            return false;
        }
    });
    if (noteContents != null)
        noteContents.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });
    if (markdownView != null)
        markdownView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });
}
Also used : DialogFragment(android.support.v4.app.DialogFragment) FirstViewDialogFragment(com.farmerbb.notepad.fragment.dialog.FirstViewDialogFragment) GestureDetector(android.view.GestureDetector) ActivityManager(android.app.ActivityManager) DialogFragment(android.support.v4.app.DialogFragment) Fragment(android.support.v4.app.Fragment) FirstViewDialogFragment(com.farmerbb.notepad.fragment.dialog.FirstViewDialogFragment) TextView(android.widget.TextView) FirstViewDialogFragment(com.farmerbb.notepad.fragment.dialog.FirstViewDialogFragment) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) FileUriExposedException(android.os.FileUriExposedException) WebResourceRequest(android.webkit.WebResourceRequest) SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) Intent(android.content.Intent) IOException(java.io.IOException) View(android.view.View) WebView(android.webkit.WebView) MarkdownView(us.feras.mdv.MarkdownView) TextView(android.widget.TextView) ScrollView(android.widget.ScrollView) MotionEvent(android.view.MotionEvent) ScrollView(android.widget.ScrollView) ActivityNotFoundException(android.content.ActivityNotFoundException) LinearLayout(android.widget.LinearLayout) TargetApi(android.annotation.TargetApi)

Example 67 with WebViewClient

use of android.webkit.WebViewClient in project Notepad by farmerbb.

the class MainActivity method printNote.

@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.KITKAT)
public void printNote(String contentToPrint) {
    SharedPreferences pref = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE);
    // Create a WebView object specifically for printing
    boolean generateHtml = !(pref.getBoolean("markdown", false) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
    WebView webView = generateHtml ? new WebView(this) : new MarkdownView(this);
    // Apply theme
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;
    String fontFamily = null;
    if (theme.contains("sans")) {
        fontFamily = "sans-serif";
    }
    if (theme.contains("serif")) {
        fontFamily = "serif";
    }
    if (theme.contains("monospace")) {
        fontFamily = "monospace";
    }
    switch(pref.getString("font_size", "normal")) {
        case "smallest":
            textSize = 12;
            break;
        case "small":
            textSize = 14;
            break;
        case "normal":
            textSize = 16;
            break;
        case "large":
            textSize = 18;
            break;
        case "largest":
            textSize = 20;
            break;
    }
    String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom_print) / getResources().getDisplayMetrics().density) + "px";
    String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right_print) / getResources().getDisplayMetrics().density) + "px";
    String fontSize = " " + Integer.toString(textSize) + "px";
    String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "}";
    webView.getSettings().setJavaScriptEnabled(false);
    webView.getSettings().setLoadsImagesAutomatically(false);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(final WebView view, String url) {
            createWebPrintJob(view);
        }
    });
    // Load content into WebView
    if (generateHtml) {
        webView.loadDataWithBaseURL(null, "<link rel='stylesheet' type='text/css' href='data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT) + "' /><html><body><p>" + StringUtils.replace(contentToPrint, "\n", "<br>") + "</p></body></html>", "text/HTML", "UTF-8", null);
    } else
        ((MarkdownView) webView).loadMarkdown(contentToPrint, "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));
}
Also used : MarkdownView(us.feras.mdv.MarkdownView) SharedPreferences(android.content.SharedPreferences) WebView(android.webkit.WebView) SuppressLint(android.annotation.SuppressLint) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint) TargetApi(android.annotation.TargetApi)

Example 68 with WebViewClient

use of android.webkit.WebViewClient in project WanAndroid by dangxy.

the class DetailActivity method initView.

protected void initView() {
    url = getIntent().getStringExtra("url");
    WebSettings webSettings = wvUrl.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setJavaScriptEnabled(true);
    wvUrl.loadUrl(url);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
    toolbar.setTitle("");
    setSupportActionBar(toolbar);
    WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressBar.setProgress(newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (title.equals("")) {
                tvTitle.setText("详情");
            } else {
                tvTitle.setText(title);
            }
        }
    };
    wvUrl.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            wvUrl.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    });
    wvUrl.setWebChromeClient(webChromeClient);
}
Also used : Bitmap(android.graphics.Bitmap) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) Toolbar(android.support.v7.widget.Toolbar) WebViewClient(android.webkit.WebViewClient)

Example 69 with WebViewClient

use of android.webkit.WebViewClient in project iNaturalistAndroid by inaturalist.

the class NewsArticle method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mHelper = new ActivityHelper(this);
    final Intent intent = getIntent();
    setContentView(R.layout.article);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setLogo(R.drawable.ic_arrow_back);
    actionBar.setTitle(R.string.article);
    mArticleTitle = (TextView) findViewById(R.id.article_title);
    mArticleContentWeb = (WebView) findViewById(R.id.article_content_web);
    mArticleContent = (TextView) findViewById(R.id.article_content);
    mUsername = (TextView) findViewById(R.id.username);
    mUserPic = (ImageView) findViewById(R.id.user_pic);
    if (mApp == null) {
        mApp = (INaturalistApp) getApplicationContext();
    }
    if (savedInstanceState == null) {
        mArticle = (BetterJSONObject) intent.getSerializableExtra(KEY_ARTICLE);
        mIsUserFeed = intent.getBooleanExtra(KEY_IS_USER_FEED, false);
    } else {
        mArticle = (BetterJSONObject) savedInstanceState.getSerializable(KEY_ARTICLE);
        mIsUserFeed = savedInstanceState.getBoolean(KEY_IS_USER_FEED);
    }
    if (mArticle == null) {
        finish();
        return;
    }
    mArticleTitle.setText(mArticle.getString("title"));
    if (mIsUserFeed) {
        mArticleContent.setVisibility(View.GONE);
        mArticleContentWeb.setVisibility(View.VISIBLE);
        mArticleContentWeb.setBackgroundColor(Color.TRANSPARENT);
        mArticleContentWeb.getSettings().setJavaScriptEnabled(true);
        mArticleContentWeb.setVerticalScrollBarEnabled(false);
        String html = "" + "<html>" + "<head>" + "<style type=\"text/css\"> " + "body {" + "line-height: 22pt;" + "margin: 0;" + "padding: 0;" + "font-family: \"HelveticaNeue-UltraLight\", \"Segoe UI\", \"Roboto Light\", sans-serif;" + "font-size: medium;" + "} " + "div {max-width: 100%;} " + "figure { padding: 0; margin: 0; } " + "img { padding-top: 4; padding-bottom: 4; max-width: 100%; } " + "</style>" + "<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width\" >" + "</head>" + "<body>";
        mArticleContentWeb.loadDataWithBaseURL("", html + mArticle.getString("body") + "</body></html>", "text/html", "UTF-8", "");
    } else {
        mArticleContentWeb.setVisibility(View.GONE);
        mArticleContent.setVisibility(View.VISIBLE);
        mArticleContent.setText(Html.fromHtml(mArticle.getString("body")));
        Linkify.addLinks(mArticleContent, Linkify.ALL);
    }
    final JSONObject user = mArticle.getJSONObject("user");
    mUsername.setText(user.optString("login"));
    // Intercept link clicks (for analytics events)
    WebViewClient webClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                JSONObject eventParams = new JSONObject();
                JSONObject item = mArticle.getJSONObject();
                eventParams.put(AnalyticsClient.EVENT_PARAM_LINK, url);
                eventParams.put(AnalyticsClient.EVENT_PARAM_ARTICLE_TITLE, item.optString("title", ""));
                eventParams.put(AnalyticsClient.EVENT_PARAM_PARENT_TYPE, item.optString("parent_type", ""));
                JSONObject parent = item.optJSONObject("parent");
                if (parent == null)
                    parent = new JSONObject();
                eventParams.put(AnalyticsClient.EVENT_PARAM_PARENT_NAME, parent.optString("title", parent.optString("name", "")));
                AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_NEWS_TAP_LINK, eventParams);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            NewsArticle.this.startActivity(intent);
            return true;
        }
    };
    mArticleContentWeb.setWebViewClient(webClient);
    View.OnClickListener showUser = new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(NewsArticle.this, UserProfile.class);
            intent.putExtra("user", new BetterJSONObject(user));
            startActivity(intent);
        }
    };
    if (user.has("user_icon_url") && !user.isNull("user_icon_url")) {
        UrlImageViewHelper.setUrlDrawable(mUserPic, user.optString("user_icon_url"), R.drawable.ic_account_circle_black_24dp, new UrlImageViewCallback() {

            @Override
            public void onLoaded(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
            // Nothing to do here
            }

            @Override
            public Bitmap onPreSetBitmap(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
                // Return a circular version of the profile picture
                return ImageUtils.getCircleBitmap(loadedBitmap);
            }
        });
    }
    mUserPic.setOnClickListener(showUser);
    mUsername.setOnClickListener(showUser);
}
Also used : UrlImageViewCallback(com.koushikdutta.urlimageviewhelper.UrlImageViewCallback) JSONException(org.json.JSONException) Intent(android.content.Intent) Uri(android.net.Uri) ImageView(android.widget.ImageView) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) ListView(android.widget.ListView) Bitmap(android.graphics.Bitmap) JSONObject(org.json.JSONObject) ImageView(android.widget.ImageView) WebView(android.webkit.WebView) ActionBar(android.support.v7.app.ActionBar) WebViewClient(android.webkit.WebViewClient)

Example 70 with WebViewClient

use of android.webkit.WebViewClient in project network-monitor by caarmen.

the class LogActivity method loadHTMLFile.

/**
 * Read the data from the DB, export it to an HTML file, and load the HTML file in the WebView.
 */
// only loading local files, it's ok.
@SuppressLint("SetJavaScriptEnabled")
private void loadHTMLFile() {
    Log.v(TAG, "loadHTMLFile");
    final ProgressBar progressBar = findViewById(R.id.progress_bar);
    assert progressBar != null;
    progressBar.setVisibility(View.VISIBLE);
    startRefreshIconAnimation();
    final boolean freezeHeader = NetMonPreferences.getInstance(this).getFreezeHtmlTableHeader();
    final String fixedTableHeight;
    if (freezeHeader) {
        // I've come to the following calculation by trial and error.
        // I've noticed that when entering the web view, the density is equal to the scale/zoom, but I'm
        // not sure if it's the density or zoom which really matters in this calculation.
        // We subtract 100px from the scaled webview height to account for the table header.
        fixedTableHeight = ((mWebView.getHeight() / getResources().getDisplayMetrics().density) - 100) + "px";
    } else {
        fixedTableHeight = null;
    }
    AsyncTask.execute(() -> {
        Log.v(TAG, "loadHTMLFile:doInBackground");
        // Export the DB to the HTML file.
        HTMLExport htmlExport = new HTMLExport(LogActivity.this, false, fixedTableHeight);
        int recordCount = NetMonPreferences.getInstance(LogActivity.this).getFilterRecordCount();
        File result = htmlExport.export(recordCount, null);
        runOnUiThread(() -> {
            Log.v(TAG, "loadHTMLFile:onPostExecute, result=" + result);
            if (isFinishing()) {
                Log.v(TAG, "finishing, ignoring loadHTMLFile result");
                return;
            }
            WebView webView = mWebView;
            if (webView == null) {
                Log.v(TAG, "Must be destroyed or destroying, we have no webview, ignoring loadHTMLFile result");
                return;
            }
            if (result == null) {
                Snackbar.make(webView, R.string.error_reading_log, Snackbar.LENGTH_LONG).show();
                return;
            }
            // Load the exported HTML file into the WebView.
            // Save our current horizontal scroll position so we can keep our
            // horizontal position after reloading the page.
            final int oldScrollX = webView.getScrollX();
            webView.getSettings().setUseWideViewPort(true);
            webView.getSettings().setBuiltInZoomControls(true);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl("file://" + result.getAbsolutePath());
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    Log.v(TAG, "onPageStarted");
                    // http://stackoverflow.com/questions/6855715/maintain-webview-content-scroll-position-on-orientation-change
                    if (oldScrollX > 0) {
                        String jsScrollX = "javascript:window:scrollTo(" + oldScrollX + " / window.devicePixelRatio,0);";
                        view.loadUrl(jsScrollX);
                    }
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    progressBar.setVisibility(View.GONE);
                    stopRefreshIconAnimation();
                }

                @Override
                @TargetApi(Build.VERSION_CODES.N)
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    return loadUrl(request.getUrl().toString()) || super.shouldOverrideUrlLoading(view, request);
                }

                @SuppressWarnings("deprecation")
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return loadUrl(url) || super.shouldOverrideUrlLoading(view, url);
                }

                private boolean loadUrl(String url) {
                    Log.v(TAG, "url: " + url);
                    // the sorting preference (column name, ascending or descending order).
                    if (url.startsWith(HTMLExport.URL_SORT)) {
                        NetMonPreferences prefs = NetMonPreferences.getInstance(LogActivity.this);
                        SortPreferences oldSortPreferences = prefs.getSortPreferences();
                        // The new column used for sorting will be the one the user tapped on.
                        String newSortColumnName = url.substring(HTMLExport.URL_SORT.length());
                        SortPreferences.SortOrder newSortOrder = oldSortPreferences.sortOrder;
                        // toggle the sort order between ascending and descending.
                        if (newSortColumnName.equals(oldSortPreferences.sortColumnName)) {
                            if (oldSortPreferences.sortOrder == SortPreferences.SortOrder.DESC)
                                newSortOrder = SortPreferences.SortOrder.ASC;
                            else
                                newSortOrder = SortPreferences.SortOrder.DESC;
                        }
                        // Update the sorting preferences (our shared preference change listener will be notified
                        // and reload the page).
                        prefs.setSortPreferences(new SortPreferences(newSortColumnName, newSortOrder));
                        return true;
                    } else // If the user clicked on the filter icon, start the filter activity for this column.
                    if (url.startsWith(HTMLExport.URL_FILTER)) {
                        Intent intent = new Intent(LogActivity.this, FilterColumnActivity.class);
                        String columnName = url.substring(HTMLExport.URL_FILTER.length());
                        intent.putExtra(FilterColumnActivity.EXTRA_COLUMN_NAME, columnName);
                        startActivityForResult(intent, REQUEST_CODE_FILTER_COLUMN);
                        return true;
                    } else {
                        return false;
                    }
                }
            });
        });
    });
}
Also used : HTMLExport(ca.rmen.android.networkmonitor.app.dbops.backend.export.HTMLExport) WebResourceRequest(android.webkit.WebResourceRequest) Intent(android.content.Intent) SuppressLint(android.annotation.SuppressLint) NetMonPreferences(ca.rmen.android.networkmonitor.app.prefs.NetMonPreferences) SortPreferences(ca.rmen.android.networkmonitor.app.prefs.SortPreferences) Bitmap(android.graphics.Bitmap) WebView(android.webkit.WebView) ProgressBar(android.widget.ProgressBar) File(java.io.File) TargetApi(android.annotation.TargetApi) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Aggregations

WebViewClient (android.webkit.WebViewClient)247 WebView (android.webkit.WebView)229 WebSettings (android.webkit.WebSettings)77 View (android.view.View)71 WebChromeClient (android.webkit.WebChromeClient)69 SuppressLint (android.annotation.SuppressLint)61 Intent (android.content.Intent)60 Bitmap (android.graphics.Bitmap)59 WebResourceRequest (android.webkit.WebResourceRequest)35 TextView (android.widget.TextView)26 LinearLayout (android.widget.LinearLayout)22 WebResourceError (android.webkit.WebResourceError)21 WebResourceResponse (android.webkit.WebResourceResponse)16 Uri (android.net.Uri)15 SslError (android.net.http.SslError)13 Bundle (android.os.Bundle)13 Toolbar (android.support.v7.widget.Toolbar)13 KeyEvent (android.view.KeyEvent)13 SslErrorHandler (android.webkit.SslErrorHandler)13 TargetApi (android.annotation.TargetApi)12