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:io.hypertrack.sendeta.util.images.EasyImage.java

private static void notifyGallery(Context context, URI pictureUri) throws URISyntaxException {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(pictureUri);
    Uri contentUri = Uri.fromFile(f);/*from www . j  a v  a  2s.c om*/
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}

From source file:com.umeng.comm.ui.widgets.ImageBrowser.java

private void galleryAddPic(File savedFile) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(savedFile);
    mediaScanIntent.setData(contentUri);
    mActivity.sendBroadcast(mediaScanIntent);
}

From source file:com.example.gangzhang.myapplication.VideoPlayerActivity.java

@Override
public void onClick(View view) {
    if (view.getId() == R.id.capture) {
        Bitmap bitmap = mMediaPlayer.getCurrentFrame();
        File dir = Environment.getExternalStorageDirectory();
        Log.d("myapp", "dir=" + dir);

        File appDir = new File(Environment.getExternalStorageDirectory(), "Player");
        if (!appDir.exists()) {
            appDir.mkdir();// w w  w  . j  av  a  2 s . com
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);

        try {
            file.createNewFile();

            FileOutputStream fos = new FileOutputStream(file);
            BitmapFactory.Options options = new BitmapFactory.Options();

            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
            bitmap.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ?
        try {
            android.provider.MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // ?
        getApplicationContext()
                .sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

        //            getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    } else if (view.getId() == R.id.record) {
        if (mIsRecoding) {

        } else {
            //                new Thread(new Runnable() {
            //                    @Override
            //                    public void run() {
            //                        Bitmap bitmap = mMediaPlayer.getCurrentFrame();
            //                        if(bitmap==null){
            //                            Log.d("myapp","bitmap null");
            //                        }
            //                        byte[] yuv = getNV21(1920,1080,bitmap);
            //                        Log.d("myapp","yuv.length="+yuv.length);
            //
            //                        startH264(yuv);
            //                        bitmap.recycle();
            //                    }
            //                }).start();

        }
        mIsRecoding = !mIsRecoding;
    } else {
        if (mIsPlaying) {
            mPlayImageView.setImageResource(R.drawable.selector_play);
            stopVideoPlayback();
        } else {
            mPlayImageView.setImageResource(R.drawable.selector_pause);
            startVideoPlayback();
        }
    }

}

From source file:com.example.android.shuttershock.MainActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 2) {
        //Converts photo taken into a bitmap
        Bitmap photo = (Bitmap) data.getExtras().get("data");

        //Creates a new instance of a database
        DataBaseHandler db = new DataBaseHandler(this);

        String randomStringForPic = "";
        int length = 12;
        randomString(length);/* w w  w .  j  ava 2s  .c om*/
        randomStringForPic = randomString(length);
        picPathData = randomStringForPic;

        //Compresses the bitmap into a byte array,
        //which the database can read as a BLOB
        /* ByteArrayOutputStream stream = new ByteArrayOutputStream();
         photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
         byte imageInByte[] = stream.toByteArray(); */

        //Adds the picture into the contact class
        // db.addContact(new Contact(picPathData);
        String y = makeDate();
        Contact contact = new Contact(picPathData, y);
        db.addContact(contact);

        db.close();

        /* //Saves the image to the user's SD card
        File sdCardDirectory = Environment.getExternalStorageDirectory();
        File image = new File(sdCardDirectory, picPathData + ".png");
                
        Uri imageUri = Uri.fromFile(image);
        */

        //Create Folder
        File folder = new File(Environment.getExternalStorageDirectory().toString() + "/ShutterShockFolder");
        folder.mkdirs();

        //Save the path as a string value
        String extStorageDirectory = folder.toString();

        //Create New file and name it Image2.PNG
        File image = new File(extStorageDirectory, picPathData + ".PNG");

        Uri imageUri = Uri.fromFile(image);

        //Send a broadcast so that the image that was just taken is saved to the users SD card
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imageUri));

        boolean success = false;

        FileOutputStream outStream;
        try {

            //COnverts the image into a smaller form while still trying to keep the quality of the image
            outStream = new FileOutputStream(image);
            photo.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            /* 100 to keep full quality of the image */

            outStream.flush();
            outStream.close();
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //If image is saved tell the user and if not then tell the user
        if (success) {
            Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_LONG).show();
            picTaken = true;
        } else {
            Toast.makeText(getApplicationContext(), "Photo not saved", Toast.LENGTH_LONG).show();
        }

        readContacts();
        // textView = (TextView)findViewById(R.id.textView);

        dataList.setAdapter(adapter);

    } else if (requestCode == SELECT_PICTURE) {

        if (data != null && resultCode == RESULT_OK) {

            Uri selectedImage = data.getData();

            if (selectedImage == null) {
                Log.d("Status", "data is null");
            } else {
                Log.d("Status", "data is not null");
            }
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            if (bmp2 != null && !bmp2.isRecycled()) {
                bmp2 = null;
            }

            Log.d("Status:", filePath);
            // textView.setText(filePath);
            bmp2 = BitmapFactory.decodeFile(filePath);
            //ivGalImg.setBackgroundResource(0);
            //ivGalImg.setImageBitmap(bmp);
            DataBaseHandler db = new DataBaseHandler(this);

            String randomStringForPic = "";
            int length = 12;
            randomString(length);
            randomStringForPic = randomString(length);
            picPathData = randomStringForPic;

            //Compresses the bitmap into a byte array,
            //which the database can read as a BLOB
            /* ByteArrayOutputStream stream = new ByteArrayOutputStream();
             photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
             byte imageInByte[] = stream.toByteArray(); */

            //Adds the picture into the contact class
            // db.addContact(new Contact(picPathData);
            String y = makeDate();
            Contact contact = new Contact(picPathData, y);
            db.addContact(contact);

            db.close();

            //Saves the image to the user's SD card
            /* File sdCardDirectory = Environment.getExternalStorageDirectory();
             File image = new File(sdCardDirectory, picPathData + ".png");
                    
             Uri imageUri = Uri.fromFile(image);
                    
            */
            //Create Folder
            File folder = new File(
                    Environment.getExternalStorageDirectory().toString() + "/ShutterShockFolder");
            folder.mkdirs();

            //Save the path as a string value
            String extStorageDirectory = folder.toString();

            //Create New file and name it Image2.PNG
            File image = new File(extStorageDirectory, picPathData + ".PNG");

            Uri imageUri = Uri.fromFile(image);

            //Send a broadcast so that the image that was just taken is saved to the users SD card
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imageUri));

            boolean success = false;

            FileOutputStream outStream;
            try {

                //COnverts the image into a smaller form while still trying to keep the quality of the image
                outStream = new FileOutputStream(image);
                bmp2.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                /* 100 to keep full quality of the image */

                outStream.flush();
                outStream.close();
                success = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //If image is saved tell the user and if not then tell the user
            if (success) {
                Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_LONG).show();
                picTaken = true;
            } else {
                Toast.makeText(getApplicationContext(), "Photo not saved", Toast.LENGTH_LONG).show();
            }

            /*
                            //Compresses the bitmap into a byte array,
                            //which the database can read as a BLOB
                            if (bmp2 != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp2.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte imageInByte[] = stream.toByteArray(); */

            /* I'm going to finish this after pic taken is fixed
            //Adds the picture into the contact class
            db.addContact(new Contact(i, "gallery picture" +
                    "", imageInByte));
            i++;
                    
            */
            readContacts();
            // textView = (TextView)findViewById(R.id.textView);

            dataList.setAdapter(adapter);
        }
    }

}

From source file:com.sien.cpshoot.screencapture.ScreenCaptureFragment.java

private void saveImage(ImageReader mImageReader, int mWidth, int mHeight) {
    if (mImageReader == null)
        return;/* w  w w  .j a  v  a2  s .c  o  m*/

    Image image = mImageReader.acquireLatestImage();
    if (image == null)
        return;
    final Image.Plane[] planes = image.getPlanes();
    if (planes.length <= 0)
        return;

    final ByteBuffer buffer = planes[0].getBuffer();
    int offset = 0;
    int pixelStride = planes[0].getPixelStride();
    int rowStride = planes[0].getRowStride();
    int rowPadding = rowStride - pixelStride * mWidth;
    Bitmap bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.RGB_565);
    bitmap.copyPixelsFromBuffer(buffer);
    image.close();

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
    String strDate = dateFormat.format(new java.util.Date());
    String pathImage = Environment.getExternalStorageDirectory().getPath() + "/Pictures/";
    String nameImage = pathImage + strDate + ".png";
    if (bitmap != null) {
        try {
            File fileImage = new File(nameImage);
            if (!fileImage.exists()) {
                fileImage.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(fileImage);
            if (out != null) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
                Toast.makeText(getActivity(), "get phone's screen succeed", Toast.LENGTH_SHORT).show();
                Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(fileImage);
                media.setData(contentUri);
                getActivity().sendBroadcast(media);

                //
                beginCrop(Uri.fromFile(new File(nameImage)));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.media.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();//  w  w  w . j a v  a2 s. co m
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    if (videoFragment == null) {
                        VideoFragment newVideoFragment = new VideoFragment();
                        newVideoFragment.addItem(fileUriString);

                    } else {
                        videoFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 1500);

        } 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 (imageFragment == null) {
                        ImageFragment newImageFragment = new ImageFragment();
                        newImageFragment.addItem(fileUriString);

                    } else {
                        imageFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 1500);
        }
    } else if (requestCode == 300) {// 
        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() {
                    luyinFragment = new LuYinFragment();
                    getSupportFragmentManager().beginTransaction().replace(R.id.contain, luyinFragment)
                            .commit();
                    // Do something after 5000ms
                    // String fileUriString =
                    // fileUri.toString().replaceFirst("file:///",
                    // "/").trim();
                    // if(luyinFragment == null)
                    // {
                    // LuYinFragment newLuYinFragment = new LuYinFragment();
                    // newLuYinFragment.addItem(fileUriString);
                    //
                    // }else
                    // {
                    // luyinFragment.addItem(fileUriString);
                    // }
                    alertDialog.cancel();
                }
            }, 1500);
        }
    }
}

From source file:org.anhonesteffort.flock.ExportService.java

private void handleIndexFilesWithMediaScanner(List<File> files) {
    for (File file : files) {
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    }/* w  w  w .  j  a v a 2  s . c o  m*/
}

From source file:org.disrupted.rumble.network.protocols.firechat.workers.FirechatOverBluetooth.java

public String downloadFile(long length) {
    if (length < 0)
        return null;
    File directory;/*w w  w.  j av  a  2  s .c  o  m*/
    try {
        directory = FileUtil.getWritableAlbumStorageDir();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        String suffix = ".jpg";
        File attachedFile = File.createTempFile(imageFileName, /* prefix */
                suffix, /* suffix */
                directory /* directory */
        );

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(attachedFile);
            int BUFFER_SIZE = 1024;
            byte[] buffer = new byte[BUFFER_SIZE];
            while (length > 0) {
                long max_read = Math.min((long) BUFFER_SIZE, length);
                int count = pbin.read(buffer, 0, (int) max_read);
                if (count < 0)
                    throw new IOException("End of stream reached before downloading was complete");
                length -= count;
                fos.write(buffer, 0, count);
            }
        } finally {
            if (fos != null)
                fos.close();
        }
        // add the photo to the media library
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(attachedFile);
        mediaScanIntent.setData(contentUri);
        RumbleApplication.getContext().sendBroadcast(mediaScanIntent);

        return attachedFile.getName();
    } catch (IOException e) {
        Log.e(TAG, "[-] file has not been downloaded ", e);
        return null;
    }
}

From source file:ru.gkpromtech.exhibition.media.FullImageActivity.java

private void doSaveImage(int index) {
    Media item = items.get(index);

    //        insertFavoriteMedia(item.id, 1);

    String path;/*from w w  w . ja  v  a2  s  .  c o m*/
    try {
        path = Images.getLocalPath(item.url);
    } catch (Throwable e) {
        return;
    }

    String filename = new File(path).getName();
    File newFile = new File(imageRoot.getAbsolutePath() + "/" + filename);

    imageRoot.mkdirs();
    try {
        copy(new File(path), newFile);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(newFile)));

    Toast.makeText(this, R.string.media_saved, Toast.LENGTH_SHORT).show();
}

From source file:com.lithidsw.wallbox.app.randomizer.RandomizerFrag.java

private void galleryAddPic(Intent data) {
    String image = checkImage(data);
    if (image != null) {
        if (!new TableHelper(fa).isExist(Utils.calculateMD5(image))) {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            File f = new File(image);
            Uri contentUri = Uri.fromFile(f);
            mediaScanIntent.setData(contentUri);
            fa.sendBroadcast(mediaScanIntent);
            new TableHelper(fa).writePaperItem(image, Utils.calculateMD5(image));
        } else {/*from  w  ww .j a va 2s . c  om*/
            Toast.makeText(fa, "Picture already exists!", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(fa, "Picture returned null, couldn't add this image, try again.", Toast.LENGTH_LONG)
                .show();
    }
}