List of usage examples for android.media MediaScannerConnection scanFile
public static void scanFile(Context context, String[] paths, String[] mimeTypes, OnScanCompletedListener callback)
From source file:ooo.oxo.mr.ViewerActivity.java
private void notifyMediaScanning(File file) { MediaScannerConnection.scanFile(getApplicationContext(), new String[] { file.getPath() }, null, null); }
From source file:com.pixby.texo.MainActivity.java
private void onFileSaved(String filePath, int outputDestination) { String msg = String.format("File saved: %s", filePath); showToast(msg);/*from w ww.java 2 s .c o m*/ Log.d(TAG, msg); MediaScannerConnection.OnScanCompletedListener scanListener = null; // if this is a share operation add post-scan listener to kick off share // listener is optional, not needed for export if (outputDestination == SaveImageService.INTENT_SHARE) { scanListener = mfileScanListener; mShareImagePath = filePath; } MediaScannerConnection.scanFile(this, new String[] { filePath }, null, scanListener); }
From source file:com.kii.cloud.sync.DownloadManager.java
/** * Download KiiFile.// ww w . j a v a 2 s .c om * * @param destFile * - specifiy where the downloaded file is saved. * @param srcFile * - KiiFile to be downloaded * @param overwrite * - specifiy if overwrite the destination file. * @throws IOException */ private void downloadKiiFile(File destFile, KiiFile srcFile, boolean overwrite) throws IOException { boolean result = true; InputStream input = null; FileOutputStream fos = null; BufferedOutputStream bos = null; File tempDest = null; try { // check for valid URL String remotePath = srcFile.getRemotePath(); if (remotePath == null) { Log.e(TAG, "remotePath is empty"); throw new IllegalArgumentException("HTTP download URL is empty"); } Log.d(TAG, "downloadKiiFile, remotePath is " + remotePath); // check if the destinated file exist // if yes, check if overwrite permitted if (destFile.exists()) { if (!overwrite) { throw new IllegalArgumentException("File already exist:" + destFile.getAbsolutePath()); } } // check if the destinated folder exist // if not, create the folder File destFolder = destFile.getParentFile(); if (destFolder == null) { throw new IllegalArgumentException("Cannot create folder for file: " + destFile); } if (!destFolder.exists()) { destFolder.mkdirs(); } // send notification that download in progress if (mContext != null) { Intent intent = new Intent(); intent.setAction(ACTION_DOWNLOAD_START); intent.putExtra(DOWNLOAD_DEST_PATH, destFile.getAbsolutePath()); mContext.sendBroadcast(intent); Intent progressIntent = new Intent(mContext.getApplicationContext(), ProgressListActivity.class); NotificationUtil.showDownloadProgressNotification(mContext.getApplicationContext(), progressIntent, destFile.getAbsolutePath()); } // create a temp file for download the file tempDest = new File(destFile.getAbsoluteFile() + "." + Long.toString(System.currentTimeMillis())); HttpGet httpGet = new HttpGet(remotePath); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != 200) { throw new IOException( "Code: " + statusLine.getStatusCode() + "; Reason:" + statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); if (entity == null) { throw new IOException("Cannot read file content."); } input = entity.getContent(); fos = new FileOutputStream(tempDest); bos = new BufferedOutputStream(fos); int len = -1; byte[] buffer = new byte[1024]; // download the file by batch while ((len = input.read(buffer)) > 0) { bos.write(buffer, 0, len); downloadCurrentSize += len; } // delete the existing if it exist if (destFile.exists()) { destFile.delete(); } if (tempDest.exists()) { Log.d(TAG, "Download file: s=" + tempDest.length() + "; d=" + tempDest.lastModified()); // rename the download file to it original file if (!tempDest.renameTo(destFile)) { throw new IllegalArgumentException("Failed to rename:" + tempDest.getAbsolutePath()); } // TODO: the download is success, update the kiifile status; // after rename, create a new file handler tempDest = new File(destFile.getAbsolutePath()); // check if the file exists if (tempDest.exists()) { if (tempDest.setLastModified(srcFile.getUpdateTime()) == false) { // on some Galaxy phones, it will fail, we simply ignore // this error and print an error log Log.e(TAG, "Failed to restore:" + tempDest.getAbsolutePath()); } } else { throw new IllegalArgumentException( "Failed to restore, file not exist after rename:" + tempDest.getAbsolutePath()); } } else { throw new IllegalArgumentException( "Failed to restore, file not exist after dnload:" + tempDest.getAbsolutePath()); } } catch (IllegalArgumentException ex) { if (mContext != null) { Intent intent = new Intent(); intent.setAction(ACTION_DOWNLOAD_START); intent.putExtra(DOWNLOAD_DEST_PATH, destFile.getAbsolutePath()); mContext.sendBroadcast(intent); Intent progressIntent = new Intent(mContext.getApplicationContext(), ProgressListActivity.class); NotificationUtil.showDownloadProgressNotification(mContext.getApplicationContext(), progressIntent, ex.getMessage()); result = false; } throw new IOException("IllegalArgumentException:" + ex.getMessage()); } finally { Utils.closeSilently(bos); Utils.closeSilently(fos); Utils.closeSilently(input); if (mContext != null) { Intent intent = new Intent(); intent.setAction(ACTION_DOWNLOAD_END); intent.putExtra(DOWNLOAD_DEST_PATH, destFile.getAbsolutePath()); intent.putExtra(DOWNLOAD_RESULT, result); mContext.sendBroadcast(intent); // cancel the notification if no error if (result) { NotificationUtil.cancelDownloadProgressNotification(mContext); } else { // delete the temp file if error exist if ((tempDest != null) && tempDest.exists()) { tempDest.delete(); } } KiiSyncClient.getInstance(mContext).notifyKiiFileLocalChange(); // force the system to run a media scan MediaScannerConnection.scanFile(mContext, new String[] { destFile.getAbsolutePath() }, null, null); } } }
From source file:com.kanedias.vanilla.audiotag.PluginService.java
/** * Writes changes in tags directly into file and closes activity. * Call this if you're absolutely sure everything is right with file and tag. *//*from w w w .j a v a 2s .co m*/ private void persistThroughFile() { try { AudioFileIO.write(mAudioFile); Toast.makeText(this, R.string.file_written_successfully, Toast.LENGTH_SHORT).show(); // update media database File persisted = mAudioFile.getFile(); MediaScannerConnection.scanFile(this, new String[] { persisted.getAbsolutePath() }, null, null); } catch (CannotWriteException e) { Log.e(LOG_TAG, String.format(getString(R.string.error_audio_file), mAudioFile.getFile().getPath()), e); Toast.makeText(this, String.format(getString(R.string.error_audio_file) + ", %s", mAudioFile.getFile().getPath(), e.getLocalizedMessage()), Toast.LENGTH_LONG).show(); } }
From source file:com.becapps.easydownloader.utils.Utils.java
public static void scanMedia(Context context, final String[] filePath, final String[] mime) { MediaScannerConnection.scanFile(context, filePath, mime, new OnScanCompletedListener() { @Override/*from www .j a v a 2s . co m*/ public void onScanCompleted(String path, Uri uri) { Log.v(DEBUG_TAG, "file " + path + " was scanned seccessfully: " + uri); } }); }
From source file:syncthing.android.service.SyncthingInstance.java
void startMonitor() { acquireSession();//from w w w . ja va 2 s .c o m final SessionController controller = mSession.controller(); controller.init(); mSessionHelper.eventSubscripion = controller.subscribeChanges(new Action1<SessionController.ChangeEvent>() { @Override public void call(SessionController.ChangeEvent changeEvent) { switch (changeEvent.change) { case ONLINE: { break; } case ITEM_FINISHED: { ItemFinished.Data data = (ItemFinished.Data) changeEvent.data; switch (data.action) { case UPDATE: { FolderConfig folder = controller.getFolder(data.folder); if (folder != null) { File file = new File(folder.path, data.item); Timber.d("Item finished update for %s", file.getAbsolutePath()); if (file.exists()) { MediaScannerConnection.scanFile(SyncthingInstance.this, new String[] { file.getAbsolutePath() }, null, null); } } break; } case DELETE: { FolderConfig folder = controller.getFolder(data.folder); if (folder != null) { File file = new File(folder.path, data.item); Timber.d("Item finished delete for %s", file.getAbsolutePath()); if (!file.exists()) { final String where = MediaStore.Files.FileColumns.DATA + "=?"; int count = getContentResolver().delete(MediaStore.Files.getContentUri("external"), where, new String[] { file.getAbsolutePath() }); Timber.i("Removed %d items from mediastore for path %s", count, file.getAbsolutePath()); } } break; } } break; } } } }, SessionController.Change.ONLINE, SessionController.Change.ITEM_FINISHED); }
From source file:com.android.mail.browse.AttachmentActionHandler.java
private File performAttachmentSave(final Attachment attachment) { try {//from w ww.j a v a2s . c o m File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); downloads.mkdirs(); File file = createUniqueFile(downloads, attachment.getName()); Uri contentUri = attachment.contentUri; InputStream in = mContext.getContentResolver().openInputStream(contentUri); OutputStream out = new FileOutputStream(file); int size = IOUtils.copy(in, out); out.flush(); out.close(); in.close(); String absolutePath = file.getAbsolutePath(); MediaScannerConnection.scanFile(mContext, new String[] { absolutePath }, null, null); DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); dm.addCompletedDownload(attachment.getName(), attachment.getName(), false /* do not use media scanner */, attachment.getContentType(), absolutePath, size, true /* show notification */); Toast.makeText(mContext, mContext.getResources().getString(R.string.save_to) + absolutePath, Toast.LENGTH_SHORT).show(); return file; } catch (IOException ioe) { // Ignore. Callers will handle it from the return code. } return null; }
From source file:de.qspool.clementineremote.backend.ClementineSongDownloader.java
/** * Start the Downlaod// ww w .j ava 2s.c om */ private DownloaderResult startDownloading(ClementineMessage clementineMessage) { boolean downloadFinished = false; DownloaderResult result = new DownloaderResult(DownloadResult.SUCCESSFUL); File f = null; FileOutputStream fo = null; // Do we have a playlist? mIsPlaylist = (clementineMessage.getMessage().getRequestDownloadSongs() .getDownloadItem() == DownloadItem.APlaylist); if (mIsPlaylist) { int id = clementineMessage.getMessage().getRequestDownloadSongs().getPlaylistId(); mPlaylistName = App.mClementine.getPlaylistManager().getPlaylist(id).getName(); } publishProgress(0); // Now request the songs mClient.sendRequest(clementineMessage); while (!downloadFinished) { // Check if the user canceled the process if (isCancelled()) { // Close the stream and delete the incomplete file try { if (fo != null) { fo.flush(); fo.close(); } if (f != null) { f.delete(); } } catch (IOException e) { } break; } // Get the raw protocol buffer ClementineMessage message = mClient.getProtoc(); // Check if an error occured if (message == null || message.isErrorMessage()) { result = new DownloaderResult(DownloadResult.CONNECTION_ERROR); break; } // Is the download forbidden? if (message.getMessageType() == MsgType.DISCONNECT) { result = new DownloaderResult(DownloadResult.FOBIDDEN); break; } // Download finished? if (message.getMessageType() == MsgType.DOWNLOAD_QUEUE_EMPTY) { break; } // Ignore other elements! if (message.getMessageType() != MsgType.SONG_FILE_CHUNK) { continue; } ResponseSongFileChunk chunk = message.getMessage().getResponseSongFileChunk(); // If we received chunk no 0, then we have to decide wether to // accept the song offered or not if (chunk.getChunkNumber() == 0) { processSongOffer(chunk); // Update progress here to. If the first (and only) file exists and shall not be // overriten, the notification bar shows NULL. mCurrentSong = MySong.fromProtocolBuffer(chunk.getSongMetadata()); publishProgress(mCurrentProgress); continue; } try { // Check if we need to create a new file if (f == null) { // Check if we have enougth free space if (chunk.getSize() > Utilities.getFreeSpaceExternal()) { result = new DownloaderResult(DownloadResult.INSUFFIANT_SPACE); break; } File dir = new File(BuildDirPath(chunk)); f = new File(BuildFilePath(chunk)); // User wants to override files, so delete it here! // The check was already done in processSongOffer() if (f.exists()) { f.delete(); } dir.mkdirs(); f.createNewFile(); fo = new FileOutputStream(f); // File for download fragment mFileUri = Uri.fromFile(f); } // Write chunk to sdcard fo.write(chunk.getData().toByteArray()); // Have we downloaded all chunks? if (chunk.getChunkCount() == chunk.getChunkNumber()) { // Index file MediaScannerConnection.scanFile(mContext, new String[] { f.getAbsolutePath() }, null, null); fo.flush(); fo.close(); f = null; } // Update notification updateProgress(chunk); } catch (IOException e) { result = new DownloaderResult(DownloaderResult.DownloadResult.NOT_MOUNTED); break; } } // Disconnect at the end mClient.disconnect(ClementineMessage.getMessage(MsgType.DISCONNECT)); return result; }
From source file:com.nextgis.mobile.InputPointActivity.java
public void onFinish() { if (descriptfrag != null) descriptfrag.onStoreValues();/*w w w .jav a 2s .com*/ if (positionfrag != null) positionfrag.onStoreValues(); if (camfrag != null) camfrag.onStoreValues(); if (notefrag != null) notefrag.onStoreValues(); //add point to the file File file = new File(getExternalFilesDir(null), "points.csv"); boolean bExist = file.exists(); try { FileOutputStream os = new FileOutputStream(file, true); PrintWriter pw = new PrintWriter(os); if (!bExist) { pw.println( "date_time;lat;lon;acc;error_est;h;dir;src;speed;gps_t;cat;subcut;az;len;desc;photos;photos_az"); } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final String CE = prefs.getString(PreferencesActivity.KEY_PREF_ACCURATE_CE, "None"); double dfLat = 0, dfLon = 0, dfAcc = 0, dfAlt = 0, dfBearing = 0, dfSpeed = 0; String sProv = ""; long nTime = 0; if (m_CurrentLocation != null) { dfLat = m_CurrentLocation.getLatitude(); dfLon = m_CurrentLocation.getLongitude(); dfAcc = m_CurrentLocation.getAccuracy(); dfAlt = m_CurrentLocation.getAltitude(); dfBearing = m_CurrentLocation.getBearing(); dfSpeed = m_CurrentLocation.getSpeed(); sProv = m_CurrentLocation.getProvider(); nTime = m_CurrentLocation.getTime(); } //filter out unsupported chars m_sCat.replace(CSV_CHAR, "|"); m_sCat.replace("\n", "|"); m_sSubCat.replace(CSV_CHAR, "|"); m_sSubCat.replace("\n", "|"); m_sNote.replace(CSV_CHAR, "|"); m_sNote.replace("\n", "|"); pw.println( java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) + CSV_CHAR + //0 dfLat + CSV_CHAR + //1 dfLon + CSV_CHAR + //2 dfAcc + CSV_CHAR + CE + CSV_CHAR + dfAlt + CSV_CHAR + //4 dfBearing + CSV_CHAR + //5 sProv + CSV_CHAR + //6 dfSpeed + CSV_CHAR + //7 nTime + CSV_CHAR + //8 m_sCat + CSV_CHAR + //9 m_sSubCat + CSV_CHAR + //10 m_fAzimuth + CSV_CHAR + //11 m_fDist + CSV_CHAR + //12 m_sNote + CSV_CHAR + //13 image_lst.toString() + CSV_CHAR + image_rotation.toString()); pw.flush(); pw.close(); os.close(); MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { Log.i("ExternalStorage", "Scanned " + path + ":"); Log.i("ExternalStorage", "-> uri=" + uri); } }); } catch (IOException e) { Log.w("ExternalStorage", "Error writing " + file, e); } //add point to the map Toast.makeText(InputPointActivity.this, R.string.input_poi_added, Toast.LENGTH_SHORT).show(); finish(); }
From source file:com.kanedias.vanilla.audiotag.PluginService.java
/** * Write changes through SAF framework - the only way to do it in Android > 4.4 when working with SD card * @param activityResponse response with URI contained in. Can be null if tree permission is already given. *///from www .jav a 2 s .c o m private void persistThroughSaf(Intent activityResponse) { Uri safUri; if (mPrefs.contains(PREF_SDCARD_URI)) { // no sorcery can allow you to gain URI to the document representing file you've been provided with // you have to find it again using now Document API // /storage/volume/Music/some.mp3 will become [storage, volume, music, some.mp3] List<String> pathSegments = new ArrayList<>( Arrays.asList(mAudioFile.getFile().getAbsolutePath().split("/"))); Uri allowedSdRoot = Uri.parse(mPrefs.getString(PREF_SDCARD_URI, "")); safUri = findInDocumentTree(DocumentFile.fromTreeUri(this, allowedSdRoot), pathSegments); } else { Intent originalSafResponse = activityResponse.getParcelableExtra(EXTRA_PARAM_SAF_P2P); safUri = originalSafResponse.getData(); } if (safUri == null) { // nothing selected or invalid file? Toast.makeText(this, R.string.saf_nothing_selected, Toast.LENGTH_LONG).show(); return; } try { // we don't have fd-related audiotagger write functions, have to use workaround // write audio file to temp cache dir // jaudiotagger can't work through file descriptor, sadly File original = mAudioFile.getFile(); File temp = File.createTempFile("tmp-media", '.' + Utils.getExtension(original)); Utils.copy(original, temp); // jtagger writes only header, we should copy the rest temp.deleteOnExit(); // in case of exception it will be deleted too mAudioFile.setFile(temp); AudioFileIO.write(mAudioFile); // retrieve FD from SAF URI ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(safUri, "rw"); if (pfd == null) { // should not happen Log.e(LOG_TAG, "SAF provided incorrect URI!" + safUri); return; } // now read persisted data and write it to real FD provided by SAF FileInputStream fis = new FileInputStream(temp); byte[] audioContent = TagEditorUtils.readFully(fis); FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor()); fos.write(audioContent); fos.close(); // delete temporary file used temp.delete(); // rescan original file MediaScannerConnection.scanFile(this, new String[] { original.getAbsolutePath() }, null, null); Toast.makeText(this, R.string.file_written_successfully, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this, getString(R.string.saf_write_error) + e.getLocalizedMessage(), Toast.LENGTH_LONG) .show(); Log.e(LOG_TAG, "Failed to write to file descriptor provided by SAF!", e); } }