Example usage for android.os Environment getExternalStoragePublicDirectory

List of usage examples for android.os Environment getExternalStoragePublicDirectory

Introduction

In this page you can find the example usage for android.os Environment getExternalStoragePublicDirectory.

Prototype

public static File getExternalStoragePublicDirectory(String type) 

Source Link

Document

Get a top-level shared/external storage directory for placing files of a particular type.

Usage

From source file:com.support.android.designlibdemo.activities.CampaignDetailActivity.java

public Uri getLocalBitmapUri(ImageView imageView) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;//from  www .  j  a  v a  2 s  .  com
    if (drawable instanceof BitmapDrawable) {
        bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
        return null;
    }

    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;

}

From source file:com.wondertoys.pokevalue.utils.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");
    if (update_file.length() > 0) {
        setChanged();/*from  w  ww .  java  2s .co m*/
        notifyObservers(AUTOUPDATE_HAVE_UPDATE);

        // raise the notification
        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Select to install";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(Uri.parse(
                "file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"
                        + update_file),
                ANDROID_PACKAGE);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setDefaults(
                Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
        builder.setSmallIcon(appIcon);
        builder.setTicker(appName + " update");
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setContentIntent(contentIntent);
        builder.setWhen(System.currentTimeMillis());
        builder.setAutoCancel(true);
        builder.setOngoing(true);

        nm.notify(NOTIFICATION_ID, builder.build());
    } else {
        //nm.cancel( NOTIFICATION_ID );   // tried this, but it just doesn't do the trick =(
        nm.cancelAll();
    }
}

From source file:com.paramedic.mobshaman.fragments.AccionesDetalleServicioFragment.java

protected 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 image = File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );/*from ww w .ja v a2  s . c o  m*/

    // Save a file: path for use with ACTION_VIEW intents
    DetalleServicioActivity activity = (DetalleServicioActivity) getActivity();
    activity.setCurrentPhotoPath("file:" + image.getAbsolutePath());
    return image;
}

From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity,
        final Action action) {

    switch (action) {

    case UPVOTE://from w w w .  ja v  a 2 s.co m
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case DELETE:
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.DELETE);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl()
                : post.url;
        intent.setData(Uri.parse(url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        LinkHandler.getImageInfo(activity, post.url, Constants.Priority.IMAGE_VIEW, 0,
                new GetImageInfoListener() {

                    @Override
                    public void onFailure(final RequestFailureType type, final Throwable t,
                            final StatusLine status, final String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(activity, type, t, status,
                                post.url);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    public void onSuccess(final ImgurAPI.ImageInfo info) {

                        CacheManager.getInstance(activity)
                                .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon,
                                        null, Constants.Priority.IMAGE_VIEW, 0,
                                        CacheRequest.DownloadType.IF_NECESSARY, Constants.FileType.IMAGE, false,
                                        false, false, activity) {

                                    @Override
                                    protected void onCallbackException(Throwable t) {
                                        BugReportActivity.handleGlobalError(context, t);
                                    }

                                    @Override
                                    protected void onDownloadNecessary() {
                                        General.quickToast(context, R.string.download_downloading);
                                    }

                                    @Override
                                    protected void onDownloadStarted() {
                                    }

                                    @Override
                                    protected void onFailure(RequestFailureType type, Throwable t,
                                            StatusLine status, String readableMessage) {
                                        final RRError error = General.getGeneralErrorForFailure(context, type,
                                                t, status, url.toString());
                                        General.showResultDialog(activity, error);
                                    }

                                    @Override
                                    protected void onProgress(boolean authorizationInProgress, long bytesRead,
                                            long totalBytes) {
                                    }

                                    @Override
                                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile,
                                            long timestamp, UUID session, boolean fromCache, String mimetype) {

                                        File dst = new File(
                                                Environment.getExternalStoragePublicDirectory(
                                                        Environment.DIRECTORY_PICTURES),
                                                General.uriFromString(info.urlOriginal).getPath());

                                        if (dst.exists()) {
                                            int count = 0;

                                            while (dst.exists()) {
                                                count++;
                                                dst = new File(
                                                        Environment.getExternalStoragePublicDirectory(
                                                                Environment.DIRECTORY_PICTURES),
                                                        count + "_" + General.uriFromString(info.urlOriginal)
                                                                .getPath().substring(1));
                                            }
                                        }

                                        try {
                                            final InputStream cacheFileInputStream = cacheFile.getInputStream();

                                            if (cacheFileInputStream == null) {
                                                notifyFailure(RequestFailureType.CACHE_MISS, null, null,
                                                        "Could not find cached image");
                                                return;
                                            }

                                            General.copyFile(cacheFileInputStream, dst);

                                        } catch (IOException e) {
                                            notifyFailure(RequestFailureType.STORAGE, e, null,
                                                    "Could not copy file");
                                            return;
                                        }

                                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                                Uri.parse("file://" + dst.getAbsolutePath())));

                                        General.quickToast(context,
                                                context.getString(R.string.action_save_image_success) + " "
                                                        + dst.getAbsolutePath());
                                    }
                                });

                    }

                    @Override
                    public void onNotAnImage() {
                        General.quickToast(activity, R.string.selected_link_is_not_image);
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        try {
            final Intent intent = new Intent(activity, PostListingActivity.class);
            intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).generateJsonUri());
            activity.startActivityForResult(intent, 1);

        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show();
        }

        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.author).toString());
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity.getFragmentManager(), null);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:co.scandy.example.scandycoreandroidexample.MainActivity.java

@SuppressWarnings("StatementWithEmptyBody")
@Override/* w  ww  .  j a  v  a  2s  . co  m*/
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.initialize_button) {
        // Setup the scan_controls
        if (mScanControlsView == null) {
            // Find the controls_container
            ViewStub stub = (ViewStub) findViewById(R.id.controls_container);
            // Set the resource to be the scan_controls
            stub.setLayoutResource(R.layout.scan_controls);
            // Store the view inflated as the mScanControlsView
            mScanControlsView = (LinearLayout) stub.inflate();
            // Bind the newly created controls to their callbacks
            bindScanControls();
        } else {
            // Or just make them visible again
            mScanControlsView.setVisibility(View.VISIBLE);
        }

        // Initialize the scanner with the first file we find in the Download directory
        File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getAbsolutePath());
        String rrf_path = "";
        // NOTE: you could present your users with a list of files to chose from if you felt like it!
        for (File file : dir.listFiles()) {
            if (file.getName().contains(".rrf")) {
                rrf_path = file.getAbsolutePath();
                break;
            }
        }

        // check to see if we have a USB sensor attached
        if (ScandyCore.hasValidSensor()) {
            ScandyCore.initializeScanner();
        } else if (rrf_path != "") {
            ScandyCore.initializeScanner(rrf_path);
        } else {
            // Show an Alert that we didn't find anything to initialize a scanner with
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("No scanner found");
            alertDialog.setMessage("Didn't find a pico flexx or a pre-recorded file.");
            alertDialog.show();
        }

    } else if (id == R.id.loadmesh_button) {
        // Make sure to uninitialize the scanner. Scandy Core gracefully handles various states.
        ScandyCore.uninitializeScanner();

        try {
            // Lets load a test Obj
            ScandyCore
                    .loadMeshFromURL(new URL("https://s3.amazonaws.com/scandycore-test-assets/scandy-obj.zip"));
        } catch (MalformedURLException e) {
            Log.e(TAG, e.getMessage());
        }
    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

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   www .j  a  v  a2 s .  c o m

    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.example.zf_android.activity.MerchantEdit.java

private void show2Dialog(int type) {

    AlertDialog.Builder builder = new AlertDialog.Builder(MerchantEdit.this);
    final String[] items = getResources().getStringArray(R.array.apply_detail_upload);

    MerchantEdit.this.type = type;

    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override//from  ww w  .j  a v a2 s .  c o m
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {

            case 0: {

                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                break;
            }
            case 1: {
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                    if (!outDir.exists()) {
                        outDir.mkdirs();
                    }
                    File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                    photoPath = outFile.getAbsolutePath();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                    startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                } else {
                    CommonUtil.toastShort(MerchantEdit.this, getString(R.string.toast_no_sdcard));
                }
                break;
            }
            }
        }
    });

    builder.show();
}

From source file:com.example.android.animationsdemo.CameraActivity.java

/** Create a File for saving an image or video */
private File getOutputMediaFile(int type) {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "GamaniaApp");
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            DKLog.d(TAG, "failed to create directory");
            return null;
        }/*www . j  a v a  2s  .c  o  m*/
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

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

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

    /**//from  ww  w. j a  v a  2 s .  c  o  m
     * 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:org.jraf.android.piclabel.app.form.FormActivity.java

private File createProcessedFile() {
    File picturesPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File albumPath = new File(picturesPath, Constants.ALBUM_NAME);
    albumPath.mkdirs();/*  w ww.j  a v  a 2  s  .c o m*/
    String fileDateName = new SimpleDateFormat("yyyy-MM-dd'_'HH-mm-ss", Locale.US).format(new Date());
    File res = new File(albumPath, fileDateName + ".jpg");
    return res;
}