Example usage for android.content Intent ACTION_CHOOSER

List of usage examples for android.content Intent ACTION_CHOOSER

Introduction

In this page you can find the example usage for android.content Intent ACTION_CHOOSER.

Prototype

String ACTION_CHOOSER

To view the source code for android.content Intent ACTION_CHOOSER.

Click Source Link

Document

Activity Action: Display an activity chooser, allowing the user to pick what they want to before proceeding.

Usage

From source file:com.core.base.js.UploadHandler.java

private Intent createChooserIntent(Intent... intents) {
    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
    chooser.putExtra(Intent.EXTRA_TITLE, "Choose file for upload");
    return chooser;
}

From source file:org.skt.runtime.RuntimeChromeClient.java

private Intent createChooserIntent(Intent... intents) {
    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
    chooser.putExtra(Intent.EXTRA_TITLE, "Select Application");
    return chooser;
}

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

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

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

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

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

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

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

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

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

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

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

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

From source file:mgks.os.webview.MainActivity.java

@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" })
@Override/*from   w  w  w . ja  v  a 2 s  . c o m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.w("READ_PERM = ", Manifest.permission.READ_EXTERNAL_STORAGE);
    Log.w("WRITE_PERM = ", Manifest.permission.WRITE_EXTERNAL_STORAGE);
    //Prevent the app from being started again when it is still alive in the background
    if (!isTaskRoot()) {
        finish();
        return;
    }

    setContentView(R.layout.activity_main);

    asw_view = findViewById(R.id.msw_view);

    final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh);
    if (ASWP_PULLFRESH) {
        pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pull_fresh();
                pullfresh.setRefreshing(false);
            }
        });
        asw_view.getViewTreeObserver()
                .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                    @Override
                    public void onScrollChanged() {
                        if (asw_view.getScrollY() == 0) {
                            pullfresh.setEnabled(true);
                        } else {
                            pullfresh.setEnabled(false);
                        }
                    }
                });
    } else {
        pullfresh.setRefreshing(false);
        pullfresh.setEnabled(false);
    }

    if (ASWP_PBAR) {
        asw_progress = findViewById(R.id.msw_progress);
    } else {
        findViewById(R.id.msw_progress).setVisibility(View.GONE);
    }
    asw_loading_text = findViewById(R.id.msw_loading_text);
    Handler handler = new Handler();

    //Launching app rating request
    if (ASWP_RATINGS) {
        handler.postDelayed(new Runnable() {
            public void run() {
                get_rating();
            }
        }, 1000 * 60); //running request after few moments
    }

    //Getting basic device information
    get_info();

    //Getting GPS location of device if given permission
    if (ASWP_LOCATION && !check_permission(1)) {
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm);
    }
    get_location();

    //Webview settings; defaults are customized for best performance
    WebSettings webSettings = asw_view.getSettings();

    if (!ASWP_OFFLINE) {
        webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
    }
    webSettings.setSaveFormData(ASWP_SFORM);
    webSettings.setSupportZoom(ASWP_ZOOM);
    webSettings.setGeolocationEnabled(ASWP_LOCATION);
    webSettings.setAllowFileAccess(true);
    webSettings.setAllowFileAccessFromFileURLs(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setDomStorageEnabled(true);

    asw_view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
    asw_view.setHapticFeedbackEnabled(false);

    asw_view.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType,
                long contentLength) {

            if (!check_permission(2)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[] {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
                        file_perm);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription(getString(R.string.dl_downloading));
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                        URLUtil.guessFileName(url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                assert dm != null;
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    } else if (Build.VERSION.SDK_INT >= 19) {
        asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }
    asw_view.setVerticalScrollBarEnabled(false);
    asw_view.setWebViewClient(new Callback());

    //Rendering the default URL
    aswm_view(ASWV_URL, false);

    asw_view.setWebChromeClient(new WebChromeClient() {
        //Handling input[type="file"] requests for android API 16+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            if (ASWP_FUPLOAD) {
                asw_file_message = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType(ASWV_F_TYPE);
                if (ASWP_MULFILE) {
                    i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                }
                startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req);
            }
        }

        //Handling input[type="file"] requests for android API 21+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (check_permission(2) && check_permission(3)) {
                if (ASWP_FUPLOAD) {
                    if (asw_file_path != null) {
                        asw_file_path.onReceiveValue(null);
                    }
                    asw_file_path = filePathCallback;
                    Intent takePictureIntent = null;
                    if (ASWP_CAMUPLOAD) {
                        takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                            File photoFile = null;
                            try {
                                photoFile = create_image();
                                takePictureIntent.putExtra("PhotoPath", asw_cam_message);
                            } catch (IOException ex) {
                                Log.e(TAG, "Image file creation failed", ex);
                            }
                            if (photoFile != null) {
                                asw_cam_message = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            } else {
                                takePictureIntent = null;
                            }
                        }
                    }
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    if (!ASWP_ONLYCAM) {
                        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                        contentSelectionIntent.setType(ASWV_F_TYPE);
                        if (ASWP_MULFILE) {
                            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        }
                    }
                    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, getString(R.string.fl_chooser));
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                    startActivityForResult(chooserIntent, asw_file_req);
                }
                return true;
            } else {
                get_file();
                return false;
            }
        }

        //Getting webview rendering progress
        @Override
        public void onProgressChanged(WebView view, int p) {
            if (ASWP_PBAR) {
                asw_progress.setProgress(p);
                if (p == 100) {
                    asw_progress.setProgress(0);
                }
            }
        }

        // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            if (Build.VERSION.SDK_INT < 23 || check_permission(1)) {
                // location permissions were granted previously so auto-approve
                callback.invoke(origin, true, false);
            } else {
                // location permissions not granted so request them
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm);
            }
        }
    });
    if (getIntent().getData() != null) {
        String path = getIntent().getDataString();
        /*
        If you want to check or use specific directories or schemes or hosts
                
        Uri data        = getIntent().getData();
        String scheme   = data.getScheme();
        String host     = data.getHost();
        List<String> pr = data.getPathSegments();
        String param1   = pr.get(0);
        */
        aswm_view(path, false);
    }
}

From source file:net.bluecarrot.lite.MainActivity.java

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

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

    // if the app is being launched for the first time
    if (savedPreferences.getBoolean("first_run", true)) {
        //todo presentation
        // save the fact that the app has been started at least once
        savedPreferences.edit().putBoolean("first_run", false).apply();
    }//from  ww w .j a  va 2s.c om

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

    //**MOBFOX***//

    banner = (Banner) findViewById(R.id.banner);
    final Activity self = this;

    banner.setListener(new BannerListener() {
        @Override
        public void onBannerError(View view, Exception e) {
            //Toast.makeText(self, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerLoaded(View view) {
            //Toast.makeText(self, "banner loaded", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClosed(View view) {
            //Toast.makeText(self, "banner closed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerFinished(View view) {
            // Toast.makeText(self, "banner finished", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClicked(View view) {
            //Toast.makeText(self, "banner clicked", Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onCustomEvent(JSONArray jsonArray) {
            return false;
        }
    });

    banner.setInventoryHash(appHash);
    banner.load();

    // 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
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    /** get a subject and text and check if this is a link trying to be shared */
    String sharedSubject = getIntent().getStringExtra(Intent.EXTRA_SUBJECT);
    String sharedUrl = getIntent().getStringExtra(Intent.EXTRA_TEXT);

    // if we have a valid URL that was shared by us, open the sharer
    if (sharedUrl != null) {
        if (!sharedUrl.equals("")) {
            // check if the URL being shared is a proper web URL
            if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) {
                // if it's not, let's see if it includes an URL in it (prefixed with a message)
                int startUrlIndex = sharedUrl.indexOf("http:");
                if (startUrlIndex > 0) {
                    // seems like it's prefixed with a message, let's trim the start and get the URL only
                    sharedUrl = sharedUrl.substring(startUrlIndex);
                }
            }
            // final step, set the proper Sharer...
            urlSharer = String.format("https://m.facebook.com/sharer.php?u=%s&t=%s", sharedUrl, sharedSubject);
            // ... and parse it just in case
            urlSharer = Uri.parse(urlSharer).toString();
            isSharer = true;
        }
    }

    // setup the webView
    webViewFacebook = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewFacebook);
    //fits images to screen

    if (isSharer) {//if is a share request
        webViewFacebook.loadUrl(urlSharer);//load the sharer url
        isSharer = false;
    } else
        goHome();//load homepage

    //        webViewFacebook.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
    //            public void onSwipeLeft() {
    //                webViewFacebook.loadUrl("javascript:try{document.querySelector('#messages_jewel > a').click();}catch(e){window.location.href='" +
    //                        getString(R.string.urlFacebookMobile) + "messages/';}");
    //            }
    //
    //        });

    //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 = "<h1 style='text-align:center; padding-top:15%; font-size:70px;'>"
                    + getString(R.string.titleNoConnection) + "</h1> <h3 "
                    + "style='text-align:center; padding-top:1%; font-style: italic;font-size:50px;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='font-size:30px; text-align:center; padding-top:80%; "
                    + "opacity: 0.3;'>" + getString(R.string.awards) + "</h5>";
            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 || Uri.parse(url).getHost().endsWith("facebook.com")
                    || Uri.parse(url).getHost().endsWith("m.facebook.com") || url.contains(".gif")) {
                //url is ok
                return false;
            } else {
                if (Uri.parse(url).getHost().endsWith("fbcdn.net")) {
                    //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;
            } //https://www.facebook.com/dialog/return/close?#_=_
        }

        //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) {
                if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                    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) {
            if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                refreshItem.setActionView(null);
            }

            //load the css customizations
            String css = "";
            if (savedPreferences.getBoolean("pref_blackTheme", false)) {
                css += getString(R.string.blackCss);
            }
            if (savedPreferences.getBoolean("pref_fixedBar", true)) {

                css += getString(R.string.fixedBar);//get the first part

                int navbar = 0;//default value
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//get id
                if (resourceId > 0) {//if there is
                    navbar = getResources().getDimensionPixelSize(resourceId);//get the dimension
                }
                float density = getResources().getDisplayMetrics().density;
                int barHeight = (int) ((getResources().getDisplayMetrics().heightPixels - navbar - 44)
                        / density);

                css += ".flyout { max-height:" + barHeight + "px; overflow-y:scroll;  }";//without this doen-t scroll

            }
            if (savedPreferences.getBoolean("pref_hideSponsoredPosts", false)) {
                css += getString(R.string.hideSponsoredPost);
            }

            //apply the customizations
            webViewFacebook.loadUrl(
                    "javascript:function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = "
                            + "str; document.body.appendChild(node); } addStyleString('" + css + "');");

            //finish the load
            super.onPageFinished(view, url);

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

    });

    //WebChromeClient for handling all chrome functions.
    webViewFacebook.setWebChromeClient(new WebChromeClient() {
        //to the Geolocation
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            //todo notify when the gps is used
        }

        //to upload files
        //!!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
        // for >= Lollipop, all in one
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            /** Request permission for external storage access.
             *  If granted it's awesome and go on,
             *  otherwise just stop here and leave the method.
             */
            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
                    Toast.makeText(getApplicationContext(), "Error occurred while creating the File",
                            Toast.LENGTH_LONG).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, getString(R.string.chooseAnImage));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

            return true;
        }

        // creating image files (Lollipop only)
        private File createImageFile() throws IOException {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            if (!imageStorageDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                imageStorageDir.mkdirs();
            }

            // create an image file name
            imageStorageDir = new File(imageStorageDir + File.separator + "IMG_"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            return imageStorageDir;
        }

        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            mUploadMessage = uploadMsg;

            try {
                File imageStorageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        appDirectoryName);

                if (!imageStorageDir.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    imageStorageDir.mkdirs();
                }

                File file = new File(imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis()) + ".jpg");

                mCapturedImageURI = Uri.fromFile(file); // save to the private variable

                final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                //captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

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

                Intent chooserIntent = Intent.createChooser(i, getString(R.string.chooseAnImage));
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });

                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), ("Camera Exception"), Toast.LENGTH_LONG).show();
            }
        }

        // openFileChooser for other Android versions

        /**
         * may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
         * https://code.google.com/p/android/issues/detail?id=62220
         * however newer versions of KitKat fixed it on some devices
         */
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

    });

    // OnLongClickListener for detecting long clicks on links and images
    // !!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
    webViewFacebook.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // activate long clicks on links and image links according to settings
            if (true) {
                WebView.HitTestResult result = webViewFacebook.getHitTestResult();
                if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE
                        || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    Message msg = linkHandler.obtainMessage();
                    webViewFacebook.requestFocusNodeHref(msg);
                    return true;
                }
            }
            return false;
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@Override
protected WebView createViewInstance(final ThemedReactContext reactContext) {
    final ReactWebView webView = new ReactWebView(reactContext);

    /**//from   w w w .j a va  2s  .  c om
     * cookie?
     * 5.0???cookie,5.0?false
     * 
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
    }

    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            reactContext.getCurrentActivity().startActivity(intent);

            //                DownloadManager.Request request = new DownloadManager.Request(
            //                        Uri.parse(url));
            //
            //                request.setMimeType(mimetype);
            //                String cookies = CookieManager.getInstance().getCookie(url);
            //                request.addRequestHeader("cookie", cookies);
            //                request.addRequestHeader("User-Agent", userAgent);
            //                request.allowScanningByMediaScanner();
            ////                request.setTitle()
            //                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            //                request.setDestinationInExternalPublicDir(
            //                        Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
            //                                url, contentDisposition, mimetype));
            //                DownloadManager dm = (DownloadManager) reactContext.getCurrentActivity().getSystemService(DOWNLOAD_SERVICE);
            //                dm.enqueue(request);
            //                Toast.makeText(reactContext, "...", //To notify the Client that the file is being downloaded
            //                        Toast.LENGTH_LONG).show();

        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage message) {
            if (ReactBuildConfig.DEBUG) {
                return super.onConsoleMessage(message);
            }
            // Ignore console logs in non debug builds.
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File imageFile = new File(storageDir, /* directory */
                    imageFileName + ".jpg" /* filename */
            );
            return imageFile;
        }

        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(reactContext.getCurrentActivity().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
                    FLog.e(ReactConstants.TAG, "Unable to create Image File", ex);
                }

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

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

            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, "?");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            // final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
            // galleryIntent.setType("image/*");
            // final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choose File");
            // reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            if (mVideoView != null) {
                callback.onCustomViewHidden();
                return;
            }

            // Store the view and it's callback for later, so we can dispose of them correctly
            mVideoView = view;
            mCustomViewCallback = callback;

            view.setBackgroundColor(Color.BLACK);
            getRootView().addView(view, FULLSCREEN_LAYOUT_PARAMS);
            webView.setVisibility(View.GONE);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity()
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }

        @Override
        public void onHideCustomView() {
            if (mVideoView == null) {
                return;
            }

            mVideoView.setVisibility(View.GONE);
            getRootView().removeView(mVideoView);
            mVideoView = null;
            mCustomViewCallback.onCustomViewHidden();
            webView.setVisibility(View.VISIBLE);
            //                View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
            //                // Show Status Bar.
            //                int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
            //                decorView.setSystemUiVisibility(uiOptions);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    //                                decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                    //                                    @Override
                    //                                    public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    //                                        WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    //                                        return defaultInsets.replaceSystemWindowInsets(
                    //                                                defaultInsets.getSystemWindowInsetLeft(),
                    //                                                0,
                    //                                                defaultInsets.getSystemWindowInsetRight(),
                    //                                                defaultInsets.getSystemWindowInsetBottom());
                    //                                    }
                    //                                });
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }

        private ViewGroup getRootView() {
            return ((ViewGroup) reactContext.getCurrentActivity().findViewById(android.R.id.content));
        }

    });

    reactContext.addLifecycleEventListener(webView);
    reactContext.addActivityEventListener(new ActivityEventListener() {
        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
                return;
            }
            Uri[] results = null;

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[] { Uri.parse(mCameraPhotoPath) };
                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[] { Uri.parse(dataString) };
                    }
                }
            }

            if (results == null) {
                mFilePathCallback.onReceiveValue(new Uri[] {});
            } else {
                mFilePathCallback.onReceiveValue(results);
            }
            mFilePathCallback = null;
            return;
        }

        @Override
        public void onNewIntent(Intent intent) {
        }
    });
    mWebViewConfig.configWebView(webView);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(false);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setDefaultFontSize(16);
    webView.getSettings().setTextZoom(100);
    // Fixes broken full-screen modals/galleries due to body height being 0.
    webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    return webView;
}

From source file:com.ushahidi.android.app.ui.phone.AddReportActivity.java

/**
 * Get shared text from other Android applications
 *//*w  w w. j a va2  s . c om*/
public void getSharedText() {
    Intent intent = getIntent();
    String action = intent.getAction();
    if (action != null) {
        if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_CHOOSER)) {
            CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
            if (text != null) {
                view.mIncidentDesc.setText(text);
            }
        }
    }
}

From source file:com.dish.browser.activity.BrowserActivity.java

@Override
public void showFileChooser(ValueCallback<Uri[]> filePathCallback) {
    if (mFilePathCallback != null) {
        mFilePathCallback.onReceiveValue(null);
    }//w w  w. j a  v  a 2 s. c o  m
    mFilePathCallback = filePathCallback;

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

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

    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);

    mActivity.startActivityForResult(chooserIntent, 1);
}