Example usage for android.webkit WebChromeClient WebChromeClient

List of usage examples for android.webkit WebChromeClient WebChromeClient

Introduction

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

Prototype

WebChromeClient

Source Link

Usage

From source file:de.storyquest.client.ContentActivity.java

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

    // enable immersive mode
    getWindow().getDecorView()//from  w w  w .j  a v a 2s  .  co m
            .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

    // load initial layout
    setContentView(R.layout.activity_content);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View header = navigationView.getHeaderView(0);

    // apply theme
    try {
        Drawable d = Drawable.createFromStream(getAssets().open("sidebar.jpg"), null);
        navigationView.setBackground(d);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // wire the drawer open event to the character sheet refresh
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer != null) {
        drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                execJavaScriptInCharactersheet("if(typeof refresh!='undefined')refresh()");
            }
        });
    }

    // get extra data with bookmark to load
    Intent intent = getIntent();
    if (intent.hasExtra(BOOKMARKID))
        bookmarkId = intent.getStringExtra(BOOKMARKID);

    // set the cover image from assets
    ImageView coverImage = (ImageView) header.findViewById(R.id.coverImage);
    try {
        InputStream ims = getAssets().open("cover.png");
        Drawable d = Drawable.createFromStream(ims, null);
        coverImage.setImageDrawable(d);
    } catch (Exception e) {
        throw new RuntimeException("Error loading cover image. Is 'cover.png' available in assets?", e);
    }

    // make the web content debuggable from external chrome tools
    WebView.setWebContentsDebuggingEnabled(true);

    // enable script interfaces
    scriptSystem = new ScriptSystem(this);
    scriptStorage = new ScriptStorage(this,
            getApplicationContext().getSharedPreferences(ScriptStorage.CONTEXT, Context.MODE_PRIVATE));
    scriptSound = new ScriptSound(this);
    scriptGameServices = new ScriptGameServices(this);

    // setup character webview
    character = (WebView) header.findViewById(R.id.characterView);
    character.getSettings().setJavaScriptEnabled(true);
    character.getSettings().setDomStorageEnabled(true);
    character.getSettings().setAllowFileAccess(true);
    character.getSettings().setAppCacheEnabled(true);
    character.addJavascriptInterface(scriptSystem, "sqSystem");
    character.addJavascriptInterface(scriptStorage, "nativeStorage");
    character.addJavascriptInterface(scriptSound, "sqSound");
    character.addJavascriptInterface(scriptGameServices, "sqGameServices");
    character.loadUrl("file:///android_asset/character.html");

    // setup web view
    web = (WebView) findViewById(R.id.webView);
    web.getSettings().setJavaScriptEnabled(true);
    web.getSettings().setDomStorageEnabled(true);
    web.getSettings().setAllowFileAccess(true);
    web.getSettings().setAppCacheEnabled(true);
    web.addJavascriptInterface(scriptSystem, "sqSystem");
    web.addJavascriptInterface(scriptStorage, "nativeStorage");
    web.addJavascriptInterface(scriptSound, "sqSound");
    web.addJavascriptInterface(scriptGameServices, "sqGameServices");

    // adding event overrides for the web view
    web.setWebChromeClient(new WebChromeClient());
    web.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String urlText) {
            if (urlText.startsWith("http")) { // Could be cleverer and use a regex
                Log.d(LOGTAG, "Opening standard web intent window for " + urlText);
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(urlText));
                startActivity(i);
                return true;
            } else {
                Log.d(LOGTAG, "Loading in webview: " + urlText);
                web.loadUrl(urlText);
                return true;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(LOGTAG, "Page rendering started: " + url + ".");
            displaySpinner(R.string.loading);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(LOGTAG, "Page rendering finished: " + url + ".");
            hideSpinner();
            if (bookmarkId != null && url.startsWith("file:///android_asset/content.html")) {
                Log.i(LOGTAG, "Loading bookmark " + bookmarkId + ".");
                execJavaScriptInContent("loadBookmark('" + bookmarkId + "')");
                bookmarkId = null;
            }
            super.onPageFinished(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            Log.d(LOGTAG, "Intercepted call: " + url + ".");
            return null;
        }
    });
    web.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d(LOGTAG, cm.message() + " - from line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
        }
    });
    web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    web.requestFocus(View.FOCUS_DOWN);

    // finally loading content bootstrap
    Log.i(LOGTAG, "Loading index.html");
    web.loadUrl("file:///android_asset/index.html");
}

From source file:net.oremland.rss.reader.fragments.BrowserFragment.java

private WebChromeClient getWebChromeClient() {
    return new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            if (getActivity() != null) {
                getActivity().setProgress(progress * 100);
            }/*w w  w.jav a2 s .com*/
        }
    };
}

From source file:ar.com.tristeslostrestigres.diasporanativewebapp.MainActivity.java

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

    progressBar = findViewById(R.id.progressBar);

    pm = new PrefManager(MainActivity.this);

    SharedPreferences config = getSharedPreferences("PodSettings", MODE_PRIVATE);
    podDomain = config.getString("podDomain", null);

    fab = findViewById(R.id.multiple_actions);
    fab.setVisibility(View.GONE);

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from ww  w. j a va 2  s  .  c  o  m*/
    getSupportActionBar().setTitle(null);

    txtTitle = (TextView) findViewById(R.id.toolbar_title);
    txtTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Helpers.isOnline(MainActivity.this)) {
                txtTitle.setText(R.string.jb_stream);
                webView.loadUrl("https://" + podDomain + "/stream");
            } else {
                Snackbar.make(v, R.string.no_internet, Snackbar.LENGTH_SHORT).show();
            }
        }
    });

    webView = findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.addJavascriptInterface(new JavaScriptInterface(), "NotificationCounter");

    if (savedInstanceState != null) {
        webView.restoreState(savedInstanceState);
    }

    wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setUseWideViewPort(true);
    wSettings.setLoadWithOverviewMode(true);
    wSettings.setDomStorageEnabled(true);
    wSettings.setMinimumFontSize(pm.getMinimumFontSize());
    wSettings.setLoadsImagesAutomatically(pm.getLoadImages());

    if (android.os.Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;
        }

        public void onPageFinished(WebView view, String url) {
            if (url.contains("/new") || url.contains("/sign_in")) {
                fab.setVisibility(View.GONE);
            } else {
                fab.setVisibility(View.VISIBLE);
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            new AlertDialog.Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage(description).setPositiveButton("CLOSE", null).show();
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.hideTopBar(wv);
                fab.setVisibility(View.VISIBLE);
            }

            if (progress == 100) {
                fab.collapse();
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.drawer), "Unable to get image",
                            Snackbar.LENGTH_SHORT).show();
                }

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

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

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

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

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    });

    /*
     * NavigationView
     */
    NavigationView navigationView = findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            if (menuItem.isChecked())
                menuItem.setChecked(false);
            else
                menuItem.setChecked(true);

            drawerLayout.closeDrawers();

            switch (menuItem.getItemId()) {
            default:
                Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                        Snackbar.LENGTH_SHORT).show();
                return true;

            case R.id.jb_stream:
                if (Helpers.isOnline(MainActivity.this)) {
                    txtTitle.setText(R.string.jb_stream);
                    webView.loadUrl("https://" + podDomain + "/stream");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_public:
                setTitle(R.string.jb_public);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/public");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_liked:
                txtTitle.setText(R.string.jb_liked);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/liked");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_commented:
                txtTitle.setText(R.string.jb_commented);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/commented");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_contacts:
                txtTitle.setText(R.string.jb_contacts);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/contacts");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_mentions:
                txtTitle.setText(R.string.jb_mentions);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/mentions");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_activities:
                txtTitle.setText(R.string.jb_activities);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/activity");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_followed_tags:
                txtTitle.setText(R.string.jb_followed_tags);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/followed_tags");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_manage_tags:

                txtTitle.setText(R.string.jb_manage_tags);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/tag_followings/manage");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_license:
                txtTitle.setText(R.string.jb_license);
                new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.license_title))
                        .setMessage(getString(R.string.license_text))
                        .setPositiveButton(getString(R.string.license_yes),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        Intent i = new Intent(Intent.ACTION_VIEW,
                                                Uri.parse("https://github.com/mdev88/Diaspora-Native-WebApp"));
                                        startActivity(i);
                                        dialog.cancel();
                                    }
                                })
                        .setNegativeButton(getString(R.string.license_no),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                })
                        .show();

                return true;

            case R.id.jb_aspects:
                txtTitle.setText(R.string.jb_aspects);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/aspects");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_settings:
                txtTitle.setText(R.string.jb_settings);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/user/edit");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();

                    return false;
                }

            case R.id.jb_pod:
                txtTitle.setText(R.string.jb_pod);
                if (Helpers.isOnline(MainActivity.this)) {
                    new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.confirmation))
                            .setMessage(getString(R.string.change_pod_warning))
                            .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                                @TargetApi(11)
                                public void onClick(DialogInterface dialog, int id) {
                                    webView.clearCache(true);
                                    dialog.cancel();
                                    Intent i = new Intent(MainActivity.this, PodsActivity.class);
                                    startActivity(i);
                                    finish();
                                }
                            }).setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
                                @TargetApi(11)
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            }).show();
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }
            }
        }
    });

    /*
     * DrawerLayout
     */
    drawerLayout = findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer);
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    //calling sync state is necessary or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();

    if (savedInstanceState == null) {
        if (Helpers.isOnline(MainActivity.this)) {
            webView.loadData("", "text/html", null);
            webView.loadUrl("https://" + podDomain);
        } else {
            Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT)
                    .show();
        }
    }

}

From source file:it.rignanese.leo.slimfacebook.MainActivity.java

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

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

    //setup the theme
    //int savedThemeId = Integer.parseInt(savedPreferences.getString("pref_key_theme8", "2131361965"));//get the last saved theme id
    //setTheme(savedThemeId);//this refresh the theme if necessary
    // TODO fix the change of status bar

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

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

    // setup the webView
    webViewFacebook = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewFacebook);//set the settings

    goHome();//load homepage

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

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

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

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

                    Toast.makeText(getApplicationContext(), getString(R.string.downloadOrShareWithBrowser),
                            Toast.LENGTH_LONG).show();
                    //TODO get bitmap from url
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

                //if the link doesn't contain 'facebook.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        }

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

            // show you progress image
            if (!swipeRefresh) {
                final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                refreshItem.setActionView(R.layout.circular_progress_bar);
            }
            swipeRefresh = false;
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // hide your progress image
            final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
            refreshItem.setActionView(null);
            super.onPageFinished(view, url);

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

    });

    //WebChromeClient for handling all chrome functions.
    webViewFacebook.setWebChromeClient(new WebChromeClient() {
        //to upload files
        //thanks to gauntface
        //https://github.com/GoogleChrome/chromium-webview-samples
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getBaseContext().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
                }

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

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

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

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

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });
}

From source file:org.globalquakemodel.org.idctdo.EQForm_MapView.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (DEBUG_LOG)
        Log.d(TAG, "ON CREATE");
    setContentView(R.layout.map_view);/* w w w. j a va 2s .  c  o  m*/
    mContext = this;

    MyStateSaver data = (MyStateSaver) getLastNonConfigurationInstance();
    if (data != null) {
        // Show splash screen if still loading
        if (data.showSplashScreen) {
            showSplashScreen();
        }
        setContentView(R.layout.map_view);

        // Rebuild your UI with your saved state here
    } else {
        showSplashScreen();
        setContentView(R.layout.map_view);
        // Do your heavy loading here on a background thread

    }

    //showSplashScreen();

    mWebView = (WebView) findViewById(R.id.map_webview);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);

    mWebView.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            if (DEBUG_LOG)
                Log.d(TAG, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
        }
    });

    if (DEBUG_LOG)
        Log.d(TAG, "adding JS interface");
    mWebView.addJavascriptInterface(this, "webConnector");

    mWebView.loadUrl("file:///android_asset/idct_map.html");
    mWebView.setWebViewClient(new MapWebViewClient());
    progressBar = new ProgressDialog(EQForm_MapView.this);
    progressBar.setMessage("Loading maps...");
    progressBar.setCancelable(false);
    progressBar.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    //Create Folder
    mediaFile = new File(Environment.getExternalStorageDirectory().toString() + "/idctdo/gemmedia");
    mediaFile.mkdirs();

    //Create Folder
    vectorsFile = new File(Environment.getExternalStorageDirectory().toString() + "/idctdo/kml");
    vectorsFile.mkdirs();

    mapTilesFile = new File(Environment.getExternalStorageDirectory().toString() + "/idctdo/maptiles");
    mapTilesFile.mkdirs();

    File testFile = new File(
            Environment.getExternalStorageDirectory().toString() + "/idctdo/kml/PUT_KML_FILES_HERE");
    try {
        testFile.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    File testFile2 = new File(Environment.getExternalStorageDirectory().toString()
            + "/idctdo/maptiles/PUT_DIRECTORIES_OF_ZYX_TILES_HERE");
    try {
        testFile2.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /** Creating a progress dialog window */
    mProgressDialog = new ProgressDialog(this);

    /** Close the dialog window on pressing back button */
    mProgressDialog.setCancelable(true);

    /** Setting a horizontal style progress bar */
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

    /** Setting a message for this progress dialog
    * Use the method setTitle(), for setting a title
    * for the dialog window
    *  */
    mProgressDialog.setMessage("Loading map data...");

    vectorsFile.toString();
    new SingleMediaScanner(this, testFile);
    new SingleMediaScanner(this, testFile2);

    sdCardPath = "file:///" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    if (DEBUG_LOG)
        Log.d(TAG, "sdcard Path: " + sdCardPath);
    // Restore preferences
    PreferenceManager.getDefaultSharedPreferences(this);
    //SharedPreferences settings = getSharedPreferences("R.xml.prefs"), 0);

    mlocListener = new MyLocationListener();
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    btn_locateMe = (Button) findViewById(R.id.btn_locate_me);
    btn_locateMe.setOnClickListener(locateMeListener);

    btn_takeCameraPhoto = (Button) findViewById(R.id.btn_take_photo);
    btn_takeCameraPhoto.setOnClickListener(takePhotoListener);

    //btn_take_survey_photo=(Button)findViewById(R.id.btn_take_survey_photo);
    //btn_take_survey_photo.setVisibility(View.INVISIBLE);//Poss Dodgy threading stuff using this

    btn_startSurvey = (Button) findViewById(R.id.btn_start_survey);
    btn_startSurvey.setVisibility(View.INVISIBLE);//Dodgy threading stuff using this
    btn_startSurvey.setOnClickListener(startSurveyListener);

    btn_cancelSurveyPoint = (Button) findViewById(R.id.btn_cancel_survey_point);
    btn_cancelSurveyPoint.setVisibility(View.INVISIBLE);//Dodgy threading stuff using this
    btn_cancelSurveyPoint.setOnClickListener(cancelSurveyPointListener);

    btn_startSurveyFavourite = (Button) findViewById(R.id.btn_start_survey_with_favourite);
    btn_startSurveyFavourite.setVisibility(View.INVISIBLE);//Dodgy threading stuff using this
    btn_startSurveyFavourite.setOnClickListener(selectFavouriteListener);

    btn_selectLayer = (Button) findViewById(R.id.btn_select_layer);
    btn_selectLayer.setOnClickListener(selectLayerListener);

    btn_selectVectorLayer = (Button) findViewById(R.id.btn_select_vector_layer);
    btn_selectVectorLayer.setOnClickListener(selectVectorLayerListener);

    btn_zoomIn = (Button) findViewById(R.id.btn_zoom_in);
    btn_zoomIn.setOnClickListener(zoomInListener);
    btn_zoomOut = (Button) findViewById(R.id.btn_zoom_out);
    btn_zoomOut.setOnClickListener(zoomOutListener);

    btn_edit_points = (ToggleButton) findViewById(R.id.btn_edit_points);
    btn_edit_points.setOnClickListener(editPointsListener);

    text_view_gpsInfo = (TextView) findViewById(R.id.text_view_gpsInfo);
    text_view_gpsInfo2 = (TextView) findViewById(R.id.text_view_gpsInfo2);

    //Load any of the previous survey points
    loadPrevSurveyPoints();
}

From source file:org.quantumbadger.redreader.fragments.WebViewFragment.java

@SuppressLint("NewApi")
@Override/*from  w  w w  .j ava2s.  c om*/
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    mActivity = (AppCompatActivity) getActivity();

    CookieSyncManager.createInstance(mActivity);

    outer = (FrameLayout) inflater.inflate(R.layout.web_view_fragment, null);

    final RedditPost src_post = getArguments().getParcelable("post");
    final RedditPreparedPost post;

    if (src_post != null) {

        final RedditParsedPost parsedPost = new RedditParsedPost(src_post, false);

        post = new RedditPreparedPost(mActivity, CacheManager.getInstance(mActivity), 0, parsedPost, -1, false,
                false);

    } else {
        post = null;
    }

    webView = (WebViewFixed) outer.findViewById(R.id.web_view_fragment_webviewfixed);
    final FrameLayout loadingViewFrame = (FrameLayout) outer
            .findViewById(R.id.web_view_fragment_loadingview_frame);

    /*handle download links show an alert box to load this outside the internal browser*/
    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(final String url, String userAgent, String contentDisposition,
                String mimetype, long contentLength) {
            {
                new AlertDialog.Builder(mActivity).setTitle(R.string.download_link_title)
                        .setMessage(R.string.download_link_message)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(url));
                                getContext().startActivity(i);
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setIcon(android.R.drawable.ic_dialog_alert).show();
            }
        }
    });
    /*handle download links end*/

    progressView = new ProgressBar(mActivity, null, android.R.attr.progressBarStyleHorizontal);
    loadingViewFrame.addView(progressView);
    loadingViewFrame.setPadding(General.dpToPixels(mActivity, 10), 0, General.dpToPixels(mActivity, 10), 0);

    final WebSettings settings = webView.getSettings();

    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    settings.setDomStorageEnabled(true);

    if (AndroidApi.isHoneyCombOrLater()) {
        settings.setDisplayZoomControls(false);
    }

    // TODO handle long clicks

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, final int newProgress) {

            super.onProgressChanged(view, newProgress);

            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                @Override
                public void run() {
                    progressView.setProgress(newProgress);
                    progressView.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
                }
            });
        }
    });

    if (mUrl != null) {
        webView.loadUrl(mUrl);
    } else {
        webView.loadDataWithBaseURL("https://reddit.com/", html, "text/html; charset=UTF-8", null, null);
    }

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, final String url) {

            if (url == null)
                return false;

            if (url.startsWith("data:")) {
                // Prevent imgur bug where we're directed to some random data URI
                return true;
            }

            // Go back if loading same page to prevent redirect loops.
            if (goingBack && currentUrl != null && url.equals(currentUrl)) {

                General.quickToast(mActivity,
                        String.format(Locale.US, "Handling redirect loop (level %d)", -lastBackDepthAttempt),
                        Toast.LENGTH_SHORT);

                lastBackDepthAttempt--;

                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                    webView.goBackOrForward(lastBackDepthAttempt);
                } else {
                    mActivity.finish();
                }
            } else {

                if (RedditURLParser.parse(Uri.parse(url)) != null) {
                    LinkHandler.onLinkClicked(mActivity, url, false);
                } else {
                    webView.loadUrl(url);
                    currentUrl = url;
                }
            }

            return true;
        }

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

            if (mUrl != null && url != null) {

                final AppCompatActivity activity = mActivity;

                if (activity != null) {
                    activity.setTitle(url);
                }
            }
        }

        @Override
        public void onPageFinished(final WebView view, final String url) {
            super.onPageFinished(view, url);

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {

                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {

                            if (currentUrl == null || url == null)
                                return;

                            if (!url.equals(view.getUrl()))
                                return;

                            if (goingBack && url.equals(currentUrl)) {

                                General.quickToast(mActivity, String.format(Locale.US,
                                        "Handling redirect loop (level %d)", -lastBackDepthAttempt));

                                lastBackDepthAttempt--;

                                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                                    webView.goBackOrForward(lastBackDepthAttempt);
                                } else {
                                    mActivity.finish();
                                }

                            } else {
                                goingBack = false;
                            }
                        }
                    });
                }
            }, 1000);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }
    });

    final FrameLayout outerFrame = new FrameLayout(mActivity);
    outerFrame.addView(outer);

    if (post != null) {

        final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(mActivity);

        final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(mActivity,
                new BezelSwipeOverlay.BezelSwipeListener() {
                    @Override
                    public boolean onSwipe(@BezelSwipeOverlay.SwipeEdge int edge) {

                        toolbarOverlay.setContents(post.generateToolbar(mActivity, false, toolbarOverlay));
                        toolbarOverlay.show(
                                edge == BezelSwipeOverlay.LEFT ? SideToolbarOverlay.SideToolbarPosition.LEFT
                                        : SideToolbarOverlay.SideToolbarPosition.RIGHT);
                        return true;
                    }

                    @Override
                    public boolean onTap() {

                        if (toolbarOverlay.isShown()) {
                            toolbarOverlay.hide();
                            return true;
                        }

                        return false;
                    }
                });

        outerFrame.addView(bezelOverlay);
        outerFrame.addView(toolbarOverlay);

        bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

        toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
    }

    return outerFrame;
}

From source file:tv.acfun.a63.ArticleActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/*  w  ww.  j  a va 2 s  . c  om*/
protected void initView(Bundle savedInstanceState) {
    ARTICLE_PATH = AcApp.getExternalCacheDir("article").getAbsolutePath();

    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");
    }
    if (!isWebMode) {
        if (aid == 0)
            throw new IllegalArgumentException(" id");
        getSupportActionBar().setTitle("ac" + aid);
        MobclickAgent.onEvent(this, "view_article");
        db = new DB(this);
        isFaved = db.isFav(aid);
    }
    mWeb.getSettings().setAppCachePath(ARTICLE_PATH);
    mWeb.addJavascriptInterface(new ACJSObject(), "AC");
    // Set a chrome client to handle the MediaResource on web page
    // like video,video loading progress, etc.
    mWeb.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            setTitle(title);
        }
    });
    mWeb.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Matcher matcher = sAreg.matcher(url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (matcher.find() || (matcher = sLiteAreg.matcher(url)).find()
                    || (matcher = sVreg.matcher(url)).find() || (matcher = sLiteVreg.matcher(url)).find()) {
                String acId = matcher.group(1);
                try {
                    intent.setData(Uri.parse("ac://ac" + acId));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    // nothing
                }

            } else if (Pattern.matches(sAppReg, url)) {
                String appLink = getString(R.string.app_ac_video_link);
                try {
                    intent.setData(Uri.parse(appLink));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    view.loadUrl(appLink);
                    return true;
                }

            }
            if (!isWebMode) {
                start(ArticleActivity.this, url);
                return true;
            } else {
                Uri uri = Uri.parse(url);
                if (uri.getHost() != null && !uri.getHost().contains("acfun")) {
                    try {
                        intent.setData(uri);
                        startActivity(intent);
                        return true;
                    } catch (ActivityNotFoundException ignored) {
                    }
                }
            }
            return false;
        }

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

        @Override
        public void onPageFinished(WebView view, String url) {
            setSupportProgressBarIndeterminateVisibility(false);
            if (isWebMode || imgUrls == null || imgUrls.isEmpty() || url.startsWith("file:///android_asset")
                    || AcApp.getViewMode() == Constants.MODE_NO_PIC) // ?
                return;
            //                    Log.d(TAG, "on finished:" + url);
            if ((url.equals(getBaseUrl()) || url.contains(NAME_ARTICLE_HTML)) && imgUrls.size() > 0
                    && !isDownloaded) {
                String[] arr = new String[imgUrls.size()];
                mDownloadTask = new DownloadImageTask();
                mDownloadTask.execute(imgUrls.toArray(arr));
            }

        }

    });
    mWeb.getSettings().setSupportZoom(true);
    mWeb.getSettings().setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        mWeb.getSettings().setDisplayZoomControls(false);
    setTextZoom(AcApp.getConfig().getInt("text_size", 0));
}

From source file:com.irccloud.android.activity.PastebinViewerActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override//from w  w  w .ja va 2s.  c o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(ColorScheme.getDialogWhenLargeTheme(ColorScheme.getUserTheme()));
    onMultiWindowModeChanged(isMultiWindow());
    if (savedInstanceState == null && (getWindowManager().getDefaultDisplay().getWidth() < TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 800, getResources().getDisplayMetrics())
            || isMultiWindow()))
        overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out);
    setContentView(R.layout.activity_pastebin);
    mSpinner = findViewById(R.id.spinner);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    toolbar.setNavigationIcon(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    getSupportActionBar().setTitle("");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mWebView = findViewById(R.id.image);
    mWebView.setBackgroundColor(ColorScheme.getInstance().contentBackgroundColor);
    mWebView.getSettings().setBuiltInZoomControls(true);
    if (Integer.parseInt(Build.VERSION.SDK) >= 19)
        mWebView.getSettings()
                .setDisplayZoomControls(!getPackageManager().hasSystemFeature("android.hardware.touchscreen"));
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JSInterface(), "Android");
    mWebView.getSettings().setLoadWithOverviewMode(false);
    mWebView.getSettings().setUseWideViewPort(false);
    mWebView.getSettings().setAppCacheEnabled(false);
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            fail();
        }

        @Override
        public void onLoadResource(WebView view, String url) {
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Crashlytics.log(
                    consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR ? Log.ERROR : Log.WARN,
                    "IRCCloud", "Javascript error - line: " + consoleMessage.lineNumber() + " message: "
                            + consoleMessage.message());
            return super.onConsoleMessage(consoleMessage);
        }
    });

    if (savedInstanceState != null && savedInstanceState.containsKey("url")) {
        url = savedInstanceState.getString("url");
        html = savedInstanceState.getString("html");
        mWebView.loadDataWithBaseURL(url, html, "text/html", "UTF-8", null);
    } else {
        if (getIntent() != null && getIntent().getDataString() != null) {
            url = getIntent().getDataString().replace(getResources().getString(R.string.PASTE_SCHEME), "https");
            if (!url.contains("?"))
                url += "?";
            try {
                url += "&mobile=android&version="
                        + getPackageManager().getPackageInfo(getPackageName(), 0).versionName + "&theme="
                        + ColorScheme.getUserTheme();
            } catch (PackageManager.NameNotFoundException e) {
            }
            new FetchPastebinTask().execute();
            Answers.getInstance().logContentView(new ContentViewEvent().putContentType("Pastebin"));
        } else {
            finish();
        }
    }
}

From source file:com.twitter4rk.TwitterAuthFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mTwitterWebView = new WebView(getActivity());
    final Bundle args = getArguments();
    if (args == null) {
        // This wont be case because startTwitterAuth() handles args for
        // fragment
        throw new IllegalArgumentException(
                "No arguments passed to fragment, Please use startTwitterAuth(...) method for showing this fragment");
    }/*from  w w  w. java  2  s .co  m*/
    // Get builder from args
    mBuilder = args.getParcelable(BUILDER_KEY);
    // Hide action bar
    if (mBuilder.hideActionBar)
        mBuilder.activity.getActionBar().hide();
    // Init progress dialog
    mProgressDialog = new ProgressDialog(mBuilder.activity);
    mProgressDialog.setMessage(mBuilder.progressText == null ? "Loading ..." : mBuilder.progressText);
    if (mBuilder.isProgressEnabled)
        mProgressDialog.show();

    // Init ConfigurationBuilder twitter4j
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    if (mBuilder.isDebugEnabled)
        cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(mBuilder.consumerKey);
    cb.setOAuthConsumerSecret(mBuilder.consumerSecret);

    // Web view client to handler url loading
    mTwitterWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Get url first
            final Uri uri = Uri.parse(url);
            // Check if we need to see for callback URL
            if (mBuilder.callbackUrl != null && url.contains(mBuilder.callbackUrl)) {
                // Get req info
                String oauthToken = uri.getQueryParameter("oauth_token");
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                if (mListener != null)
                    mListener.onSuccess(oauthToken, oauthVerifier);
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                mIsAuthenticated = true;
                removeMe();
                return true;
                // If no callback URL then check for info directly
            } else if (uri.getQueryParameter("oauth_token") != null
                    && uri.getQueryParameter("oauth_verifier") != null) {
                // Get req info
                String oauthToken = uri.getQueryParameter("oauth_token");
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                if (mListener != null)
                    mListener.onSuccess(oauthToken, oauthVerifier);
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                mIsAuthenticated = true;
                removeMe();
                return true;
                // If nothing then its failure
            } else {
                // Notify user
                if (mListener != null)
                    mListener.onFailure(
                            new Exception("Couldn't find the callback URL or oath parameters in response"));
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                removeMe();
                return false;
            }
        }
    });
    // Web Crome client to handler progress dialog visibility
    mTwitterWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                if (mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
            }
        }
    });
    final Handler handler = new Handler();
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                final TwitterFactory twitterFactory = new TwitterFactory(cb.build());
                final Twitter twitter = twitterFactory.getInstance();
                RequestToken requestToken = null;
                if (mBuilder.callbackUrl == null)
                    requestToken = twitter.getOAuthRequestToken();
                else
                    requestToken = twitter.getOAuthRequestToken(mBuilder.callbackUrl);
                final RequestToken finalRequestToken = requestToken;
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        final String url = finalRequestToken.getAuthorizationURL();
                        mTwitterWebView.loadUrl(url);
                    }
                });
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
    }).start();

    return mTwitterWebView;
}

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

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

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
    webSettings.setSupportMultipleWindows(false);
    webSettings.setSupportZoom(false);//from   www  . ja  v  a  2 s .co  m
    webSettings.setAppCacheEnabled(true);

    registerForContextMenu(mWebView);

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

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

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

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

    mWebView.setWebViewClient(new WebViewClient() {

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

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

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

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

    mWebView.setOnTouchListener(new View.OnTouchListener() {

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

            return false;
        }
    });
}