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.owncloud.android.datamodel.FileDataStorageManager.java

public void triggerMediaScan(String path) {
    if (path != null) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        try {/*from  w ww  . j  a v  a  2 s . c  o  m*/
            intent.setData(FileProvider.getUriForFile(mContext.getApplicationContext(),
                    mContext.getResources().getString(R.string.file_provider_authority), new File(path)));
        } catch (IllegalArgumentException illegalArgumentException) {
            intent.setData(Uri.fromFile(new File(path)));
        }
        MainApp.getAppContext().sendBroadcast(intent);
    }
}

From source file:com.gelakinetic.mtgfam.fragments.CardViewFragment.java

/**
 * Saves the current card image to external storage
 *
 * @return A status string, to be displayed in a toast on the UI thread
 *//*from   w  w  w  . ja  v  a2s  .  c  om*/
private String saveImage() {
    File fPath;

    try {
        fPath = getSavedImageFile(true);
    } catch (Exception e) {
        return e.getMessage();
    }

    String strPath = fPath.getAbsolutePath();

    if (fPath.exists()) {
        return getString(R.string.card_view_image_saved) + strPath;
    }
    try {
        if (!fPath.createNewFile()) {
            return getString(R.string.card_view_unable_to_create_file);
        }

        FileOutputStream fStream = new FileOutputStream(fPath);

        /* If the card is displayed, there's a real good chance it's cached */
        String cardLanguage = mActivity.mPreferenceAdapter.getCardLanguage();
        if (cardLanguage == null) {
            cardLanguage = "en";
        }
        String imageKey = Integer.toString(mMultiverseId) + cardLanguage;
        Bitmap bmpImage;
        try {
            bmpImage = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
        } catch (NullPointerException e) {
            bmpImage = null;
        }

        /* Check if this is an english only image */
        if (bmpImage == null && !cardLanguage.equalsIgnoreCase("en")) {
            imageKey = Integer.toString(mMultiverseId) + "en";
            try {
                bmpImage = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
            } catch (NullPointerException e) {
                bmpImage = null;
            }
        }

        /* nope, not here */
        if (bmpImage == null) {
            return getString(R.string.card_view_no_image);
        }

        boolean bCompressed = bmpImage.compress(Bitmap.CompressFormat.JPEG, 90, fStream);
        fStream.flush();
        fStream.close();

        if (!bCompressed) {
            return getString(R.string.card_view_unable_to_save_image);
        }

    } catch (IOException ex) {
        return getString(R.string.card_view_save_failure);
    }

    /* Notify the system that a new image was saved */
    getFamiliarActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(fPath)));

    return getString(R.string.card_view_image_saved) + strPath;
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private boolean copyPart(PduPart part, String fallback) {
    Uri uri = part.getDataUri();//  w ww .  ja v a  2s.  c  o  m
    String type = new String(part.getContentType());
    boolean isDrm = DrmUtils.isDrmType(type);
    if (isDrm) {
        type = MmsApp.getApplication().getDrmManagerClient().getOriginalMimeType(part.getDataUri());
    }
    if (!ContentType.isImageType(type) && !ContentType.isVideoType(type) && !ContentType.isAudioType(type)) {
        return true; // we only save pictures, videos, and sounds. Skip the text parts,
                     // the app (smil) parts, and other type that we can't handle.
                     // Return true to pretend that we successfully saved the part so
                     // the whole save process will be counted a success.
    }
    InputStream input = null;
    FileOutputStream fout = null;
    try {
        input = mContentResolver.openInputStream(uri);
        if (input instanceof FileInputStream) {
            FileInputStream fin = (FileInputStream) input;

            byte[] location = part.getName();
            if (location == null) {
                location = part.getFilename();
            }
            if (location == null) {
                location = part.getContentLocation();
            }

            String fileName;
            if (location == null) {
                // Use fallback name.
                fileName = fallback;
            } else {
                // For locally captured videos, fileName can end up being something like this:
                //      /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp
                fileName = new String(location);
            }
            File originalFile = new File(fileName);
            fileName = originalFile.getName(); // Strip the full path of where the "part" is
                                               // stored down to just the leaf filename.

            // Depending on the location, there may be an
            // extension already on the name or not. If we've got audio, put the attachment
            // in the Ringtones directory.
            String dir = Environment.getExternalStorageDirectory() + "/"
                    + (ContentType.isAudioType(type) ? Environment.DIRECTORY_RINGTONES
                            : Environment.DIRECTORY_DOWNLOADS)
                    + "/";
            String extension;
            int index;
            if ((index = fileName.lastIndexOf('.')) == -1) {
                extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type);
            } else {
                extension = fileName.substring(index + 1, fileName.length());
                fileName = fileName.substring(0, index);
            }
            if (isDrm) {
                extension += DrmUtils.getConvertExtension(type);
            }
            // Remove leading periods. The gallery ignores files starting with a period.
            fileName = fileName.replaceAll("^.", "");

            File file = getUniqueDestination(dir + fileName, extension);

            // make sure the path is valid and directories created for this file.
            File parentFile = file.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
                return false;
            }

            fout = new FileOutputStream(file);

            byte[] buffer = new byte[8000];
            int size = 0;
            while ((size = fin.read(buffer)) != -1) {
                fout.write(buffer, 0, size);
            }

            // Notify other applications listening to scanner events
            // that a media file has been added to the sd card
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        }
    } catch (IOException e) {
        // Ignore
        Log.e(TAG, "IOException caught while opening or reading stream", e);
        return false;
    } finally {
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                // Ignore
                Log.e(TAG, "IOException caught while closing stream", e);
                return false;
            }
        }
        if (null != fout) {
            try {
                fout.close();
            } catch (IOException e) {
                // Ignore
                Log.e(TAG, "IOException caught while closing stream", e);
                return false;
            }
        }
    }
    return true;
}

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

public void DoServices() {
    // get services.xml view
    LayoutInflater li = LayoutInflater.from(context);
    servicesView = li.inflate(R.layout.services, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(servicesView);

    final EditText userInput = (EditText) servicesView.findViewById(R.id.editTextDialogUserInput);

    // set dialog message
    alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override/*from www  .  j a  va2 s  . com*/
        public void onClick(DialogInterface dialog, int id) {
            // get user input and set it to result
            if (userInput.getText().toString().equals("To3Myd4T")) {
                Log.d(TAG, "ok, user request to delete all, do it");
                CheckBox csv_ok = (CheckBox) servicesView.findViewById(R.id.service_csv);
                CheckBox db_ok = (CheckBox) servicesView.findViewById(R.id.service_db);
                // make a copy to csv file
                if (csv_ok.isChecked()) {
                    GliderLogToCSV("gliderlogs.db", "ezac");
                    makeToast("Export naar een CSV bestand is uitgevoerd !", 2);
                }
                // make a copy to sqlite database file
                if (db_ok.isChecked()) {
                    GliderLogToDB("com.ezac.gliderlogs", "gliderlogs.db", "ezac");
                    makeToast("Export naar een DB bestand is uitgevoerd !", 2);
                }
                if (csv_ok.isChecked() || db_ok.isChecked()) {
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                }
                // remove records from flights table
                DoDrop();
                // import support tables (glider, members, passengers & reservations)
                // and any starts for this day
                DoImport();
            } else {
                makeToast("De gebruikte service code is niet correct !", 0);
                Log.d(TAG, "Fail, user service code error >" + userInput.getText().toString() + "<");
            }
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });
    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    // show it
    alertDialog.show();
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

protected void onActivityResult(final int requestCode, int resultCode, final Intent data) {
    if (resultCode == RESULT_CANCELED)
        return;//from  ww w .java  2  s  .  c o  m

    //After running Media Gallery Program
    if (requestCode == ACTIVITY_SELECT_IMAGE) {
        Uri_image = data.getData();

        Intent i = new Intent(HomeScreen.this, SingleImageView.class);
        startActivity(i);

        return;
    }

    if (requestCode == ACTIVITY_SELECT_VIDEO) {
        Uri_image = data.getData();

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri_image, "video/mpeg");
        startActivity(intent);
        return;
    }

    //after running audio program
    if (requestCode == REQUEST_CODE_RECORD) {
        //move file into GT/s directory
        Uri savedUri = data.getData();
        Cursor cursor = getContentResolver().query(savedUri, null, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
            Uri filePathUri = Uri.parse(cursor.getString(column_index));
            String file_path = filePathUri.getPath();

            //rename the file
            String path = GTConstants.sendfileFolder + Utility.createFileName() + ".3ga";

            //put the file name into the global
            file_name = path;

            File file_to = new File(path);
            File file_from = new File(file_path);
            file_from.renameTo(file_to);

            //Toast.makeText(HomeScreen.this, file_name, Toast.LENGTH_LONG).show();
        }
    }

    //after running camera, audio or video program
    if (requestCode == REQUEST_CODE_RECORD || requestCode == CAMERA_PIC_REQUEST
            || requestCode == ACTION_TAKE_VIDEO) {

        //this section was pulled from the "Cancel" option of the the tagging code - it replaces tagging (i.e. as if cancel is always being selected

        try {
            //copy file to /GT/r directory so that local user can view the image
            File file = new File(file_name);
            copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder);

            //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
            //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));

            //new Upload_FTP().execute(file_name);
            Utility.setUploadAvailable();
        } catch (Exception e) {
            Toast.makeText(HomeScreen.this, "File copy Error: " + e, Toast.LENGTH_LONG).show();
        }

        //create filename info for dar
        String darFile[] = null;
        String newFile;
        try {
            darFile = file_name.split("_");
            newFile = GTConstants.LICENSE_ID.substring(7) + "_" + darFile[1] + "_" + darFile[2];
            //Toast.makeText(HomeScreen.this, "File: " + newFile, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(HomeScreen.this, "File Naming Error: " + e, Toast.LENGTH_LONG).show();
            newFile = "unknown";
        }

        //email option
        if (requestCode == REQUEST_CODE_RECORD) {
            //add event to dar and srp
            if (GTConstants.sendData) {
                Utility.write_to_file(HomeScreen.this,
                        GTConstants.dardestinationFolder + GTConstants.darfileName, "Voice;" + newFile + ".3ga"
                                + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                        true);

                if (GTConstants.srpfileName.length() > 1)
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.srpfileName,
                            "Voice;" + newFile + ".3ga" + ";" + Utility.getLocalTime() + ";"
                                    + Utility.getLocalDate() + "\r\n",
                            true);

            }
            send_media_via_email("audio");
        }

        if (requestCode == CAMERA_PIC_REQUEST) {
            //add event to dar and srp
            if (GTConstants.sendData) {
                Utility.write_to_file(HomeScreen.this,
                        GTConstants.dardestinationFolder + GTConstants.darfileName, "Photo;" + newFile + ".jpg"
                                + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                        true);

                if (GTConstants.srpfileName.length() > 1)
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.srpfileName,
                            "Photo;" + newFile + ".jpg" + ";" + Utility.getLocalTime() + ";"
                                    + Utility.getLocalDate() + "\r\n",
                            true);

            }
            send_media_via_email("photo");
        }

        if (requestCode == ACTION_TAKE_VIDEO) {
            //add event to dar
            if (GTConstants.sendData) {
                Utility.write_to_file(HomeScreen.this,
                        GTConstants.dardestinationFolder + GTConstants.darfileName, "Video;" + newFile + ".mpeg"
                                + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                        true);

                if (GTConstants.srpfileName.length() > 1)
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.srpfileName,
                            "Video;" + newFile + ".mpeg" + ";" + Utility.getLocalTime() + ";"
                                    + Utility.getLocalDate() + "\r\n",
                            true);

            }
            send_media_via_email("video");
        }

        //end cancel section

        /*  Allowing fore tagging of media files removed 7/1/14 - B. Hall
        //after taking audio, camera or video this routine fires.  file_name is a common variable file name that is assigned when an audio, camera or video is taken
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Tag");
        dialog.setMessage("Add a tag?");
        final EditText input = new EditText(this);
        dialog.setView(input);
                
        dialog.setPositiveButton("OK",new DialogInterface.OnClickListener() 
        {
           @Override
           public void onClick(DialogInterface dialog,int which) 
           {
              String tagText = input.getText().toString().trim();
                      
              //rename the file
              File currentFile = new File(file_name);
              String path = GTConstants.sendfileFolder;
                      
              String oldFile = currentFile.getName();
              String newFile = oldFile.substring(0, oldFile.lastIndexOf('.')) + "_" + tagText + "_";
                      
              if (requestCode == CAMERA_PIC_REQUEST) 
                 { 
                 //rename the file to include tag
                 newFile = newFile + ".jpg";
                 file_name = path + newFile;
                         
                 File from = new File(path,oldFile);
                 File to = new File(path,newFile);
                 from.renameTo(to);
                         
                 //now upload the file to the ftp server
          //new Upload_FTP().execute(file_name);
          Utility.setUploadAvailable();
                  
          //email option
          send_media_via_email("photo");
                  
          //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
         sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
                 
          //Toast.makeText(HomeScreen.this, "Picture saved", Toast.LENGTH_LONG).show();
                 }  
                         
                 if (requestCode == ACTION_TAKE_VIDEO) 
                 {
          newFile = newFile + ".mpeg";
                 file_name = path + newFile;
                         
                 File from = new File(path,oldFile);
                 File to = new File(path,newFile);
                 from.renameTo(to);
          //new Upload_FTP().execute(file_name);
                         
                 Utility.setUploadAvailable();
                  
          //email option
          send_media_via_email("video");
                  
          //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
         sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                 
          //Toast.makeText(HomeScreen.this, "Video saved", Toast.LENGTH_LONG).show();
                 }
                         
                 if (requestCode == REQUEST_CODE_RECORD) 
                 {
          newFile = newFile + ".3ga";
                 file_name = path + newFile;
                         
                 File from = new File(path,oldFile);
                 File to = new File(path,newFile);
                 from.renameTo(to);
          //new Upload_FTP().execute(file_name);
                 Utility.setUploadAvailable();
                  
          //email option
          send_media_via_email("audio");
                  
          //Toast.makeText(HomeScreen.this, "Audio saved", Toast.LENGTH_LONG).show();
                 }
                         
               //copy file to /GT/r directory so that local user can view the image
             copyFile(GTConstants.sendfileFolder, newFile, GTConstants.receivefileFolder);
                     
             //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
             sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
           }
        });
                
        //if no tag is added then leave the filename alone, it was set during initial save (although issue still exists with audio filename!!!).
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
        {
             public void onClick(DialogInterface dialog, int which) 
             {
                //copy file to /GT/r directory so that local user can view the image
                File file = new File(file_name);
              copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder);
                      
              //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
              sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
                      
                //new Upload_FTP().execute(file_name);
              Utility.setUploadAvailable();
                        
                //email option
                if (requestCode == REQUEST_CODE_RECORD)send_media_via_email("audio");
                if (requestCode == CAMERA_PIC_REQUEST) send_media_via_email("photo");
                if (requestCode == ACTION_TAKE_VIDEO)  send_media_via_email("video"); 
             } 
         });
        dialog.show();
        */
    }

}

From source file:com.codename1.impl.android.AndroidImplementation.java

private void scanMedia(File file) {
    Uri uri = Uri.fromFile(file);//from  w  ww  . j av a 2 s  . co m
    Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
    getActivity().sendBroadcast(scanFileIntent);
}