Example usage for android.webkit WebViewClient WebViewClient

List of usage examples for android.webkit WebViewClient WebViewClient

Introduction

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

Prototype

WebViewClient

Source Link

Usage

From source file:com.cnm.cnmrc.fragment.search.SearchNaver.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.search_naver, container, false);

    preventClickDispatching = (FrameLayout) layout.findViewById(R.id.prevent_click_dispatching);
    preventClickDispatching.setOnClickListener(this);

    webview = (WebView) layout.findViewById(R.id.webView);
    webview.setVisibility(View.INVISIBLE);

    // listview/*w w  w .ja  v  a  2  s  . c  o m*/
    listView = (ListView) layout.findViewById(R.id.listview);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //Intent intent = new Intent(Intent.ACTION_VIEW);
            //Uri uri = Uri.parse(mResult.get(position).getLink());
            //intent.setData(uri);
            //getActivity().startActivity(intent);

            //webview use to call own site
            webview.setWebViewClient(new WebViewClient());
            WebSettings set = webview.getSettings();
            set.setJavaScriptEnabled(true);
            set.setBuiltInZoomControls(true);
            webview.loadUrl(mResult.get(position).getLink());
            webview.setVisibility(View.VISIBLE);

            // zoom all
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);

            //webview.setVerticalScrollBarEnabled(false);
            //webview.setHorizontalScrollBarEnabled(false);
        }

    });

    return layout;
}

From source file:com.robandjen.comicsapp.FullscreenActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override//w  ww .j  a  v a 2  s.  c o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_fullscreen);

    final WebView v = (WebView) findViewById(R.id.fullscreen_content);
    v.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            updateShare(url);
            return false;
        }

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

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

    final WebSettings settings = v.getSettings();
    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.open_drawer,
            R.string.close_drawer);
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    if (mComicList == null) {

        try {
            InputStream is = openFileInput(COMICFILE);
            if (!loadXml(is)) {
                Log.w(TAG, "Downloaded list not parseable, defaulting to built-in");
            }
        } catch (FileNotFoundException e) {
            Log.i(TAG, "Downloaded list not found, defaulting to built-in");

        }
    }

    if (mComicList == null) {
        loadDefaultXML();
    }

    if (savedInstanceState != null) {
        mCurComic = savedInstanceState.getInt(CURCOMICKEY, 0);
        final String url = savedInstanceState.getString(CURURLKEY);
        showCurrentComic(url);
    } else {
        do {
            if (!bSkipOther || !mComicList.get(mCurComic).getOther()) {
                break;
            }

            ++mCurComic;
            mCurComic %= mComicList.size();
        } while (mCurComic != 0);
        showCurrentComic();
    }

}

From source file:ch.gianulli.trelloapi.ui.AuthenticationDialogFragment.java

@Nullable
@Override// w ww.  j  a  v  a 2 s.  co  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getDialog() != null) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    View v = inflater.inflate(R.layout.dialog_authentication, container, false);

    mProgressIndicator = (ProgressBar) v.findViewById(R.id.progress_indicator);
    mWebView = (WebView) v.findViewById(R.id.webview);

    // Catch token
    mWebView.setWebViewClient(new WebViewClient() {

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

        @Override
        public void onPageFinished(WebView view, String url) {
            setProgressIndicatorVisibility(false);
            if (url.equals(URL_TOKEN)) {
                // Get token and close dialog
                mWebView.loadUrl("javascript:window.HTMLOUT.parseHTML('<html>'+document"
                        + ".getElementsByTagName('html')[0].innerHTML+'</html>');");
            } else {
                super.onPageFinished(view, url);
            }
        }
    });
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
    mWebView.setVisibility(View.GONE);

    mWebView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                        return true;
                    }
                }

            }
            return false;
        }
    });

    // Load first page
    setProgressIndicatorVisibility(true);
    try {
        mWebView.loadUrl(URL_AUTHORIZATION + "key=" + mApi.getAppKey() + "&name="
                + URLEncoder.encode(getString(R.string.app_name), "UTF-8")
                + "&expiration=never&response_type=token&scope=read,write");
    } catch (UnsupportedEncodingException e) {
        // never happens
    }

    return v;
}

From source file:net.sarangnamu.scroll_capture.MainActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from   w ww.j a v a2  s  .  c  o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }

    setContentView(R.layout.activity_main);

    ButterKnife.bind(this);

    mWeb.loadUrl("http://aucd29.tistory.com/m");
    BkCfg.hideKeyboard(mWeb);

    mWeb.getSettings().setJavaScriptEnabled(true);
    mWeb.getSettings().setDomStorageEnabled(true);
    mWeb.getSettings().setLoadWithOverviewMode(true);
    mWeb.getSettings().setUseWideViewPort(true);
    mWeb.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mLog.isDebugEnabled()) {
                String log = "";
                log += "===================================================================\n";
                log += "WEBPAGE LOADED\n";
                log += "===================================================================\n";
                mLog.debug(log);
            }

            if (url.equals("http://aucd29.tistory.com/")) {
                mProgress.setVisibility(View.GONE);
                //                    mFab.animate().alpha(1);
            }
        }

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

            return true;
        }

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

            if (url.equals("http://aucd29.tistory.com/")) {
                mProgress.setVisibility(View.VISIBLE);
                //                    mFab.animate().alpha(0);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            if (mLog.isErrorEnabled()) {
                String log = "";
                log += "===================================================================\n";
                log += "ERROR: \n";
                log += "===================================================================\n";
                mLog.error(log);
            }
            super.onReceivedError(view, request, error);
        }
    });

}

From source file:org.safegees.safegees.gui.fragment.InfoFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_info, container, false);
    final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);

    webView = (WebView) view.findViewById(R.id.webview_info);
    //webView.getSettings().setAppCachePath( this.getActivity().getApplicationContext().getCacheDir().getAbsolutePath() );
    //webView.getSettings().setAppCacheEnabled( true );
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default

    if (!Connectivity.isNetworkAvaiable(getContext())) { // loading offline
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }//from w ww.  j  av a 2  s.  com
    webView.getSettings().setAllowFileAccess(true);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains(WebViewInfoWebDownloadController.CRISIS_HUB_DEFAULT_URL)) {
                view.loadUrl(url);

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

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

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

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webView.loadUrl("about:blank");
            webView.loadUrl("file:///android_asset/default_error.html");
        }

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

    //Load language
    String language = Locale.getDefault().getDisplayLanguage();
    if (language.equals("ar")) {
        webView.loadUrl(WebViewInfoWebDownloadController.CRISIS_HUB_DEFAULT_URL_AR);
    } else if (language.equals("fa")) {
        webView.loadUrl(WebViewInfoWebDownloadController.CRISIS_HUB_DEFAULT_URL_FA);
    } else {
        webView.loadUrl(WebViewInfoWebDownloadController.CRISIS_HUB_DEFAULT_URL);
    }

    return view;
}

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

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

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

    setContentView(R.layout.activity_main);

    //setup the floating button
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override//from ww w .  j  a v  a 2  s .  c  om
        public void onClick(View view) {
            webViewTwitter.scrollTo(0, 0);//scroll up
        }
    });

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

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

    goHome();//load homepage

    //WebViewClient that is the client callback.
    webViewTwitter.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>";
            webViewTwitter.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("twitter.com")) {
                //url is ok
                return false;
            } else {
                //if the link doesn't contain 'twitter.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        }

        //START management of loading
        @Override
        public void onPageFinished(WebView view, String url) {
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
            super.onPageFinished(view, url);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewTwitter.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:cn.zy.ef.fragment.WebViewFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mWebView.setWebViewClient(new WebViewClient() {
        @Override//from w ww  . j  a  v  a  2 s  . c o m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url); //?webviewurl
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            WebViewFragment.this.onPageFinished(view, url);
        }
    });

    if (!TextUtils.isEmpty(mUrl)) {
        mWebView.loadUrl(mUrl);
    }
}

From source file:de.uni_weimar.m18.anatomiederstadt.element.LatexFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_latex, container, false);
    WebView latexView = (WebView) root.findViewById(R.id.latexWebView);
    latexView.getSettings().setJavaScriptEnabled(true);
    latexView.getSettings().setBuiltInZoomControls(false);
    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = getActivity().getTheme();
    theme.resolveAttribute(R.color.windowBackgroundColor, typedValue, true);
    latexView.setBackgroundColor(typedValue.data);

    latexView.loadDataWithBaseURL("http://bar",
            "<script type='text/x-mathjax-config'>" + "MathJax.Hub.Config({ " + "messageStyle: 'none',"
                    + "showMathMenu: false, " + "jax: ['input/TeX','output/HTML-CSS'], "
                    + "extensions: ['tex2jax.js'], " + "TeX: { extensions: ['AMSmath.js','AMSsymbols.js',"
                    + "'noErrors.js','noUndefined.js'] } " + "});</script>" + "<script type='text/javascript' "
                    + "src='file:///android_asset/MathJax/MathJax.js'" + "></script><span id='math'></span>",
            "text/html", "utf-8", "");

    Log.v(LOG_TAG, "Loading latexCode: " + mLatexCode);
    latexView.setWebViewClient(new WebViewClient() {
        private String mLatexCode = null;

        @Override//from w  ww. j  a v a  2  s.  c o  m
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (Build.VERSION.SDK_INT < 19) {
                view.loadUrl("javascript:document.getElementById('math').innerHTML='\\\\["
                        + doubleEscapeTeX(getLatexCode()) + "\\\\]'");
                view.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
            } else {
                view.evaluateJavascript("javascript:document.getElementById('math').innerHTML='\\\\["
                        + doubleEscapeTeX(getLatexCode()) + "\\\\]'", null);
                view.evaluateJavascript("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);", null);
            }
        }
    });

    return root;
}

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 .jav  a 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:com.smoothsync.smoothsetup.microfragments.appspecificpassword.AppSpecificWebviewFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Nullable/*from   ww w  .ja  v  a  2s  . c  om*/
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.smoothsetup_microfragment_webview, container, false);
    mWebView = (WebView) root.findViewById(R.id.smoothsetup_webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setOnKeyListener(this);
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgress.animate().alpha(0).start();
        }
    });
    mWebView.addJavascriptInterface(new AppSpecificPasswordCallback() {
        @JavascriptInterface
        @Override
        public void onAppSpecificPassword(final String appSpecificPassword) {
            if (!TextUtils.isEmpty(appSpecificPassword)
                    && !TextUtils.equals(mAppSpecificPassword, appSpecificPassword)) {
                mAppSpecificPassword = appSpecificPassword;
                mSnackbar = Snackbar
                        .make(mWebView,
                                getString(R.string.smoothsetup_snackbar_found_app_specific_password,
                                        appSpecificPassword),
                                Snackbar.LENGTH_INDEFINITE)
                        .setAction(R.string.smoothsetup_button_copy_app_specific_password,
                                mOnCopyPasswordListener);
                mSnackbar.show();
            }
        }
    }, "SmoothSetup");
    String url = new FragmentEnvironment<Params>(this).microFragment().parameter().uri().toASCIIString();
    if (savedInstanceState == null) {
        mWebView.loadUrl(url);
    } else {
        mWebView.restoreState(savedInstanceState);
    }
    mPasswordProbe = new DefaultPasswordProbeFactory().forUrl(URI.create(url));
    mProgress = (ProgressBar) root.findViewById(android.R.id.progress);

    // start probing for the password
    mHandler.postDelayed(mPasswordProbeRunnable, PASSWORD_PROBE_PERIOD);

    return root;
}