Java Code Examples for android.media.MediaScannerConnection#scanFile()

The following examples show how to use android.media.MediaScannerConnection#scanFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SingleMediaScanner.java    From cordova-rtmp-rtsp-stream with Apache License 2.0 8 votes vote down vote up
@Override
public void onScanCompleted(String path, Uri uri) {
    Log.i("SingleMediaScanner", path);
    Log.i("SingleMediaScanner", uri.getPath());

    mMs.disconnect();

    MediaScannerConnection.scanFile(mContext, new String[] { mFile.getAbsolutePath() }, new String[] { "video/*" }, null);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(Uri.fromFile(mFile));
        mContext.sendBroadcast(mediaScanIntent);
    }
    else
    {
        mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(mFile.getAbsolutePath())));
    }
}
 
Example 2
Source File: SaveAttachmentTask.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private @Nullable String saveAttachment(Context context, Attachment attachment)
    throws NoExternalStorageException, IOException
{
  String      contentType = MediaUtil.getCorrectedMimeType(attachment.contentType);
  String         fileName = attachment.fileName;

  if (fileName == null) fileName = generateOutputFileName(contentType, attachment.date);
  fileName = sanitizeOutputFileName(fileName);

  File    outputDirectory = createOutputDirectoryFromContentType(contentType);
  File          mediaFile = createOutputFile(outputDirectory, fileName);
  InputStream inputStream = PartAuthority.getAttachmentStream(context, attachment.uri);

  if (inputStream == null) {
    return null;
  }

  OutputStream outputStream = new FileOutputStream(mediaFile);
  Util.copy(inputStream, outputStream);

  MediaScannerConnection.scanFile(context, new String[]{mediaFile.getAbsolutePath()},
                                  new String[]{contentType}, null);

  return outputDirectory.getName();
}
 
Example 3
Source File: RecorderService.java    From screenrecorder with GNU Affero General Public License v3.0 6 votes vote down vote up
private void indexFile() {
    //Create a new ArrayList and add the newly created video file path to it
    ArrayList<String> toBeScanned = new ArrayList<>();
    toBeScanned.add(SAVEPATH);
    String[] toBeScannedStr = new String[toBeScanned.size()];
    toBeScannedStr = toBeScanned.toArray(toBeScannedStr);

    //Request MediaScannerConnection to scan the new file and index it
    MediaScannerConnection.scanFile(this, toBeScannedStr, null, new MediaScannerConnection.OnScanCompletedListener() {

        @Override
        public void onScanCompleted(String path, Uri uri) {
            Log.i(Const.TAG, "SCAN COMPLETED: " + path);
            //Show toast on main thread
            Message message = mHandler.obtainMessage();
            message.sendToTarget();
            stopSelf();
        }
    });
}
 
Example 4
Source File: QRGeneratorUtils.java    From privacy-friendly-qr-scanner with GNU General Public License v3.0 6 votes vote down vote up
public static void saveImageToExternalStorage(Context context, Bitmap finalBitmap) {
    File externalPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File myDir = new File(externalPath, "Generated QR-Codes");
    myDir.mkdirs();

    File file = writeToFile(myDir, finalBitmap);

    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(context, new String[] { file.toString() }, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
}
 
Example 5
Source File: CameraActivity.java    From AndroidProject with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_REQUEST_CODE) {
        switch (resultCode) {
            case RESULT_OK:
                // 重新扫描多媒体(否则可能扫描不到)
                MediaScannerConnection.scanFile(getApplicationContext(), new String[]{mFile.getPath()}, null,null);
                break;
            case RESULT_CANCELED:
                // 删除这个文件
                mFile.delete();
                break;
            default:
                break;
        }
        setResult(resultCode);
        finish();
    }
}
 
Example 6
Source File: Path.java    From SMP with GNU General Public License v3.0 6 votes vote down vote up
private static void scanMediaFiles(Context context, Collection<File> filesToScan) {
    String[] filesToScanArray = new String[filesToScan.size()];
    int i = 0;
    for (File file : filesToScan) {
        filesToScanArray[i] = file.getAbsolutePath();
        //if (filesToScanArray[i].contains("emulated/0"))
            Log.d("Settings", "fileToScan: " + filesToScanArray[i]);
        i++;
    }

    if (filesToScanArray.length != 0) {
        MediaScannerConnection.scanFile(context, filesToScanArray, null, null);
    } else {
        Log.e("Settings", "Media scan requested when nothing to scan");
    }
}
 
Example 7
Source File: FoldersFragment.java    From VinylMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
private void scanPaths(@Nullable String[] toBeScanned) {
    if (getActivity() == null) return;
    if (toBeScanned == null || toBeScanned.length < 1) {
        Toast.makeText(getActivity(), R.string.nothing_to_scan, Toast.LENGTH_SHORT).show();
    } else {
        MediaScannerConnection.scanFile(getActivity().getApplicationContext(), toBeScanned, null, new UpdateToastMediaScannerCompletionListener(getActivity(), toBeScanned));
    }
}
 
Example 8
Source File: ContextUtils.java    From memetastic with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Request the givens paths to be scanned by MediaScanner
 *
 * @param files Files and folders to scan
 */
public void mediaScannerScanFile(final File... files) {
    if (android.os.Build.VERSION.SDK_INT > 19) {
        String[] paths = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            paths[i] = files[i].getAbsolutePath();
        }
        MediaScannerConnection.scanFile(_context, paths, null, null);
    } else {
        for (File file : files) {
            _context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        }
    }
}
 
Example 9
Source File: FoldersFragment.java    From Orin with GNU General Public License v3.0 5 votes vote down vote up
private void scanPaths(@Nullable String[] toBeScanned) {
    if (getActivity() == null) return;
    if (toBeScanned == null || toBeScanned.length < 1) {
        Toast.makeText(getActivity(), R.string.nothing_to_scan, Toast.LENGTH_SHORT).show();
    } else {
        MediaScannerConnection.scanFile(getActivity().getApplicationContext(), toBeScanned, null, new UpdateToastMediaScannerCompletionListener(getActivity(), toBeScanned));
    }
}
 
Example 10
Source File: CaptureManager.java    From ViewCapture with Apache License 2.0 5 votes vote down vote up
private void saveBitmap(File directoryFile) {
    File imageFile = new File(directoryFile, getFileName());
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(imageFile))) {
        if (fileNameSuffix.contains("png")) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        } else {
            bitmap.compress(Bitmap.CompressFormat.JPEG, jpgQuality, out);
        }
    } catch (Exception e) {
        Log.e(TAG, "save bitmap error :" + e);
    } finally {
        MediaScannerConnection.scanFile(context, new String[]{imageFile.toString()}, null, this);
    }
}
 
Example 11
Source File: Utility.java    From iBeebo with GNU General Public License v3.0 5 votes vote down vote up
public static void forceRefreshSystemAlbum(String path) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    String type = options.outMimeType;

    MediaScannerConnection.scanFile(BeeboApplication.getInstance(), new String[]{
            path
    }, new String[]{
            type
    }, null);

}
 
Example 12
Source File: DeleteTask.java    From FileManager with Apache License 2.0 5 votes vote down vote up
@Override
protected List<String> doInBackground(String... files) {
    final Activity activity = this.activity.get();
    final List<String> failed = new ArrayList<>();

    for (String str : files) {
        FileUtil.deleteTarget(str);
        SqlUtil.delete(str);
    }

    MediaScannerConnection.scanFile(activity, files, null, null);
    return failed;
}
 
Example 13
Source File: FileUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
public static void updateMediaStore(Context context, String... pathsArray){
    MediaScannerConnection.scanFile(context, pathsArray, null, new MediaScannerConnection.OnScanCompletedListener() {
        @Override
        public void onScanCompleted(String s, Uri uri) {
            //Log.i("Scanner", "Scanned " + s + ":");
            //Log.i("Scanner", "-> uri=" + uri);
        }
    });
}
 
Example 14
Source File: ExtraUtil.java    From NanoIconPack with Apache License 2.0 5 votes vote down vote up
/**
 * 记录新增图片文件到媒体库,这样可迅速在系统图库看到
 *
 * @param context
 * @param newlyPicFile
 * @return
 */
private static boolean record2Gallery(Context context, File newlyPicFile, boolean allInDir) {
    if (context == null || newlyPicFile == null || !newlyPicFile.exists()) {
        return false;
    }

    Log.d(C.LOG_TAG, "record2Gallery(): " + newlyPicFile + ", " + allInDir);

    if (C.SDK >= 19) {
        String[] filePaths;
        if (allInDir) {
            filePaths = newlyPicFile.getParentFile().list();
        } else {
            filePaths = new String[]{newlyPicFile.getPath()};
        }
        MediaScannerConnection.scanFile(context, filePaths, null, null);
    } else {
        if (allInDir) {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.fromFile(newlyPicFile.getParentFile())));
        } else {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(newlyPicFile)));
        }
    }

    return true;
}
 
Example 15
Source File: StoryFragment.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
private void saveImage(Bitmap bitmap) {
    File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + GlobalConstant.APP_NAME);
    if (!file.exists())
        file.mkdirs();

    String fileName = GlobalConstant.DOWNLOADED_FILENAME + System.currentTimeMillis() + ".jpg";

    File newImage = new File(file, fileName);
    if (newImage.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(newImage);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();


        Downloads downloads = new Downloads();
        downloads.setUser_id("");
        downloads.setPath(file.getAbsolutePath() + "/" + fileName);
        downloads.setUsername("");
        downloads.setType(0);
        downloads.setFilename(fileName);
        dataObjectRepositry.addDownloadedData(downloads);

        Toast.makeText(getActivity(), "Saving image...", Toast.LENGTH_SHORT).show();

        if (Build.VERSION.SDK_INT >= 19) {
            MediaScannerConnection.scanFile(getActivity(), new String[]{newImage.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                }
            });
        } else {
            getActivity().sendBroadcast(new Intent("android.intent.action.MEDIA_MOUNTED", Uri.fromFile(newImage)));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: AbsTagEditorActivity.java    From Phonograph with GNU General Public License v3.0 4 votes vote down vote up
private void scan(String[] toBeScanned) {
    Context context = getContext();
    MediaScannerConnection.scanFile(applicationContext, toBeScanned, null, context instanceof Activity ? new UpdateToastMediaScannerCompletionListener((Activity) context, toBeScanned) : null);
}
 
Example 17
Source File: AbsTagEditorActivity.java    From Orin with GNU General Public License v3.0 4 votes vote down vote up
private void scan(String[] toBeScanned) {
    Context context = getContext();
    MediaScannerConnection.scanFile(applicationContext, toBeScanned, null, context instanceof Activity ? new UpdateToastMediaScannerCompletionListener((Activity) context, toBeScanned) : null);
}
 
Example 18
Source File: Utils.java    From android-open-project-demo with Apache License 2.0 4 votes vote down vote up
public static void scanMediaJpegFile(final Context context, final File file,
        final OnScanCompletedListener listener) {
    MediaScannerConnection
            .scanFile(context, new String[]{file.getAbsolutePath()}, new String[]{"image/jpg"},
                    listener);
}
 
Example 19
Source File: RecordingSession.java    From Telecine with Apache License 2.0 4 votes vote down vote up
private void stopRecording() {
  Timber.d("Stopping screen recording...");

  if (!running) {
    throw new IllegalStateException("Not running.");
  }
  running = false;

  hideOverlay();

  boolean propagate = false;
  try {
    // Stop the projection in order to flush everything to the recorder.
    projection.stop();
    // Stop the recorder which writes the contents to the file.
    recorder.stop();

    propagate = true;
  } finally {
    try {
      // Ensure the listener can tear down its resources regardless if stopping crashes.
      listener.onStop();
    } catch (RuntimeException e) {
      if (propagate) {
        //noinspection ThrowFromFinallyBlock
        throw e; // Only allow listener exceptions to propagate if stopped successfully.
      }
    }
  }

  long recordingStopNanos = System.nanoTime();

  recorder.release();
  display.release();

  analytics.send(new HitBuilders.EventBuilder() //
      .setCategory(Analytics.CATEGORY_RECORDING)
      .setAction(Analytics.ACTION_RECORDING_STOP)
      .build());
  analytics.send(new HitBuilders.TimingBuilder() //
      .setCategory(Analytics.CATEGORY_RECORDING)
      .setValue(TimeUnit.NANOSECONDS.toMillis(recordingStopNanos - recordingStartNanos))
      .setVariable(Analytics.VARIABLE_RECORDING_LENGTH)
      .build());

  Timber.d("Screen recording stopped. Notifying media scanner of new video.");

  MediaScannerConnection.scanFile(context, new String[] { outputFile }, null,
      new MediaScannerConnection.OnScanCompletedListener() {
        @Override public void onScanCompleted(String path, final Uri uri) {
          if (uri == null) throw new NullPointerException("uri == null");
          Timber.d("Media scanner completed.");
          mainThread.post(new Runnable() {
            @Override public void run() {
              showNotification(uri, null);
            }
          });
        }
      });
}
 
Example 20
Source File: EventProcessor.java    From syncthing-android with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Performs the actual event handling.
 */
@Override
public void onEvent(Event event) {
    switch (event.type) {
        case "ConfigSaved":
            if (mApi != null) {
                Log.v(TAG, "Forwarding ConfigSaved event to RestApi to get the updated config.");
                mApi.reloadConfig();
            }
            break;
        case "DeviceRejected":
            onDeviceRejected(
                (String) event.data.get("device"),          // deviceId
                (String) event.data.get("name")             // deviceName
            );
            break;
        case "FolderCompletion":
            CompletionInfo completionInfo = new CompletionInfo();
            completionInfo.completion = (Double) event.data.get("completion");
            mApi.setCompletionInfo(
                (String) event.data.get("device"),          // deviceId
                (String) event.data.get("folder"),          // folderId
                completionInfo
            );
            break;
        case "FolderRejected":
            onFolderRejected(
                (String) event.data.get("device"),          // deviceId
                (String) event.data.get("folder"),          // folderId
                (String) event.data.get("folderLabel")      // folderLabel
            );
            break;
        case "ItemFinished":
            String folder = (String) event.data.get("folder");
            String folderPath = null;
            for (Folder f : mApi.getFolders()) {
                if (f.id.equals(folder)) {
                    folderPath = f.path;
                }
            }
            File updatedFile = new File(folderPath, (String) event.data.get("item"));
            if (!"delete".equals(event.data.get("action"))) {
                Log.i(TAG, "Rescanned file via MediaScanner: " + updatedFile.toString());
                MediaScannerConnection.scanFile(mContext, new String[]{updatedFile.getPath()},
                        null, null);
            } else {
                // https://stackoverflow.com/a/29881556/1837158
                Log.i(TAG, "Deleted file from MediaStore: " + updatedFile.toString());
                Uri contentUri = MediaStore.Files.getContentUri("external");
                ContentResolver resolver = mContext.getContentResolver();
                resolver.delete(contentUri, MediaStore.Images.ImageColumns.DATA + " LIKE ?",
                        new String[]{updatedFile.getPath()});
            }
            break;
        case "Ping":
            // Ignored.
            break;
        case "DeviceConnected":
        case "DeviceDisconnected":
        case "DeviceDiscovered":
        case "DownloadProgress":
        case "FolderPaused":
        case "FolderScanProgress":
        case "FolderSummary":
        case "ItemStarted":
        case "LocalIndexUpdated":
        case "LoginAttempt":
        case "RemoteDownloadProgress":
        case "RemoteIndexUpdated":
        case "Starting":
        case "StartupComplete":
        case "StateChanged":
            if (BuildConfig.DEBUG) {
                Log.v(TAG, "Ignored event " + event.type + ", data " + event.data);
            }
            break;
        default:
            Log.v(TAG, "Unhandled event " + event.type);
    }
}