Example usage for android.media MediaScannerConnection scanFile

List of usage examples for android.media MediaScannerConnection scanFile

Introduction

In this page you can find the example usage for android.media MediaScannerConnection scanFile.

Prototype

public static void scanFile(Context context, String[] paths, String[] mimeTypes,
        OnScanCompletedListener callback) 

Source Link

Document

Convenience for constructing a MediaScannerConnection , calling #connect on it, and calling #scanFile with the given path and mimeType when the connection is established.

Usage

From source file:com.andfchat.frontend.activities.ChatScreen.java

public void exportChat() {
    int permissionCheck = ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    } else {//from  w  w  w  .jav  a 2  s.c  o m
        String filename = "FListLog-" + chatroomManager.getActiveChat().getName() + "-"
                + System.currentTimeMillis() + ".txt";
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(path, filename);

        try {
            path.mkdirs();

            OutputStream os = new FileOutputStream(file);
            os.write(Exporter.exportText(this, chatroomManager.getActiveChat()));
            os.close();

            ChatEntry entry = entryFactory.getNotation(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.exported, new Object[] { filename });
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);

            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {

                        }
                    });
        } catch (IOException e) {
            Ln.w("ExternalStorage", "Error writing " + file, e);
            ChatEntry entry = entryFactory.getError(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.export_failed);
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);
        }
    }

}

From source file:dentex.youtube.downloader.utils.Utils.java

public static void scanMedia(Context context, final String[] filePath, final String[] mime) {
    MediaScannerConnection.scanFile(context, filePath, mime, new OnScanCompletedListener() {
        @Override//from  w  w w  .  j  a  va 2s .  c om
        public void onScanCompleted(String path, Uri uri) {
            Log.v(DEBUG_TAG, "file " + path + " was scanned successfully: " + uri);
            //YTD.videoinfo.edit().putString(path, uri.toString()).apply();
        }
    });
}

From source file:com.flyingcrop.ScreenCaptureFragment.java

void savePlanes() {

    Image.Plane[] planes = image.getPlanes();
    Buffer imageBuffer = planes[0].getBuffer().rewind();
    //Log.i(TAG, "Time 2 " + (System.currentTimeMillis() - time_now));

    // create bitmap
    bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(imageBuffer);

    int offset = 0;
    int pixelStride = planes[0].getPixelStride();
    int rowStride = planes[0].getRowStride();
    int rowPadding = rowStride - pixelStride * mWidth;
    ByteBuffer buffer = planes[0].getBuffer();
    //Log.e(TAG, "Time 3 " + (System.currentTimeMillis() - time_now));
    for (int i = 0; i < mHeight; ++i) {
        for (int j = 0; j < mWidth; ++j) {
            int pixel = 0;
            pixel |= (buffer.get(offset) & 0xff) << 16; // R
            pixel |= (buffer.get(offset + 1) & 0xff) << 8; // G
            pixel |= (buffer.get(offset + 2) & 0xff); // B
            pixel |= (buffer.get(offset + 3) & 0xff) << 24; // A
            bitmap.setPixel(j, i, pixel);
            offset += pixelStride;//from  w  ww  .ja  v  a 2s .  co m
        }
        offset += rowPadding;
    }
    //Log.i(TAG, "Time 4 " + (System.currentTimeMillis() - time_now));

    Log.i(TAG, "x_inicial " + x_inicial);
    Log.i(TAG, "x_final " + x_final);
    Log.i(TAG, "y_inicial " + y_inicial);
    Log.i(TAG, "y_final " + y_final);

    bitmap = Bitmap.createBitmap(bitmap, (int) x_inicial, (int) status_bar_height + (int) y_inicial,
            Math.abs((int) x_final - (int) x_inicial), Math.abs((int) y_final - (int) y_inicial));
    //bitmap = Bitmap.createBitmap(bitmap, 0 ,0,mWidth, mHeight);
    // write bitmap to a file
    SharedPreferences settings = getActivity().getSharedPreferences("data", 0);

    if (!settings.getBoolean("watermark", false)) {
        Canvas mCanvas = new Canvas(bitmap);

        Bitmap watermark = resize(
                BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.watermark));

        mCanvas.drawBitmap(watermark, 0, 0, null);

    }

    String date = getDate();
    String dir = STORE_DIRECTORY + "/FlyingCrop/" + date + ".png";
    try {
        fos = new FileOutputStream(dir);
    } catch (Exception e) {

    }

    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    //Log.e(TAG, "Time 5 " + (System.currentTimeMillis() - time_now));
    File file = new File(dir);
    // MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

    if (settings.getBoolean("toast", true)) {
        Toast.makeText(getActivity(), getResources().getString(R.string.fragment_img_saved) + " " + dir,
                Toast.LENGTH_SHORT).show();
    }

    Intent mIntent = new Intent(getActivity(), Brush.class);
    getActivity().stopService(mIntent);

    notifySS(bitmap, date, dir);

    MediaScannerConnection.scanFile(getActivity(), new String[] { dir }, null, null);

    mImageReader = null;
    getActivity().finish();
}

From source file:opensource.zeocompanion.ZeoCompanionApplication.java

public static void forceShowOnPC(File theFile) {
    MediaScannerConnection.scanFile(mOurContext, new String[] { theFile.getPath() }, null, null);
}

From source file:com.musenkishi.wally.activities.ImageDetailsActivity.java

private void handleSavedImageData(Uri filePath) {
    if (filePath != null && filePath.getPath() != null) {
        Message msgObj = uiHandler.obtainMessage();
        msgObj.what = currentHandlerCode;
        msgObj.obj = filePath;/*  ww w.  j av a2  s.c  om*/
        uiHandler.sendMessage(msgObj);
        MediaScannerConnection.scanFile(getApplicationContext(), new String[] { filePath.getPath() }, null,
                new MediaScannerConnection.MediaScannerConnectionClient() {
                    @Override
                    public void onMediaScannerConnected() {

                    }

                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        getApplication().sendBroadcast(new Intent(FileChangeReceiver.FILES_CHANGED));
                    }
                });
    }
}

From source file:com.bitants.wally.activities.ImageDetailsActivity.java

private void handleSavedImageData(Uri filePath) {
    if (filePath != null && filePath.getPath() != null) {
        Message msgObj = uiHandler.obtainMessage();
        msgObj.what = currentHandlerCode;
        msgObj.obj = filePath;/* ww  w  .j  av  a 2  s . c  o m*/
        uiHandler.sendMessage(msgObj);
        MediaScannerConnection.scanFile(getApplicationContext(), new String[] { filePath.getPath() }, null,
                new MediaScannerConnection.MediaScannerConnectionClient() {
                    @Override
                    public void onMediaScannerConnected() {

                    }

                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        getApplication().sendBroadcast(new Intent(FileReceiver.GET_FILES));
                    }
                });
    }
}

From source file:com.kircherelectronics.accelerationfilter.activity.AccelerationPlotActivity.java

/**
 * Write the logged data out to a persisted file.
 *//*from www . j av a2s  . c  o m*/
private void writeLogToFile() {
    Calendar c = Calendar.getInstance();
    String filename = "AccelerationFilter-" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"
            + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.HOUR) + "-" + c.get(Calendar.MINUTE) + "-"
            + c.get(Calendar.SECOND) + ".csv";

    File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "AccelerationFilter"
            + File.separator + "Logs");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File file = new File(dir, filename);

    FileOutputStream fos;
    byte[] data = log.getBytes();
    try {
        fos = new FileOutputStream(file);
        fos.write(data);
        fos.flush();
        fos.close();

        CharSequence text = "Log Saved";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    } catch (FileNotFoundException e) {
        CharSequence text = e.toString();
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    } catch (IOException e) {
        // handle exception
    } finally {
        // Update the MediaStore so we can view the file without rebooting.
        // Note that it appears that the ACTION_MEDIA_MOUNTED approach is
        // now blocked for non-system apps on Android 4.4.
        MediaScannerConnection.scanFile(this, new String[] { file.getPath() }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(final String path, final Uri uri) {

                    }
                });
    }
}

From source file:com.tct.emailcommon.utility.AttachmentUtilities.java

public static void saveAttachmentToExternal(Context context, Attachment attachment, String path) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;// w  w  w.java  2  s.  c o  m
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    final long size;
    InputStream in = null;
    OutputStream out = null;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (Utility.isExternalStorageMounted()) {
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_S
            try {
                String cachedFileUri = attachment.getCachedFileUri();
                if (TextUtils.isEmpty(cachedFileUri)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(cachedFileUri));
            } catch (IOException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
                //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_S
            } catch (IllegalArgumentException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
            }
            //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_E
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_S
            //Note: we support save attachment at user designated location.
            File downloads;
            if (path != null) {
                downloads = new File(path);
            } else {
                downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            }
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_E
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            out = new FileOutputStream(file);
            size = copyFile(in, out);
            String absolutePath = file.getAbsolutePath();
            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);
            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;
            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }
        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_S
        //Note:we have saved the attachment to sd card,so should update the attachment destination external
        cv.put(AttachmentColumns.UI_DESTINATION, UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_EXTERNAL);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_E
    } catch (IOException e) {
        // Handle failures here...
        LogUtils.e(Logging.LOG_TAG, "IOException while save an attachment to external storage");
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            LogUtils.e(Logging.LOG_TAG, "ioexception while close the stream");
        }
    }
    // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_E
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_S
    //        context.getContentResolver().update(uri, cv, null, null);
    if (cv.size() > 0) {
        context.getContentResolver().update(uri, cv, null, null);
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_E
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
}

From source file:com.rks.musicx.misc.utils.Helper.java

/**
 * Multi file delete/*from w  ww. j  a  v  a2s . co m*/
 * @param songList
 * @param context
 */
public static void multiDeleteTrack(Action action, List<Song> songList, Context context) {
    if (songList.size() == 0) {
        return;
    }
    MaterialDialog.Builder dialog = new MaterialDialog.Builder(context);
    dialog.title("Delete Tracks");
    dialog.content(context.getString(R.string.delete_music));
    dialog.positiveText(android.R.string.ok);
    dialog.typeface(getFont(context), getFont(context));
    dialog.onPositive(new MaterialDialog.SingleButtonCallback() {
        @Override
        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            boolean confirm = false;
            for (Song song : songList) {
                String path = song.getmSongPath();
                if (path != null) {
                    File file = new File(path);
                    if (file.exists()) {
                        if (file.delete()) {
                            confirm = true;
                            MediaScannerConnection.scanFile(context, new String[] { file.getAbsolutePath() },
                                    new String[] { "audio/*" },
                                    new MediaScannerConnection.MediaScannerConnectionClient() {
                                        @Override
                                        public void onMediaScannerConnected() {

                                        }

                                        @Override
                                        public void onScanCompleted(String s, Uri uri) {
                                            action.refresh();
                                        }
                                    });
                        } else {
                            confirm = false;
                        }

                    }
                }
            }
            if (confirm) {
                Log.e("Helper", "files are Deleted");
                action.refresh();
                Toast.makeText(context, "All Songs deleted", Toast.LENGTH_SHORT).show();
            } else {
                Log.e("Helper", "files are not Deleted");
                action.refresh();
                Toast.makeText(context, "Failed to delete song", Toast.LENGTH_SHORT).show();
            }
        }
    });
    dialog.negativeText(R.string.cancel);
    dialog.show();
}

From source file:cn.suishen.email.activity.MessageViewFragmentBase.java

private File performAttachmentSave(MessageViewAttachmentInfo info) {
    Attachment attachment = Attachment.restoreAttachmentWithId(mContext, info.mId);
    Uri attachmentUri = AttachmentUtilities.getAttachmentUri(mAccountId, attachment.mId);

    try {/*from ww w . ja va  2  s.  c om*/
        File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        downloads.mkdirs();
        File file = Utility.createUniqueFile(downloads, attachment.mFileName);
        Uri contentUri = AttachmentUtilities.resolveAttachmentIdToContentUri(mContext.getContentResolver(),
                attachmentUri);
        InputStream in = mContext.getContentResolver().openInputStream(contentUri);
        OutputStream out = new FileOutputStream(file);
        IOUtils.copy(in, out);
        out.flush();
        out.close();
        in.close();

        String absolutePath = file.getAbsolutePath();

        // Although the download manager can scan media files, scanning only happens after the
        // user clicks on the item in the Downloads app. So, we run the attachment through
        // the media scanner ourselves so it gets added to gallery / music immediately.
        MediaScannerConnection.scanFile(mContext, new String[] { absolutePath }, null, null);

        DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
        dm.addCompletedDownload(info.mName, info.mName, false /* do not use media scanner */, info.mContentType,
                absolutePath, info.mSize, true /* show notification */);

        // Cache the stored file information.
        info.setSavedPath(absolutePath);

        // Update our buttons.
        updateAttachmentButtons(info);

        return file;

    } catch (IOException ioe) {
        // Ignore. Callers will handle it from the return code.
    }

    return null;
}