Java 类android.media.MediaScannerConnection 实例源码

项目:ascii_generate    文件:AndroidUtils.java   
/**
 * Notifies the OS to index the new image, so it shows up in Gallery. Allows optional callback method to notify client when
 * the scan is completed, e.g. so it can access the "content" URI that gets assigned.
 */
public static void scanSavedMediaFile(final Context context, final String path, final MediaScannerCallback callback) {
    // silly array hack so closure can reference scannerConnection[0] before it's created
    final MediaScannerConnection[] scannerConnection = new MediaScannerConnection[1];
    try {
        MediaScannerConnection.MediaScannerConnectionClient scannerClient = new MediaScannerConnection.MediaScannerConnectionClient() {
            public void onMediaScannerConnected() {
                scannerConnection[0].scanFile(path, null);
            }

            public void onScanCompleted(String scanPath, Uri scanURI) {
                scannerConnection[0].disconnect();
                if (callback != null) {
                    callback.mediaScannerCompleted(scanPath, scanURI);
                }
            }
        };
        scannerConnection[0] = new MediaScannerConnection(context, scannerClient);
        scannerConnection[0].connect();
    } catch (Exception ignored) {
    }
}
项目:publicProject    文件:FileUtils.java   
/**
 * 扫描指定文件夹Android4.4中,则会抛出异常MediaScannerConnection.scanFile可以解决
 */
public static void fileScan(Context context) {
    try {
        if (Build.VERSION.SDK_INT < 19) {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                    + Environment.getExternalStorageDirectory())));
        } else {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                    + Environment.getExternalStorageDirectory())));
            MediaScannerConnection.scanFile(context, new String[]{new File(Environment.getExternalStorageDirectory().toString()).getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {

                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:react-native-camera-android-simple    文件:ImageFileUtils.java   
public static void addToGalleryAndNotify(Context context, File imageFile, final Promise promise) {
    final WritableMap response = new WritableNativeMap();
    response.putString("path", Uri.fromFile(imageFile).toString());

    // borrowed from react-native CameraRollManager, it finds and returns the 'internal'
    // representation of the image uri that was just saved.
    // e.g. content://media/external/images/media/123
    MediaScannerConnection.scanFile(
            context,
            new String[]{imageFile.getAbsolutePath()},
            null,
            new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {
                    promise.resolve(response);
                }
            });
}
项目:ceji_android    文件:MusicDownLoadActivity.java   
@Override
public void onFinish(DownloadInfo downloadInfo) {
    //            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(LqBookConst.DOWN_PATH)));
    Log.i(TAG,"onFinish="+downloadInfo.getFileName());
    Toast.makeText(getApplicationContext(), getString(R.string.downLoaded) + downloadInfo.getTargetPath(), Toast.LENGTH_SHORT).show();
    adapter.notifyDataSetChanged();
    /**
     * 重新扫描数据库
     */
    MediaScannerConnection.scanFile(getApplicationContext(),
            new String[]{downloadInfo.getTargetPath()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
}
项目:ceji_android    文件:MediaScannerFile.java   
/**
 * 扫描指定的文件
 *
 * @param context
 * @param filePath
 * @param sListener
 */
public static MediaScannerConnection scanFile(Context context, String[] filePath, String[] mineType,
                                              MediaScannerConnection.OnScanCompletedListener sListener) {

    ClientProxy client = new ClientProxy(filePath, mineType, sListener);

    try {
        MediaScannerConnection connection = new MediaScannerConnection(
                context.getApplicationContext(), client);
        client.mConnection = connection;
        connection.connect();
        return connection;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:LiveNotes    文件:LiveNotesActivity.java   
@SuppressWarnings("ResultOfMethodCallIgnored")
private boolean saveFile(String fileName) {
    try {
        File path = getExternalStoragePublicDirectory(getString(R.string.storage_dir));
        path.mkdir();
        File file = new File(path, fileName);

        FileOutputStream stream = new FileOutputStream(file);
        stream.write(getXML().getBytes());
        stream.flush();
        stream.close();

        MediaScannerConnection.scanFile(this, new String[] {file.toString()}, null, null);

        return true;
    } catch (IOException e) {
        return false;
    }
}
项目:PeSanKita-android    文件:SaveAttachmentTask.java   
private boolean saveAttachment(Context context, MasterSecret masterSecret, Attachment attachment) throws IOException {
  String contentType      = MediaUtil.getCorrectedMimeType(attachment.contentType);
  File mediaFile          = constructOutputFile(contentType, attachment.filename, attachment.date);
  InputStream inputStream = PartAuthority.getAttachmentStream(context, masterSecret, attachment.uri);

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

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

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

  return true;
}
项目:Selector    文件:ImageCacheUtils.java   
public static String saveToSDCard(byte[] data,Context context,String path) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String filename = "IMG_" + format.format(date) + ".jpg";
        File fileFolder = new File(path);
        if (!fileFolder.exists()) {
            fileFolder.mkdirs();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); //
        //刷新相册
        MediaScannerConnection.scanFile(context,
                new String[]{jpgFile.getAbsolutePath()}, null, null);

        outputStream.write(data);
        outputStream.close();
//        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        Uri uri = Uri.fromFile(new File(Environment
//                .getExternalStorageDirectory() + "/DeepbayPicture/" + filename));
//        intent.setData(uri);
//        mContext.sendBroadcast(intent);
        return jpgFile.getAbsolutePath();
    }
项目:Sega    文件:ImagePickerActivity.java   
/**
 * Check if the captured image is stored successfully
 * Then reload data
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Constants.REQUEST_CODE_CAPTURE) {
        if (resultCode == RESULT_OK && currentImagePath != null) {
            Uri imageUri = Uri.parse(currentImagePath);
            if (imageUri != null) {
                MediaScannerConnection.scanFile(this,
                        new String[]{imageUri.getPath()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                Log.v(TAG, "File " + path + " was scanned successfully: " + uri);
                                getDataWithPermission();
                            }
                        });
            }
        }
    }
}
项目:Moment    文件:PictureActivity.java   
private void download() {
    Observable.just(null)
            .compose(bindToLifecycle())
            .compose(ensurePermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            .filter(granted -> {
                if (granted) {
                    return true;
                } else {
                    Toasty.info(this, getString(R.string.permission_required),
                            Toast.LENGTH_LONG).show();
                    return false;
                }
            })
            .flatMap(granted -> ensureDirectory("Moment"))
            .map(file -> new File(file, makeFileName()))
            .flatMap(file -> file.exists()
                    ? Observable.just(file)
                    : save(file))
            .doOnNext(file -> MediaScannerConnection.scanFile(getApplicationContext(),
                    new String[]{file.getPath()}, null, null))
            .subscribe(file -> {
                showTips(getString(R.string.save_path_tips, file.getPath()));
            });
}
项目:xmrwallet    文件:LoginActivity.java   
private boolean backupWallet(String walletName) {
    File backupFolder = new File(getStorageRoot(), "backups");
    if (!backupFolder.exists()) {
        if (!backupFolder.mkdir()) {
            Timber.e("Cannot create backup dir %s", backupFolder.getAbsolutePath());
            return false;
        }
        // make folder visible over USB/MTP
        MediaScannerConnection.scanFile(this, new String[]{backupFolder.toString()}, null, null);
    }
    File walletFile = Helper.getWalletFile(LoginActivity.this, walletName);
    File backupFile = new File(backupFolder, walletName);
    Timber.d("backup " + walletFile.getAbsolutePath() + " to " + backupFile.getAbsolutePath());
    // TODO probably better to copy to a new file and then rename
    // then if something fails we have the old backup at least
    // or just create a new backup every time and keep n old backups
    boolean success = copyWallet(walletFile, backupFile, true, true);
    Timber.d("copyWallet is %s", success);
    return success;
}
项目:Cable-Android    文件:SaveAttachmentTask.java   
private @Nullable File saveAttachment(Context context, MasterSecret masterSecret, 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, masterSecret, 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 mediaFile.getParentFile();
}
项目:MusicX-music-player    文件:TagEditorFragment.java   
@Override
protected void onPostExecute(Boolean b) {
    super.onPostExecute(b);
    if (b) {
        Toast.makeText(context, "Tag Edit Success", Toast.LENGTH_SHORT).show();
        mediaScannerConnection = new MediaScannerConnection(getContext(),
                new MediaScannerConnection.MediaScannerConnectionClient() {

                    public void onScanCompleted(String path, Uri uri) {
                        mediaScannerConnection.disconnect();
                    }

                    public void onMediaScannerConnected() {
                        mediaScannerConnection.scanFile(song.getmSongPath(), "audio/*");
                    }
                });
    } else {
        Toast.makeText(context, "Tag Edit Failed", Toast.LENGTH_SHORT).show();
    }
}
项目:RLibrary    文件:RUtils.java   
/**
     * 扫描文件, 到系统相册/视频文件夹
     */
    public static void scanFile(Context context, String filePath) {
        File file = new File(filePath);
        if (file.exists() && context != null) {
            /*需要android.intent.action.MEDIA_MOUNTED系统权限,但是再Android 4.4系统以后,限制了只有系统应用才有使用广播通知系统扫描的权限,否则会抛出异常信息*/
//            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//            Uri uri = Uri.fromFile(file);
//            intent.setData(uri);
//            context.sendBroadcast(intent);

            MediaScannerConnection.scanFile(context.getApplicationContext(), new String[]{filePath}, null,
                    new MediaScannerConnection.MediaScannerConnectionClient() {
                        @Override
                        public void onMediaScannerConnected() {
                            L.e("call: onMediaScannerConnected([])-> ");
                        }

                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            L.e("call: onScanCompleted([path, uri])-> " + path + " ->" + uri);
                        }
                    });
        }
    }
项目:RLibrary    文件:RUtils.java   
public static void scanVideo(Context context, String videoPath) {
    File file = new File(videoPath);
    if (file.exists() && context != null) {
        MediaScannerConnection.scanFile(context, new String[]{videoPath}, new String[]{"video/mp4"},
                new MediaScannerConnection.MediaScannerConnectionClient() {
                    @Override
                    public void onMediaScannerConnected() {
                        L.e("call: onMediaScannerConnected([])-> ");
                    }

                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        L.e("call: onScanCompleted([path, uri])-> " + path + " ->" + uri);
                    }
                });
    }
}
项目:cloudier    文件:ImagePickerActivity.java   
/**
 * Check if the captured image is stored successfully
 * Then reload data
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Constants.REQUEST_CODE_CAPTURE) {
        if (resultCode == RESULT_OK) {
            if (currentFile != null && currentFile.exists()) {
                MediaScannerConnection.scanFile(this,
                        new String[]{currentFile.getAbsolutePath()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                Log.v("MediaScanWork", "file " + path + " was scanned successfully: " + uri);
                                getDataWithPermission();
                            }
                        });
            }
        }
    }
}
项目:UVCCameraZxing    文件:CameraServer.java   
public void handleUpdateMedia(final String path) {
    if (DEBUG) Log.d(TAG_THREAD, "handleUpdateMedia:path=" + path);
    final Context context = mWeakContext.get();
    if (context != null) {
        try {
            if (DEBUG) Log.i(TAG, "MediaScannerConnection#scanFile");
            MediaScannerConnection.scanFile(context, new String[]{ path }, null, null);
        } catch (final Exception e) {
            Log.e(TAG, "handleUpdateMedia:", e);
        }
    } else {
        Log.w(TAG, "MainActivity already destroyed");
        // give up to add this movice to MediaStore now.
        // Seeing this movie on Gallery app etc. will take a lot of time.
        handleRelease();
    }
}
项目:xmpp    文件:MultiImageSelectorActivity.java   
@Override
    public void onCameraShot(File imageFile) {
        if (imageFile != null) {
            onImageSelected(imageFile.getAbsolutePath());
//            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + imageFile)));
            MediaScannerConnection.scanFile(this, new String[]{imageFile.toString()}, null, null);
            int mode = intent.getIntExtra(EXTRA_SELECT_MODE, MODE_MULTI);
            boolean isShow = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, true);
            Bundle bundle = new Bundle();
            bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_COUNT, mDefaultCount);
            bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_MODE, mode);
            bundle.putBoolean(MultiImageSelectorFragment.EXTRA_SHOW_CAMERA, isShow);
            bundle.putStringArrayList(MultiImageSelectorFragment.EXTRA_DEFAULT_SELECTED_LIST, resultList);

            getSupportFragmentManager().beginTransaction()
                    .add(R.id.image_grid, Fragment.instantiate(this, MultiImageSelectorFragment.class.getName(), bundle))
                    .commit();
            //finish();
        }
    }
项目:mimi-reader    文件:GalleryImageBase.java   
private void invokeMediaScanner(File savedFile) {
    if (getActivity() != null) {

        Toast.makeText(getActivity(), R.string.file_saved, Toast.LENGTH_LONG).show();

        final File noMediaFile = new File(MimiUtil.getSaveDir(getActivity()), ".nomedia");
        if (!noMediaFile.exists()) {

            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.MIME_TYPE, Utils.getMimeType(fileExt));
            values.put(MediaStore.Images.Media.DATA, savedFile.getAbsolutePath());
            values.put(MediaStore.Images.Media.DATE_MODIFIED, savedFile.lastModified());

            getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            final String[] dir = {savedFile.getAbsolutePath()};
            MediaScannerConnection.scanFile(getActivity(), dir, null, new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {
                    Log.i(LOG_TAG, "SCAN COMPLETED: path=" + path + ", uri=" + uri);
                }
            });
        }

    }
}
项目:AutoMusicTagFixer    文件:TrackDetailsActivity.java   
@Override
protected Boolean doInBackground(Void... voids) {
    boolean success = false;
    try {
        mPathToFile = FileSaver.saveImageFile(mDataImage, mTitle, mArtist, mAlbum);
        //if was successful saved, then
        //inform to system that one file has been created
        if(mPathToFile != null && !mPathToFile.equals(FileSaver.NULL_DATA)
                && !mPathToFile.equals(FileSaver.NO_EXTERNAL_STORAGE_WRITABLE)
                && !mPathToFile.equals(FileSaver.INPUT_OUTPUT_ERROR)) {
            MediaScannerConnection.scanFile(
                    mTrackDetailsActivityWeakReference.get().getApplicationContext(),
                    new String[]{mPathToFile},
                    new String[]{MimeTypeMap.getFileExtensionFromUrl(mPathToFile)},
                    null);
            success = true;
        }

    } catch (IOException e) {
        Crashlytics.logException(e);
        e.printStackTrace();
        success = false;
    }

    return success;
}
项目:StorageManager    文件:MediaStoreUtil.java   
public static boolean updateAfterChangeBlocking(String[] paths, int timeToWaitToRecheckMediaScanner)
{
    final AtomicInteger counter = new AtomicInteger(0);
    MediaScannerConnection.scanFile(StorageManager.get().getContext(), paths, null,
            new MediaScannerConnection.OnScanCompletedListener()
            {
                public void onScanCompleted(String path, Uri uri)
                {
                    counter.incrementAndGet();
                }
            });

    int count = paths.length;
    while (counter.get() != count) {
        try {
            Thread.sleep(timeToWaitToRecheckMediaScanner);
        } catch (InterruptedException e) {
            return false;
        }
    }

    return true;
}
项目:TAG    文件:RecorderVideoActivity.java   
public void sendVideo(View view) {
    if (TextUtils.isEmpty(localPath)) {
        EMLog.e("Recorder", "recorder fail please try again!");
        return;
    }

    msc = new MediaScannerConnection(this,
            new MediaScannerConnectionClient() {

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    Log.d("log scanner completed");
                    msc.disconnect();
                    setResult(RESULT_OK, getIntent().putExtra("uri", uri));
                    finish();
                }

                @Override
                public void onMediaScannerConnected() {
                    msc.scanFile(localPath, "video/*");
                }
            });
    msc.connect();

}
项目:FunWithAndroid    文件:TakePictureActivity.java   
private void indexPictureInGallery(View view, File picture) {
    Timber.d("Adding taken picture to media collection");
    MediaScannerConnection.scanFile(TakePictureActivity.this, new String[]{picture.getAbsolutePath()}, new String[]{"image/jpg"}, (s, uri) -> {
        Timber.d("Picture %s added to gallery under %s", s, uri);

        Snackbar snackbar = Snackbar.make(view, "" +
                "Picture saved", Snackbar.LENGTH_SHORT);

        Intent viewIntent = new Intent(Intent.ACTION_VIEW);
        viewIntent.setDataAndType(uri, "image/*");

        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(viewIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfos.size() > 0) {
            snackbar.setAction("Show", v -> {
                Timber.d("Opening picture in gallery");
                startActivity(viewIntent);
            });
        }
        snackbar.show();
    });
}
项目:nitroshare-android    文件:TransferManager.java   
/**
 * Create a new transfer manager
 */
TransferManager(Context context, TransferNotificationManager transferNotificationManager) {
    mContext = context;
    mTransferNotificationManager = transferNotificationManager;

    mMediaScannerConnection = new MediaScannerConnection(mContext, new MediaScannerConnection.MediaScannerConnectionClient() {
        @Override
        public void onMediaScannerConnected() {
            Log.i(TAG, "connected to media scanner");
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
        }
    });
}
项目:TrebleShot    文件:CommunicationService.java   
@Override
public void onCreate()
{
    super.onCreate();

    if (!mCommunicationServer.start() || !mSeamlessServer.start())
        stopSelf();

    mNotificationUtils = new NotificationUtils(this);
    mDatabase = new AccessDatabase(this);
    mMediaScanner = new MediaScannerConnection(this, null);
    mHotspotUtils = HotspotUtils.getInstance(this);
    mWifiLock = ((WifiManager) getApplicationContext().getSystemService(Service.WIFI_SERVICE))
            .createWifiLock(TAG);

    mReceive.setNotifyDelay(2000);
    mSend.setNotifyDelay(2000);

    mMediaScanner.connect();

    getWifiLock().acquire();
    updateServiceState(getNotificationUtils().getPreferences().getBoolean("trust_always", false));
}
项目:WireGoggles    文件:AndroidUtils.java   
/** Notifies the OS to index the new image, so it shows up in Gallery. Allows optional callback method to notify client when
   * the scan is completed, e.g. so it can access the "content" URI that gets assigned.
   */
  public static void scanSavedMediaFile(final Context context, final String path, final MediaScannerCallback callback) {
    // silly array hack so closure can reference scannerConnection[0] before it's created 
    final MediaScannerConnection[] scannerConnection = new MediaScannerConnection[1];
try {
    MediaScannerConnection.MediaScannerConnectionClient scannerClient = new MediaScannerConnection.MediaScannerConnectionClient() {
        public void onMediaScannerConnected() {
            scannerConnection[0].scanFile(path, null);
        }

        public void onScanCompleted(String scanPath, Uri scanURI) {
            scannerConnection[0].disconnect();
            if (callback!=null) {
                callback.mediaScannerCompleted(scanPath, scanURI);
            }
        }
    };
        scannerConnection[0] = new MediaScannerConnection(context, scannerClient);
        scannerConnection[0].connect();
}
catch(Exception ignored) {}
  }
项目:vanilla-music-tag-editor    文件: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.
 */
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();
    }
}
项目:screenrecorder    文件:EditVideoActivity.java   
private void indexFile(String SAVEPATH) {
    //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);
            saveprogress.cancel();
            setResult(Const.VIDEO_EDIT_RESULT_CODE);
            finish();
        }
    });
}
项目:screenrecorder    文件:RecorderService.java   
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();
        }
    });
}
项目:mobile-manager-tool    文件:FileManagerActivity.java   
private void refreshMediaResource(){
    // Android 4.4
    if(Build.VERSION.SDK_INT>= 19){
        MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().getAbsolutePath()},
                null, new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {


                    }
                }
        );
    }else{
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        intentFilter.addDataScheme("file");
        scanReceiver = new ScanSdFilesReceiver();
        registerReceiver(scanReceiver, intentFilter);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
    }
}
项目:odyssey    文件:MediaScannerService.java   
/**
 * Proceeds to the next bunch of files to scan if any available.
 *
 * @param context Context used for scanning.
 */
private void scanNextBunch(final Context context) {
    if (mRemainingFiles.isEmpty() || mAbort) {
        // No files left to scan, stop service (delayed to allow the ServiceConnection to the MediaScanner to close itself)
        Timer delayedStopTimer = new Timer();
        delayedStopTimer.schedule(new DelayedStopTask(), 100);
        return;
    }

    String[] bunch = new String[Math.min(MEDIASCANNER_BUNCH_SIZE, mRemainingFiles.size())];
    int i = 0;

    ListIterator<FileModel> listIterator = mRemainingFiles.listIterator();
    while (listIterator.hasNext() && i < MEDIASCANNER_BUNCH_SIZE) {
        bunch[i] = listIterator.next().getPath();
        listIterator.remove();
        i++;
    }
    MediaScannerConnection.scanFile(context, bunch, null, new MediaScanCompletedCallback(bunch.length, context));
}
项目:screenshott    文件:ScreenShott.java   
/**
 * Save screenshot to pictures folder.
 *
 * @param context
 *     the context
 * @param image
 *     the image
 * @param filename
 *     the filename
 * @return the bitmap file object
 * @throws Exception
 *     the exception
 */
public File saveScreenshotToPicturesFolder(Context context, Bitmap image, String filename)
    throws Exception {
  File bitmapFile = getOutputMediaFile(filename);
  if (bitmapFile == null) {
    throw new NullPointerException("Error creating media file, check storage permissions!");
  }
  FileOutputStream fos = new FileOutputStream(bitmapFile);
  image.compress(Bitmap.CompressFormat.PNG, 90, fos);
  fos.close();

  // Initiate media scanning to make the image available in gallery apps
  MediaScannerConnection.scanFile(context, new String[] { bitmapFile.getPath() },
      new String[] { "image/jpeg" }, null);
  return bitmapFile;
}
项目:Practice    文件:MovieFragment.java   
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.id_movie_refresh:
            MediaScannerConnection.scanFile(getActivity(), new String[]{Environment
                    .getExternalStorageDirectory().getAbsolutePath()}, null, null);
            if (movieList != null) {
                movieList.clear();
                nameList.clear();
            }
            movieList = MovieUtils.getAllMovies(getActivity());
            for (Movie movie : movieList) {
                nameList.add(movie.getTitle());
            }
            adapterMovie.notifyDataSetChanged();
            break;
        default:
            break;
    }
}
项目:Practice    文件:MovieFragment.java   
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.id_movie_refresh:
            MediaScannerConnection.scanFile(getActivity(), new String[]{Environment
                    .getExternalStorageDirectory().getAbsolutePath()}, null, null);
            if (movieList != null) {
                movieList.clear();
                nameList.clear();
            }
            movieList = MovieUtils.getAllMovies(getActivity());
            for (Movie movie : movieList) {
                nameList.add(movie.getTitle());
            }
            adapterMovie.notifyDataSetChanged();
            break;
        default:
            break;
    }
}
项目:Practice    文件:MovieFragment.java   
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.id_movie_refresh:
            MediaScannerConnection.scanFile(getActivity(), new String[]{Environment
                    .getExternalStorageDirectory().getAbsolutePath()}, null, null);
            if (movieList != null) {
                movieList.clear();
                nameList.clear();
            }
            movieList = MovieUtils.getAllMovies(getActivity());
            for (Movie movie : movieList) {
                nameList.add(movie.getTitle());
            }
            adapterMovie.notifyDataSetChanged();
            break;
        default:
            break;
    }
}
项目:FacerecognitionFlowpilots    文件:CameraFragment.java   
@SuppressWarnings("unused")
public void onEventMainThread(CameraEngine.VideoTakenEvent event) {
  if (getArguments().getBoolean(ARG_UPDATE_MEDIA_STORE, false)) {
    final Context app=getActivity().getApplicationContext();
    Uri output=getArguments().getParcelable(ARG_OUTPUT);
    final String path=output.getPath();

    new Thread() {
      @Override
      public void run() {
        SystemClock.sleep(2000);
        MediaScannerConnection.scanFile(app,
            new String[]{path}, new String[]{"video/mp4"},
            null);
      }
    }.start();
  }

  isVideoRecording=false;
  fabPicture.setImageResource(R.drawable.cwac_cam2_ic_videocam);
  fabPicture.setColorNormalResId(R.color.cwac_cam2_picture_fab);
  fabPicture.setColorPressedResId(R.color.cwac_cam2_picture_fab_pressed);
}
项目:texo    文件:MainActivity.java   
private void onFileSaved(String filePath, int outputDestination) {
    String msg = String.format("File saved: %s", filePath);
    showToast(msg);
    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);
}
项目:InstaImageDownloader    文件:ImageRecyclerAdaptor.java   
public void callBroadCast() {
  if (Build.VERSION.SDK_INT >= 14) {
    Log.e("-->", " >= 14");
    MediaScannerConnection.scanFile(mContext, new String[]{ Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
      /*
       *   (non-Javadoc)
       * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
       */
      public void onScanCompleted(String path, Uri uri) {
        Log.e("ExternalStorage", "Scanned " + path + ":");
        Log.e("ExternalStorage", "-> uri=" + uri);
      }
    });
  } else {
    Log.e("-->", " < 14");
    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
        Uri.parse("file://" + Environment.getExternalStorageDirectory())));
  }
}
项目:open-mygirl-android-gradle    文件:MainImageActivity.java   
private void connectMediaScan(final String filename) {
    msc = new MediaScannerConnection(this, new MediaScannerConnectionClient() {

        @Override
        public void onScanCompleted(String path, Uri uri) {
            savedUri = uri;
            msc.disconnect();
            if (isNeedShare) {
                KakaoShare.shareImageKakao(MainImageActivity.this, uri);
            }
            isNeedShare = false;
        }

        @Override
        public void onMediaScannerConnected() {
            msc.scanFile(filename, "image/png");
        }
    });
    msc.connect();
}
项目:In-Time-Android-Native-App-    文件:MainActivity.java   
@Override
protected void onDestroy() {
    //UNREGISTER RECEIVERS
    LocalBroadcastManager.getInstance(this).unregisterReceiver(delayStartReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(informStatusReceiver);        
    Log.d(LOG_TAG, "DESTROY HERE");             
    if(isWorkerStarted){
        mediaRecorder.stop();
        releaseMediaRecorder();
        releaseCamera(); 
        saveCurrentTimelap();
        MediaScannerConnection.scanFile(InTimeApp.getInstance().getApplicationContext(), new String[] { currentVideoPath }, new String[] { null }, null);
    }else{
        releaseCamera();
    }
    isWorkerStarted = false;        
    super.onDestroy();
}