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.google.codelabs.cosu.MainActivity.java

private void setImageToView() {
    // Save the file in gallery

    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);//from  w  ww.jav a 2s  .com
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);

    // Get the dimensions of the view

    int targetH = imageView.getMaxHeight();
    int targetW = imageView.getMaxWidth();

    // Get the dimensions of the bitmap

    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoH = bmOptions.outHeight;
    int photoW = bmOptions.outWidth;

    // Determine how much to scale down image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;

    Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    imageView.setImageBitmap(imageBitmap);

    // Enable lock task button
    lockTaskButton.setEnabled(true);
}

From source file:com.zetterstrom.android.soundboarder.fragments.SoundboardFragment.java

public boolean saveAsNotification(Sound sound) {
    byte[] buffer = null;
    InputStream fIn = getActivity().getBaseContext().getResources().openRawResource(sound.getSoundResourceId());
    int size = 0;

    try {/*w  w  w.j a v a2  s .c  om*/
        size = fIn.available();
        buffer = new byte[size];
        fIn.read(buffer);
        fIn.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    String path = Environment.getExternalStorageDirectory().getPath() + "/media/audio/notifications/";
    String filename = sound.getDescription() + ".ogg";

    boolean exists = (new File(path)).exists();
    if (!exists) {
        new File(path).mkdirs();
    }

    FileOutputStream save;
    try {
        save = new FileOutputStream(path + filename);
        save.write(buffer);
        save.flush();
        save.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    getActivity().sendBroadcast(
            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path + filename)));

    File k = new File(path, filename);

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, sound.getDescription());
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
    values.put(MediaStore.Audio.Media.ARTIST, "soundboarder");
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
    values.put(MediaStore.Audio.Media.IS_ALARM, true);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

    // Insert it into the database
    getActivity().getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()),
            values);

    return true;
}

From source file:org.quantumbadger.redreader.image.ShareImageCallback.java

@Override
public void onPermissionGranted() {

    final RedditAccount anon = RedditAccountManager.getAnon();

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

        @Override/*w  w w  .  j av a 2  s  .  c o  m*/
        public void onFailure(final @CacheRequest.RequestFailureType int type, final Throwable t,
                final Integer status, final String readableMessage) {
            final RRError error = General.getGeneralErrorForFailure(activity, type, t, status, uri);
            General.showResultDialog(activity, error);
        }

        @Override
        public void onSuccess(final ImageInfo info) {

            CacheManager.getInstance(activity)
                    .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon, null,
                            Constants.Priority.IMAGE_VIEW, 0, DownloadStrategyIfNotCached.INSTANCE,
                            Constants.FileType.IMAGE, CacheRequest.DOWNLOAD_QUEUE_IMMEDIATE, 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(@CacheRequest.RequestFailureType int type, Throwable t,
                                Integer 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) {

                            String filename = General.filenameFromString(info.urlOriginal);
                            File dst = new File(Environment.getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES), filename);

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

                                while (dst.exists()) {
                                    count++;
                                    dst = new File(
                                            Environment.getExternalStoragePublicDirectory(
                                                    Environment.DIRECTORY_PICTURES),
                                            count + "_" + filename.substring(1));
                                }
                            }

                            Uri sharedImage = FileProvider.getUriForFile(context,
                                    "org.quantumbadger.redreader.provider", dst);

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

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

                                General.copyFile(cacheFileInputStream, dst);

                                Intent shareIntent = new Intent();
                                shareIntent.setAction(Intent.ACTION_SEND);
                                shareIntent.putExtra(Intent.EXTRA_STREAM, sharedImage);
                                shareIntent.setType(mimetype);
                                activity.startActivity(Intent.createChooser(shareIntent,
                                        activity.getString(R.string.action_share_image)));

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

                            activity.sendBroadcast(
                                    new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, sharedImage));

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

From source file:camera.AnotherCamera.java

/**
 * Add the picture to the photo gallery.
 * Must be called on all camera images or they will
 * disappear once taken.//from   ww  w .  j a  v a  2 s  .co m
 */
protected void addPhotoToGallery() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    CameraActivity activity = (CameraActivity) getActivity();
    File f = new File(activity.getCurrentPhotoPath());
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.getActivity().sendBroadcast(mediaScanIntent);
}

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

private void scrollCapture() {
    mProgress.setVisibility(View.VISIBLE);
    BkCfg.hideKeyboard(mUrl);/* ww  w. j  ava2 s.  co  m*/

    if (mLog.isDebugEnabled()) {
        String log = "";
        log += "===================================================================\n";
        log += "CAPTURE START\n";
        log += "===================================================================\n";
        mLog.debug(log);
    }

    new AsyncTask<Object, Integer, Boolean>() {
        Bitmap mBmp;

        @Override
        protected void onPreExecute() {
            int w, h;
            try {
                Picture pic = mWeb.capturePicture();

                w = pic.getWidth();
                h = pic.getHeight();
            } catch (Exception e) {
                w = mWeb.getMeasuredWidth();
                h = mWeb.getMeasuredHeight();
            }

            mWeb.measure(
                    View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED,
                            View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            mBmp = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);

            Canvas canvas = new Canvas(mBmp);
            mWeb.draw(canvas);
        }

        @Override
        protected Boolean doInBackground(Object... objects) {
            Context context = (Context) objects[0];

            File dnPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File ssPath = new File(dnPath, "screenshot");
            if (!ssPath.exists()) {
                ssPath.mkdirs();
            }

            String fileName = "test.png"; // DateFormat.format("yyyyMMdd-HHmmss", new Date()) + ".png";
            File ssFile = new File(ssPath, fileName);

            try {
                FileOutputStream os = new FileOutputStream(ssFile);
                mBmp.compress(Bitmap.CompressFormat.PNG, 90, os);
                os.flush();
                os.close();

                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.parse("file://" + ssFile.getAbsolutePath())));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (mBmp != null) {
                mBmp.recycle();
                mBmp = null;
            }

            if (mLog.isDebugEnabled()) {
                String log = "";
                log += "===================================================================\n";
                log += "CAPTURE END\n";
                log += "===================================================================\n";
                mLog.debug(log);
            }

            mProgress.setVisibility(View.GONE);
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MainActivity.this);
}

From source file:at.andreasrohner.spartantimelapserec.BackgroundService.java

@Override
public void onDestroy() {
    created = false;/*w  w  w .  j a v  a2  s.c om*/
    File projectDir = null;

    final Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            if (recorder != null)
                recorder.stop();
            handlerThread.quit();
        }
    });

    try {
        handlerThread.join(5000);
        if (handlerThread.isAlive()) {
            handlerThread.quit();
            handlerThread.join(2000);
        }
    } catch (Exception e) {
    }

    if (recorder != null) {
        projectDir = recorder.getOutputDir();
        recorder = null;
    }

    if (surfaceView != null) {
        WindowManager winMgr = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        winMgr.removeView(surfaceView);
    }

    if (wakeLock != null)
        wakeLock.release();

    if (projectDir != null && projectDir.exists())
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(projectDir)));
}

From source file:otmobile.FirstScreen.java

@Override
public void onPictureTaken(byte[] imageData) {
    // Use our utility functions to obtain a unique filename to store into the image gallery.
    File fullpath = new File(CoreHelper.getImageGalleryPath(), CoreHelper.getUniqueFilename("Img", ".JPG"));
    Log.d(TAG, "save to path: " + fullpath);

    try {//from   w w  w  .  ja  v a  2  s  . co m
        // Use our utility function to save this JPG encoded byte array to storage.
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageData);
        CoreHelper.saveFile(inputStream, fullpath);

        // Get a URI to broadcast and let Android know there is a new image in the gallery.
        Uri uri = Uri.fromFile(fullpath);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

        // Send the new picture taken to the enhancement screen so that users can modify it if necessary.
        gotoEnhanceImage(uri);
    } catch (IOException e) {
        // Log a message and display an error using our utility function.
        Log.e(TAG, e.getMessage(), e);
        CoreHelper.displayError(this, "Could not save the image to the gallery.");
    }
}

From source file:com.amaze.filemanager.utils.files.FileUtils.java

/**
 * Triggers {@link Intent#ACTION_MEDIA_SCANNER_SCAN_FILE} intent to refresh the media store.
 *
 * @param uri File's {@link Uri}/*w  w w  .  j  a  va  2  s  . c om*/
 * @param c {@link Context}
 */
public static void scanFile(@NonNull Uri uri, @NonNull Context c) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
    c.sendBroadcast(mediaScanIntent);
}

From source file:me.piebridge.prevent.ui.UserGuideActivity.java

private void refreshQrCode(File qrCode) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    mediaScanIntent.setData(Uri.fromFile(qrCode));
    sendBroadcast(mediaScanIntent);//  w  w  w.  java 2s  .com
}

From source file:com.nit.vicky.servicelayer.NoteService.java

/**
 * Considering the field is new, if it has media handle it
 * //from   w  ww.j  ava 2s  .  c  o  m
 * @param field
 */
private static void importMediaToDirectory(IField field, Context context) {
    String tmpMediaPath = null;
    switch (field.getType()) {
    case AUDIO:
        tmpMediaPath = field.getAudioPath();
        break;

    case IMAGE:
        tmpMediaPath = field.getImagePath();
        break;

    case TEXT:
    default:
        break;
    }
    if (tmpMediaPath != null) {
        try {
            File inFile = new File(tmpMediaPath);
            if (inFile.exists()) {
                Collection col = AnkiDroidApp.getCol();
                String mediaDir = col.getMedia().getDir() + "/";

                File mediaDirFile = new File(mediaDir);

                File parent = inFile.getParentFile();

                // If already there.
                if (mediaDirFile.getAbsolutePath().contentEquals(parent.getAbsolutePath())) {
                    return;
                }

                //File outFile = new File(mediaDir + inFile.getName().replaceAll(" ", "_"));

                //if (outFile.exists()) {

                File outFile = null;

                if (field.getType() == EFieldType.IMAGE) {
                    outFile = File.createTempFile("imggallery", ".jpg", DiskUtil.getStoringDirectory());
                } else if (field.getType() == EFieldType.AUDIO) {
                    outFile = File.createTempFile("soundgallery", ".mp3", DiskUtil.getStoringDirectory());
                }

                //}

                if (field.hasTemporaryMedia()) {
                    // Move
                    inFile.renameTo(outFile);
                } else {
                    // Copy
                    InputStream in = new FileInputStream(tmpMediaPath);
                    OutputStream out = new FileOutputStream(outFile.getAbsolutePath());

                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                }

                switch (field.getType()) {
                case AUDIO:
                    field.setAudioPath(outFile.getAbsolutePath());
                    break;

                case IMAGE:
                    field.setImagePath(outFile.getAbsolutePath());
                    break;
                default:
                    break;
                }

                Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                scanIntent.setData(Uri.fromFile(inFile));
                context.sendBroadcast(scanIntent);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}