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.vanco.abplayer.BiliVideoViewActivity.java

@SuppressLint("SimpleDateFormat")
@Override/* w ww .j  av  a 2s  . c  o  m*/
public void snapshot() {
    if (!com.vanco.abplayer.view.FileUtils.sdAvailable()) {
        ToastUtils.showToast(R.string.file_explorer_sdcard_not_available);
    } else {
        Uri imgUri = null;
        Bitmap bitmap = vPlayer.getCurrentFrame();
        if (bitmap != null) {
            File screenshotsDirectory = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                            + VP.SNAP_SHOT_PATH);
            if (!screenshotsDirectory.exists()) {
                screenshotsDirectory.mkdirs();
            }

            File savePath = new File(screenshotsDirectory.getPath() + "/"
                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
            if (ImageUtils.saveBitmap(savePath.getPath(), bitmap)) {
                imgUri = Uri.fromFile(savePath);
            }
        }
        if (imgUri != null) {
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imgUri));
            ToastUtils.showLongToast(getString(R.string.video_screenshot_save_in, imgUri.getPath()));
        } else {
            ToastUtils.showToast(R.string.video_screenshot_failed);
        }
    }
}

From source file:org.kontalk.ui.AbstractComposeFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // image from storage/picture from camera
    // since there are like up to 3 different ways of doing this...
    if (requestCode == SELECT_ATTACHMENT_OPENABLE || requestCode == SELECT_ATTACHMENT_PHOTO) {
        if (resultCode == Activity.RESULT_OK) {
            Uri[] uris = null;/*from  w  w w  . java 2 s  . c  om*/
            String[] mimes = null;

            // returning from camera
            if (requestCode == SELECT_ATTACHMENT_PHOTO) {
                if (mCurrentPhoto != null) {
                    Uri uri = Uri.fromFile(mCurrentPhoto);
                    // notify media scanner
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(uri);
                    getActivity().sendBroadcast(mediaScanIntent);
                    mCurrentPhoto = null;

                    uris = new Uri[] { uri };
                }
            } else {
                if (mCurrentPhoto != null) {
                    mCurrentPhoto.delete();
                    mCurrentPhoto = null;
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && data.getClipData() != null) {
                    ClipData cdata = data.getClipData();
                    uris = new Uri[cdata.getItemCount()];

                    for (int i = 0; i < uris.length; i++) {
                        ClipData.Item item = cdata.getItemAt(i);
                        uris[i] = item.getUri();
                    }
                } else {
                    uris = new Uri[] { data.getData() };
                    mimes = new String[] { data.getType() };
                }

                // SAF available, request persistable permissions
                if (MediaStorage.isStorageAccessFrameworkAvailable()) {
                    for (Uri uri : uris) {
                        if (uri != null && !"file".equals(uri.getScheme())) {
                            MediaStorage.requestPersistablePermissions(getActivity(), uri);
                        }
                    }
                }
            }

            for (int i = 0; uris != null && i < uris.length; i++) {
                Uri uri = uris[i];
                if (uri == null)
                    continue;

                String mime = (mimes != null && mimes.length >= uris.length) ? mimes[i] : null;

                if (mime == null || mime.startsWith("*/") || mime.endsWith("/*")) {
                    mime = MediaStorage.getType(getActivity(), uri);
                    Log.v(TAG, "using detected mime type " + mime);
                }

                if (ImageComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, mime, true, ImageComponent.class);
                else if (VCardComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                else
                    Toast.makeText(getActivity(), R.string.send_mime_not_supported, Toast.LENGTH_LONG).show();
            }
        }
        // operation aborted
        else {
            // delete photo :)
            if (mCurrentPhoto != null) {
                mCurrentPhoto.delete();
                mCurrentPhoto = null;
            }
        }
    }
    // contact card (vCard)
    else if (requestCode == SELECT_ATTACHMENT_CONTACT) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                Uri vcardUri = null;

                // get lookup key
                final Cursor c = getContext().getContentResolver().query(uri,
                        new String[] { Contacts.LOOKUP_KEY }, null, null, null);
                if (c != null) {
                    try {
                        if (c.moveToFirst()) {
                            String lookupKey = c.getString(0);
                            vcardUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
                        }
                    } catch (Exception e) {
                        Log.w(TAG, "unable to lookup selected contact. Did you grant me the permission?", e);
                        ReportingManager.logException(e);
                    } finally {
                        c.close();
                    }
                }

                if (vcardUri != null) {
                    sendBinaryMessage(vcardUri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                } else {
                    Toast.makeText(getContext(), R.string.err_no_contact, Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    // invite user
    else if (requestCode == REQUEST_INVITE_USERS) {
        if (resultCode == Activity.RESULT_OK) {

            ArrayList<Uri> uris;
            Uri threadUri = data.getData();
            if (threadUri != null) {
                String userId = threadUri.getLastPathSegment();
                addUsers(new String[] { userId });
            } else if ((uris = data.getParcelableArrayListExtra("org.kontalk.contacts")) != null) {
                String[] users = new String[uris.size()];
                for (int i = 0; i < users.length; i++)
                    users[i] = uris.get(i).getLastPathSegment();
                addUsers(users);
            }

        }
    }
}

From source file:kr.wdream.storyshop.AndroidUtilities.java

public static void addMediaToGallery(Uri uri) {
    if (uri == null) {
        return;/*from  w  ww .  ja v  a 2s. c  o  m*/
    }
    try {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(uri);
        ApplicationLoader.applicationContext.sendBroadcast(mediaScanIntent);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void addMediaToGallery(Uri uri) {
    if (uri == null) {
        return;//from  w  w w. ja v  a  2  s.com
    }
    try {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(uri);
        ApplicationLoader.applicationContext.sendBroadcast(mediaScanIntent);
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:com.example.camera2apidemo.Camera2BasicFragment.java

public static void saveImageToGallery(Context context, Bitmap bmp) {
    // ?//  w w  w  . j a v a2 s  .  c om
    File appDir = new File(Environment.getExternalStorageDirectory(), "Camera2API");
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    String fileName = System.currentTimeMillis() + ".jpg";
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // ?
    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName,
                null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // ?
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // image from storage/picture from camera
    // since there are like up to 3 different ways of doing this...
    if (requestCode == SELECT_ATTACHMENT_OPENABLE || requestCode == SELECT_ATTACHMENT_PHOTO) {
        if (resultCode == Activity.RESULT_OK) {
            Uri[] uris = null;//from w w  w .  j av  a  2 s  .c  o  m
            String[] mimes = null;

            // returning from camera
            if (data == null) {
                if (mCurrentPhoto != null) {
                    Uri uri = Uri.fromFile(mCurrentPhoto);
                    // notify media scanner
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(uri);
                    getActivity().sendBroadcast(mediaScanIntent);
                    mCurrentPhoto = null;

                    uris = new Uri[] { uri };
                }
            } else {
                if (mCurrentPhoto != null) {
                    mCurrentPhoto.delete();
                    mCurrentPhoto = null;
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && data.getClipData() != null) {
                    ClipData cdata = data.getClipData();
                    uris = new Uri[cdata.getItemCount()];

                    for (int i = 0; i < uris.length; i++) {
                        ClipData.Item item = cdata.getItemAt(i);
                        uris[i] = item.getUri();
                    }
                } else {
                    uris = new Uri[] { data.getData() };
                    mimes = new String[] { data.getType() };
                }

                // SAF available, request persistable permissions
                if (MediaStorage.isStorageAccessFrameworkAvailable()) {
                    for (Uri uri : uris) {
                        if (uri != null && !"file".equals(uri.getScheme())) {
                            MediaStorage.requestPersistablePermissions(getActivity(), uri);
                        }
                    }
                }
            }

            for (int i = 0; uris != null && i < uris.length; i++) {
                Uri uri = uris[i];
                String mime = (mimes != null && mimes.length >= uris.length) ? mimes[i] : null;

                if (mime == null || mime.startsWith("*/") || mime.endsWith("/*")) {
                    mime = MediaStorage.getType(getActivity(), uri);
                    Log.v(TAG, "using detected mime type " + mime);
                }

                if (ImageComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, mime, true, ImageComponent.class);
                else if (VCardComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                else
                    Toast.makeText(getActivity(), R.string.send_mime_not_supported, Toast.LENGTH_LONG).show();
            }
        }
        // operation aborted
        else {
            // delete photo :)
            if (mCurrentPhoto != null) {
                mCurrentPhoto.delete();
                mCurrentPhoto = null;
            }
        }
    }
    // contact card (vCard)
    else if (requestCode == SELECT_ATTACHMENT_CONTACT) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                // get lookup key
                final Cursor c = getActivity().getContentResolver().query(uri,
                        new String[] { Contacts.LOOKUP_KEY }, null, null, null);
                if (c != null) {
                    try {
                        c.moveToFirst();
                        String lookupKey = c.getString(0);
                        Uri vcardUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
                        sendBinaryMessage(vcardUri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                    } finally {
                        c.close();
                    }
                }
            }
        }
    }
}

From source file:de.baumann.browser.Browser_right.java

private void screenshot() {

    shareFile = helper_main.newFile(mWebView);

    try {//from w  w  w  .  ja v  a  2s.c o m
        mWebView.measure(
                View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        mWebView.layout(0, 0, mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight());
        mWebView.setDrawingCacheEnabled(true);
        mWebView.buildDrawingCache();

        bitmap = Bitmap.createBitmap(mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        int iHeight = bitmap.getHeight();
        canvas.drawBitmap(bitmap, 0, iHeight, paint);
        mWebView.draw(canvas);

    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        Snackbar.make(mWebView, R.string.toast_screenshot_failed, Snackbar.LENGTH_SHORT).show();
    }

    if (bitmap != null) {
        try {
            OutputStream fOut;
            fOut = new FileOutputStream(shareFile);

            bitmap.compress(Bitmap.CompressFormat.PNG, 50, fOut);
            fOut.flush();
            fOut.close();
            bitmap.recycle();

            Snackbar snackbar = Snackbar
                    .make(mWebView,
                            getString(R.string.context_saveImage_toast) + " " + shareFile.getName() + ". "
                                    + getString(R.string.app_open),
                            Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            helper_main.switchToActivity(Browser_right.this, Popup_files.class, "", false);
                        }
                    });
            snackbar.show();

            Uri uri = Uri.fromFile(shareFile);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
            sendBroadcast(intent);

        } catch (Exception e) {
            e.printStackTrace();
            Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
        }
    }
}

From source file:de.baumann.browser.Browser_left.java

private void screenshot() {

    shareFile = helper_main.newFile(mWebView);

    try {//from   w  ww .jav a2 s  .c  o  m
        mWebView.measure(
                View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        mWebView.layout(0, 0, mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight());
        mWebView.setDrawingCacheEnabled(true);
        mWebView.buildDrawingCache();

        bitmap = Bitmap.createBitmap(mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        int iHeight = bitmap.getHeight();
        canvas.drawBitmap(bitmap, 0, iHeight, paint);
        mWebView.draw(canvas);

    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        Snackbar.make(mWebView, R.string.toast_screenshot_failed, Snackbar.LENGTH_SHORT).show();
    }

    if (bitmap != null) {
        try {
            OutputStream fOut;
            fOut = new FileOutputStream(shareFile);

            bitmap.compress(Bitmap.CompressFormat.PNG, 50, fOut);
            fOut.flush();
            fOut.close();
            bitmap.recycle();

            Snackbar snackbar = Snackbar
                    .make(mWebView,
                            getString(R.string.context_saveImage_toast) + " " + shareFile.getName() + ". "
                                    + getString(R.string.app_open),
                            Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            helper_main.switchToActivity(Browser_left.this, Popup_files.class, "", false);
                        }
                    });
            snackbar.show();

            Uri uri = Uri.fromFile(shareFile);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
            sendBroadcast(intent);

        } catch (Exception e) {
            e.printStackTrace();
            Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
        }
    }
}

From source file:de.baumann.browser.Browser.java

private void screenshot() {

    shareFile = helper_main.newFile();/*from  w w w .jav a  2  s . c  o  m*/

    try {
        mWebView.measure(
                View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        mWebView.layout(0, 0, mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight());
        mWebView.setDrawingCacheEnabled(true);
        mWebView.buildDrawingCache();

        bitmap = Bitmap.createBitmap(mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        int iHeight = bitmap.getHeight();
        canvas.drawBitmap(bitmap, 0, iHeight, paint);
        mWebView.draw(canvas);

    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        Snackbar.make(mWebView, R.string.toast_screenshot_failed, Snackbar.LENGTH_SHORT).show();
    }

    if (bitmap != null) {
        try {
            OutputStream fOut;
            fOut = new FileOutputStream(shareFile);

            bitmap.compress(Bitmap.CompressFormat.PNG, 50, fOut);
            fOut.flush();
            fOut.close();
            bitmap.recycle();

            Snackbar snackbar = Snackbar
                    .make(mWebView,
                            getString(R.string.context_saveImage_toast) + " " + helper_main.newFileName() + ". "
                                    + getString(R.string.app_open),
                            Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String startDir = Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                    .getPath();
                            helper_main.openFilePicker(Browser.this, mWebView, startDir);
                        }
                    });
            snackbar.show();

            Uri uri = Uri.fromFile(shareFile);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
            sendBroadcast(intent);

        } catch (Exception e) {
            e.printStackTrace();
            Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
        }
    }
}

From source file:com.ezac.gliderlogs.FlightOverviewActivity.java

public boolean DoAction(int MyAct, String MyMsg) {
    final int Action = MyAct;
    final String Message = MyMsg;
    new AlertDialog.Builder(FlightOverviewActivity.this).setTitle("Bevestig deze opdracht").setMessage(Message)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override/* w w w . j  a va  2  s. c o  m*/
                public void onClick(DialogInterface dialog, int whichButton) {
                    switch (Action) {
                    case 1:
                        if (DoStatusCheck()) {
                            // first make backup of existing data
                            GliderLogToCSV("gliderlogs.db", "ezac");
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                            // first remove records from flights table
                            DoDrop();
                            // then do import of support table (glider &
                            // members) and any starts of this day
                            DoImport();
                        } else {
                            if ((intSum[0] + intSum[1]) != 0) {
                                makeToast(
                                        "Er zijn nog " + intSum[0] + " vluchten niet gestart en \n" + intSum[1]
                                                + " vluchten niet geland, deze moeten eerst opgelost worden.",
                                        1);
                            }
                            if ((intSum[2] + intSum[3]) != 0) {
                                makeToast("Er zijn nog " + intSum[2] + " vluchten niet verwijderd en \n"
                                        + intSum[3]
                                        + " vluchten moeten nog verwerkt worden\n probeer het later opnieuw, na 5 min.",
                                        1);
                            }
                        }
                        break;
                    case 2:
                        if (DoStatusCheck()) {
                            createDayReport();
                            GliderLogToCSV("gliderlogs.db", "ezac");
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                        } else {
                            if ((intSum[0] + intSum[1]) != 0) {
                                makeToast(
                                        "Er zijn nog " + intSum[0] + " vluchten niet gestart en \n" + intSum[1]
                                                + " vluchten niet geland, deze moeten eerst opgelost worden.",
                                        1);
                            }
                            if ((intSum[2] + intSum[3]) != 0) {
                                makeToast("Er zijn nog " + intSum[2] + " vluchten niet verwijderd en \n"
                                        + intSum[3]
                                        + " vluchten moeten nog verwerkt worden\n probeer het later opnieuw, na 5 min.",
                                        1);
                            }
                        }
                        break;
                    case 3:
                        if (isAuthenticated) {
                            //final Calendar c = Calendar.getInstance();
                            new LDRTask().execute(host_url + "api/passagiers/*.json?datum="
                                    + Common.FourDigits(c.get(Calendar.YEAR)), "4");
                            //+ "-" + Common.TwoDigits(c.get(Calendar.MONTH))
                        }
                        break;
                    case 4:
                        break;
                    default:
                        break;
                    }
                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Do nothing.
                }
            }).show();
    return true;
}