Example usage for android.webkit WebSettings LOAD_CACHE_ELSE_NETWORK

List of usage examples for android.webkit WebSettings LOAD_CACHE_ELSE_NETWORK

Introduction

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

Prototype

int LOAD_CACHE_ELSE_NETWORK

To view the source code for android.webkit WebSettings LOAD_CACHE_ELSE_NETWORK.

Click Source Link

Document

Use cached resources when they are available, even if they have expired.

Usage

From source file:com.ben.gank.fragment.WebFragment.java

private void initWebView() {
    mWebView.setWebViewClient(new WebViewClient() {
        @Override//from   w  w w  . ja va 2 s  .  co m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //trueWebViewfalse??
            view.loadUrl(url);
            return true;
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                // ?
                if (mProgressBar != null && mSwipeRefreshLayout != null) {
                    mProgressBar.setVisibility(View.GONE);
                    mProgressBar.setProgress(0);
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            } else {
                // 
                if (mProgressBar != null) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
            }
        }
    });
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setDisplayZoomControls(true);

}

From source file:com.guodong.sun.guodong.activity.ZhiHuDetailActivity.java

private void initWebView() {
    mWebView.setScrollbarFadingEnabled(true);
    //js//  w  w  w . j  a v  a  2  s . co m
    mWebView.getSettings().setJavaScriptEnabled(true);
    //,????
    mWebView.getSettings().setBuiltInZoomControls(false);
    //
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    //?DOM storage API
    mWebView.getSettings().setDomStorageEnabled(true);
    //?application Cache
    mWebView.getSettings().setAppCacheEnabled(true);
    mWebView.getSettings().setAppCachePath(getCacheDir().getAbsolutePath() + "/webViewCache");
    mWebView.getSettings().setBlockNetworkImage(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    mWebView.setWebChromeClient(new WebChromeClient());
}

From source file:com.moki.touch.fragments.views.WebContent.java

private void configureWebView(Context context) {
    if (!userAgent.equals("default")) {
        webView.getSettings().setUserAgentString(userAgent);
    }/*w ww.j av a  2s. c  o m*/
    webView.getSettings().setJavaScriptEnabled(true);
    // Set cache size to 32 mb by default. should be more than enough
    webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 32);
    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

    String appCachePath = context.getCacheDir().getAbsolutePath();
    webView.getSettings().setAppCachePath(appCachePath);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    webView.setWebViewClient(new CustomClient());
    if (showProgressBar) {
        webView.setWebChromeClient(new CustomChromeClient());
    }
}

From source file:moose.com.ac.ArticleViewActivity.java

@Override
protected void onInitView(Bundle savedInstanceState) {
    setContentView(R.layout.activity_article_view);
    article = (Article) getIntent().getSerializableExtra(Config.ARTICLE);
    /*//from  w  w  w.j a  v  a 2 s. co m
    * Uri data = getIntent().getData();
    if(Intent.ACTION_VIEW.equalsIgnoreCase(getIntent().getAction()) && data!=null){
    String scheme = data.getScheme();
    if(scheme.equals("ac")){
        // ac://ac000000
        aid = Integer.parseInt(getIntent().getDataString().substring(7));
    }else if(scheme.equals("http")){
        // http://www.acfun.tv/v/ac123456
        Matcher matcher;
        String path = data.getPath();
        if(path==null){
            finish();
            return;
        }
        if((matcher = sVreg.matcher(path)).find()
                || (matcher = sAreg.matcher(path)).find()){
            aid = Integer.parseInt(matcher.group(1));
        }
    }
    if(aid != 0) title = "ac"+aid;
    isWebMode = getIntent().getBooleanExtra("webmode", false) && aid == 0;
    }else{
    aid = getIntent().getIntExtra("aid", 0);
    title = getIntent().getStringExtra("title");
    }*/
    isFav = dbHelper.isExits(TAB_NAME, article.isfav);
    articleId = Integer.valueOf(article.contentId);
    toolbarHeight = DisplayUtil.dip2px(this, 56f);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final ActionBar ab = getSupportActionBar();
    if (ab != null) {
        ab.setDisplayHomeAsUpEnabled(true);
    }
    contend = "ac" + articleId;
    getSupportActionBar().setTitle(contend);

    fab = (FloatingActionButton) findViewById(R.id.view_fab);
    fab.setOnClickListener(v -> {
        Intent intent = new Intent(this, BigNewsActivity.class);
        intent.putExtra(Config.CONTENTID, String.valueOf(articleId));
        intent.putExtra(Config.TITLE, title);
        startActivity(intent);
    });

    mSwipeRefreshLayout = (MultiSwipeRefreshLayout) findViewById(R.id.web_swipe);
    mSwipeRefreshLayout.setSwipeableChildren(R.id.view_fab);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.md_white);
    mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorPrimary);

    mWeb = (ObservableWebView) findViewById(R.id.view_webview);
    mContentView = (CoordinatorLayout) findViewById(R.id.view_content);
    settings = mWeb.getSettings();
    settings.setJavaScriptEnabled(true);
    //settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    settings.setUserAgentString(RxUtils.UA);
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setDefaultTextEncodingName(Config.TEXT_ENCODING);
    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mWeb.getSettings().setDisplayZoomControls(false);
    }
    mWeb.setWebViewClient(new Client());
    mWeb.addJavascriptInterface(new JsBridge(), "JsBridge");
    if (Build.VERSION.SDK_INT >= 11)
        mWeb.setBackgroundColor(Color.argb(1, 0, 0, 0));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
    }

    mWeb.setOnScrollChangedCallback(this);
    level = CommonUtil.getTextSize();
    setText();
    mSwipeRefreshLayout.post(() -> mSwipeRefreshLayout.setRefreshing(true));
    initData();
}

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
 *///  w  ww  . ja  va  2  s.  co  m
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:de.baumann.browser.Browser.java

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

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.onStart(Browser.this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);// w  w w .  ja  va  2s  .  c  o  m

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            actionBar = getSupportActionBar();
            assert actionBar != null;
            if (!actionBar.isShowing()) {
                editText.setText(mWebView.getTitle());
                actionBar.show();
            }
            setNavArrows();
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser.this, mWebView);
    helper_webView.webView_WebViewClient(Browser.this, swipeView, mWebView, editText);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_editText.editText_Touch(editText, Browser.this, mWebView);
    helper_editText.editText_EditorAction(editText, Browser.this, mWebView);
    helper_editText.editText_FocusChange(editText, Browser.this);

    onNewIntent(getIntent());
    helper_main.grantPermissionsStorage(Browser.this);
}

From source file:de.baumann.browser.Browser_right.java

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

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    getWindow().setStatusBarColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwoDark));

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.onStart(Browser_right.this);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit()/*from w ww. j  a va  2s .c o m*/
            .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/"))
            .apply();
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwo));
    setSupportActionBar(toolbar);

    actionBar = getSupportActionBar();

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setVisibility(View.GONE);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    urlBar = (TextView) findViewById(R.id.urlBar);

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            if (!actionBar.isShowing()) {
                urlBar.setText(mWebView.getTitle());
                actionBar.show();
            }
            helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right);
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorTwo, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser_right.this, mWebView);
    helper_webView.webView_WebViewClient(Browser_right.this, swipeView, mWebView, urlBar);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_browser.toolbar(Browser_right.this, Browser_left.class, mWebView, toolbar);
    helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar);
    helper_editText.editText_FocusChange(editText, Browser_right.this);
    helper_main.grantPermissionsStorage(Browser_right.this);

    onNewIntent(getIntent());
}

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

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

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

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

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

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

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

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

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

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

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

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

From source file:de.baumann.browser.Browser_left.java

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

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    getWindow().setStatusBarColor(ContextCompat.getColor(Browser_left.this, R.color.colorPrimaryDark));

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.checkPin(Browser_left.this);
    helper_main.onStart(Browser_left.this);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putBoolean("isOpened", true).apply();

    boolean show = sharedPref.getBoolean("introShowDo_notShow", true);

    if (show) {//from w  w w  .  j a v  a  2 s  . c om
        helper_main.switchToActivity(Browser_left.this, Activity_intro.class, "", false);
    }

    sharedPref.edit()
            .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/"))
            .apply();
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    if (sharedPref.getString("saved_key_ok", "no").equals("no")) {
        char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!$%&/()=?;:_-.,+#*<>"
                .toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 25; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        sharedPref.edit().putString("saved_key", sb.toString()).apply();
        sharedPref.edit().putString("saved_key_ok", "yes").apply();
    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    actionBar = getSupportActionBar();

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setVisibility(View.GONE);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    urlBar = (TextView) findViewById(R.id.urlBar);

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            if (!actionBar.isShowing()) {
                urlBar.setText(mWebView.getTitle());
                actionBar.show();
            }
            helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right);
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser_left.this, mWebView);
    helper_webView.webView_WebViewClient(Browser_left.this, swipeView, mWebView, urlBar);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_browser.toolbar(Browser_left.this, Browser_right.class, mWebView, toolbar);
    helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar);
    helper_editText.editText_FocusChange(editText, Browser_left.this);
    helper_main.grantPermissionsStorage(Browser_left.this);

    onNewIntent(getIntent());
}

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

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

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