Search in sources :

Example 6 with WebResourceRequest

use of android.webkit.WebResourceRequest 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 7 with WebResourceRequest

use of android.webkit.WebResourceRequest 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)

Example 8 with WebResourceRequest

use of android.webkit.WebResourceRequest in project CCIP-Android by CCIP-App.

the class PuzzleFragment method onCreateView.

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_web, container, false);
    setHasOptionsMenu(true);
    mActivity = getActivity();
    progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    webView = (WebView) view.findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            view.loadUrl(URL_NO_NETWORK);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });
    webView.setWebChromeClient(new WebChromeViewClient(progressBar));
    if (PreferenceUtil.getToken(getActivity()) != null) {
        webView.loadUrl(URL_PUZZLE + PreferenceUtil.getToken(getActivity()));
    } else {
        webView.loadUrl("data:text/html, <div>Please login</div>");
    }
    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    if (Build.VERSION.SDK_INT >= 21) {
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
    }
    return view;
}
Also used : WebChromeViewClient(org.sitcon.ccip.network.webclient.WebChromeViewClient) WebResourceRequest(android.webkit.WebResourceRequest) WebSettings(android.webkit.WebSettings) WebResourceError(android.webkit.WebResourceError) Intent(android.content.Intent) WebView(android.webkit.WebView) View(android.view.View) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) Nullable(android.support.annotation.Nullable)

Example 9 with WebResourceRequest

use of android.webkit.WebResourceRequest in project BookReader by JustWayward.

the class ReadCHMActivity method initVweView.

private void initVweView() {
    mProgressBar.setMax(100);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            visible(mProgressBar);
            mProgressBar.setProgress(newProgress);
        }
    });
    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                }
            }
            super.onPageStarted(view, url, favicon);
            mProgressBar.setProgress(50);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressBar.setProgress(100);
            gone(mProgressBar);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                }
            }
            super.onLoadResource(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                String insideFileName;
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                    insideFileName = temp;
                } else {
                    insideFileName = temp.substring(extractPath.length());
                }
                if (insideFileName.contains("#")) {
                    insideFileName = insideFileName.substring(0, insideFileName.indexOf("#"));
                }
                if (insideFileName.contains("?")) {
                    insideFileName = insideFileName.substring(0, insideFileName.indexOf("?"));
                }
                if (insideFileName.contains("%20")) {
                    insideFileName = insideFileName.replaceAll("%20", " ");
                }
                if (url.endsWith(".gif") || url.endsWith(".jpg") || url.endsWith(".png")) {
                    try {
                        return new WebResourceResponse("image/*", "", Utils.chm.getResourceAsStream(insideFileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        return super.shouldInterceptRequest(view, request);
                    }
                } else if (url.endsWith(".css") || url.endsWith(".js")) {
                    try {
                        return new WebResourceResponse("", "", Utils.chm.getResourceAsStream(insideFileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        return super.shouldInterceptRequest(view, request);
                    }
                } else {
                    Utils.extractSpecificFile(chmFilePath, extractPath + insideFileName, insideFileName);
                }
            }
            Log.e("2, webviewrequest", url);
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                    view.loadUrl(url);
                    return true;
                }
            }
            return false;
        }

        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return shouldOverrideUrlLoading(view, request.getUrl().toString());
        }
    });
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setDisplayZoomControls(false);
    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setLoadsImagesAutomatically(true);
}
Also used : Bitmap(android.graphics.Bitmap) WebResourceRequest(android.webkit.WebResourceRequest) WebResourceResponse(android.webkit.WebResourceResponse) WebChromeClient(android.webkit.WebChromeClient) IOException(java.io.IOException) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 10 with WebResourceRequest

use of android.webkit.WebResourceRequest in project Reader by TheKeeperOfPie.

the class ActivityLogin method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    CustomApplication.getComponentMain().inject(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }
    layoutRoot = (ViewGroup) findViewById(R.id.layout_root);
    Themer themer = new Themer(this);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(themer.getColorFilterPrimary().getColor());
    progressAuth = (ProgressBar) findViewById(R.id.progress_auth);
    webAuth = (WebView) findViewById(R.id.web_auth);
    webAuth.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(TAG, "onPageStarted() called with: " + "view = [" + view + "], url = [" + url + "], favicon = [" + favicon + "]");
            progressAuth.setIndeterminate(true);
            progressAuth.setVisibility(View.VISIBLE);
            Uri uri = Uri.parse(url);
            if (uri.getHost().equals(Reddit.REDIRECT_URI.replaceFirst("https://", ""))) {
                String error = uri.getQueryParameter("error");
                String returnedState = uri.getQueryParameter("state");
                if (!TextUtils.isEmpty(error) || !state.equals(returnedState)) {
                    Toast.makeText(ActivityLogin.this, error, Toast.LENGTH_LONG).show();
                    webAuth.loadUrl(Reddit.getUserAuthUrl(state));
                    return;
                }
                // TODO: Failsafe with error and state
                String code = uri.getQueryParameter("code");
                fetchTokens(code);
            }
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressAuth.setVisibility(View.GONE);
            toolbar.setTitle(view.getTitle());
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            Log.e(TAG, "WebView error: " + error);
        }
    });
    webAuth.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressAuth.setIndeterminate(false);
            progressAuth.setProgress(newProgress);
        }
    });
    webAuth.loadUrl(Reddit.getUserAuthUrl(state));
}
Also used : Bitmap(android.graphics.Bitmap) WebResourceRequest(android.webkit.WebResourceRequest) WebChromeClient(android.webkit.WebChromeClient) WebResourceError(android.webkit.WebResourceError) Themer(com.winsonchiu.reader.theme.Themer) WebView(android.webkit.WebView) Uri(android.net.Uri) WebViewClient(android.webkit.WebViewClient)

Aggregations

WebResourceRequest (android.webkit.WebResourceRequest)38 WebView (android.webkit.WebView)37 WebViewClient (android.webkit.WebViewClient)34 Bitmap (android.graphics.Bitmap)22 WebResourceError (android.webkit.WebResourceError)21 WebResourceResponse (android.webkit.WebResourceResponse)16 WebSettings (android.webkit.WebSettings)14 Intent (android.content.Intent)13 View (android.view.View)12 WebChromeClient (android.webkit.WebChromeClient)12 SuppressLint (android.annotation.SuppressLint)11 TextView (android.widget.TextView)9 SslError (android.net.http.SslError)8 SslErrorHandler (android.webkit.SslErrorHandler)8 Uri (android.net.Uri)7 TargetApi (android.annotation.TargetApi)6 IOException (java.io.IOException)5 Nullable (android.support.annotation.Nullable)3 SearchView (android.support.v7.widget.SearchView)3 Toolbar (android.support.v7.widget.Toolbar)3