Example usage for android.content Intent ACTION_MEDIA_SCANNER_SCAN_FILE

List of usage examples for android.content Intent ACTION_MEDIA_SCANNER_SCAN_FILE

Introduction

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

Prototype

String ACTION_MEDIA_SCANNER_SCAN_FILE

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

Click Source Link

Document

Broadcast Action: Request the media scanner to scan a file and add it to the media database.

Usage

From source file:com.dycode.jepretstory.mediachooser.activity.HomeFragmentActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();/*from   w ww. j  a  v a 2 s.  c o m*/
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    //android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                    if (mVideoFragment == null) {
                        VideoFragment newVideoFragment = new VideoFragment();
                        newVideoFragment.addItem(fileUriString);

                    } else {
                        mVideoFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 5000);

        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the video capture
        } else {
            // Video capture failed, advise user
        }
    } else if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    if (mImageFragment == null) {
                        ImageFragment newImageFragment = new ImageFragment();
                        newImageFragment.addItem(fileUriString);

                    } else {
                        mImageFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 5000);
        }
    }
}

From source file:net.evendanan.android.hagarfingerpainting.HagarFingerpaintingActivity.java

private File takeScreenshot(boolean showToast) {
    View v = getWindow().getDecorView();
    final int originalAdsVisibility = mAdView.getVisibility();
    mAdView.setVisibility(View.INVISIBLE);
    mSettingsIcons.setVisibility(View.INVISIBLE);

    v.setDrawingCacheEnabled(true);//from w  w w  .  j  a va  2 s.c o m
    Bitmap cachedBitmap = v.getDrawingCache();
    Bitmap copyBitmap = cachedBitmap.copy(Bitmap.Config.RGB_565, true);
    FileOutputStream output = null;
    File file = null;
    try {
        File path = Places.getScreenshotFolder();
        Calendar cal = Calendar.getInstance();

        file = new File(path,
                getPainterName() + "_" + cal.get(Calendar.YEAR) + "_" + (1 + cal.get(Calendar.MONTH)) + "_"
                        + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + "_"
                        + cal.get(Calendar.MINUTE) + "_" + cal.get(Calendar.SECOND) + ".png");
        output = new FileOutputStream(file);
        copyBitmap.compress(CompressFormat.PNG, 100, output);
    } catch (FileNotFoundException e) {
        file = null;
        e.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        mAdView.setVisibility(originalAdsVisibility);
        mSettingsIcons.setVisibility(View.VISIBLE);
    }

    if (file != null) {
        if (showToast)
            Toast.makeText(getApplicationContext(), "Save fingerpainting to: " + file.getAbsolutePath(),
                    Toast.LENGTH_LONG).show();
        //sending a broadcast to the media scanner so it will scan the new screenshot.
        Intent requestScan = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        requestScan.setData(Uri.fromFile(file));
        sendBroadcast(requestScan);

        return file;
    } else {
        return null;
    }
}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Request the givens paths to be scanned by MediaScanner
 *
 * @param files Files and folders to scan
 *///from   w  w w  . j av a 2  s . c  om
public void mediaScannerScanFile(File... files) {
    if (android.os.Build.VERSION.SDK_INT > 19) {
        String[] paths = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            paths[i] = files[i].getAbsolutePath();
        }
        MediaScannerConnection.scanFile(_context, paths, null, null);
    } else {
        for (File file : files) {
            _context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        }
    }
}

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://  w  w w.ja va 2 s .  c  om
        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:com.lge.friendsCamera.CameraFileListViewActivity.java

/**
 * Handle response of getFile//from w  w  w.  j  a  v a2  s  .  c  o m
 * Update android gallery to show downloaded image and show toast message
 *
 * @param fileName downloaded file name
 * @param localUri downloaded file uri on local storage
 */
private void handleResponse(String fileName, String localUri) {
    //Set downloading flag as false
    //Update android gallery
    startDownloading = false;
    currentDownloadFile = "";
    mContext.sendBroadcast(
            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + (String) localUri)));
    Toast.makeText(mContext, fileName + " is saved", Toast.LENGTH_LONG).show();
    mProgressDialog.cancel();
}

From source file:com.nikhilnayak.games.octoshootar.ui.fragments.GameScoreFragment.java

private void handleShareScore() {
    new AsyncTask<Void, Void, Uri>() {
        @Override//from w w w .  ja v a  2  s  .  c o  m
        protected Uri doInBackground(Void... params) {
            final Bitmap bitmapToShare = getBitmapToShare();

            //Compress the bitmap before saving and sharing.
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmapToShare.compress(Bitmap.CompressFormat.JPEG, BITMAP_QUALITY, bytes);
            bitmapToShare.recycle();

            final Uri uriToShare = writeScoreBytesToExternalStorage(bytes);

            return uriToShare;
        }

        @Override
        protected void onPostExecute(Uri uri) {
            super.onPostExecute(uri);
            if (uri != null) {
                // Add the screen to the Media Provider's database.
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                mediaScanIntent.setData(uri);
                getActivity().sendBroadcast(mediaScanIntent);

                // Share intent
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                shareIntent.setType("image/*");
                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                getActivity().startActivity(shareIntent);
            }
        }
    }.execute();
}

From source file:com.remobile.camera.CameraLauncher.java

private void refreshGallery(Uri contentUri) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    mediaScanIntent.setData(contentUri);
    this.cordova.getActivity().sendBroadcast(mediaScanIntent);
}

From source file:com.jungle.base.utils.MiscUtils.java

public static void scanMediaFile(String file) {
    if (TextUtils.isEmpty(file)) {
        return;/*from   ww w .j a  v  a  2 s  .co m*/
    }

    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(new File(file)));
    AppCore.getApplicationContext().sendBroadcast(intent);
}

From source file:com.velli.passwordmanager.FragmentPasswordDetails.java

private void createScreenshot() {
    Utils.createScreenshot(mEntry, getActivity(), new OnScreenshotSavedListener() {

        @Override// w  ww  . j a  v a2s.c  o m
        public void onScreenshotSaved(final String path) {
            if (path != null && getView() != null) {
                final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                scanIntent.setData(Uri.parse(path));

                getActivity().sendBroadcast(scanIntent);

                mSnack = Snackbar
                        .make(getView(), getActivity().getText(R.string.action_screenshot_saved),
                                Snackbar.LENGTH_LONG)
                        .setAction(getActivity().getText(R.string.menu_action_open), new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent();
                                intent.setAction(android.content.Intent.ACTION_VIEW);
                                intent.setDataAndType(Uri.fromFile(new File(path)), "image/jpg");
                                try {
                                    startActivity(intent);
                                } catch (ActivityNotFoundException ex) {
                                    Toast.makeText(getActivity(), "There are no gallery application installed.",
                                            Toast.LENGTH_SHORT).show();
                                }

                            }
                        }).setActionTextColor(getActivity().getResources().getColor(R.color.color_primary_500));

                mSnack.show();
            }

        }
    });
}