Example #1
0
  public void startScan() {
    if (conn != null) {
      conn.disconnect();
    }

    conn = new MediaScannerConnection(context, this);
    conn.connect();
  }
Example #2
0
 @Override
 public void onMediaScannerConnected() {
   for (String filename : toScan) {
     conn.scanFile(filename, null);
   }
   toScan.clear();
 }
Example #3
0
    private void saveImage(final String folderName, final String fileName, final Bitmap image) {
      File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
      File file = new File(path, folderName + "/" + fileName);
      try {
        file.getParentFile().mkdirs();
        image.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
        MediaScannerConnection.scanFile(
            mContext,
            new String[] {file.toString()},
            null,
            new MediaScannerConnection.OnScanCompletedListener() {
              @Override
              public void onScanCompleted(final String path, final Uri uri) {
                if (mListener != null) {
                  mHandler.post(
                      new Runnable() {

                        @Override
                        public void run() {
                          mListener.onPictureSaved(uri);
                        }
                      });
                }
              }
            });
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }
 public void onScanCompleted(String s, Uri uri)
 {
     if (mMediaScannerConnection != null)
     {
         mMediaScannerConnection.disconnect();
     }
 }
 public void onMediaScannerConnected()
 {
     if (mMediaScannerConnection != null)
     {
         mMediaScannerConnection.scanFile(mFilename, mMimeType);
     }
 }
Example #6
0
 @Override
 public void onScanCompleted(String path, Uri uri) {
   if (toScan.size() == 0) {
     conn.disconnect();
     conn = null;
   }
 }
  public void sendVideo(View view) {
    if (TextUtils.isEmpty(localPath)) {
      EMLog.e("Recorder", "recorder fail please try again!");
      return;
    }
    if (msc == null)
      msc =
          new MediaScannerConnection(
              this,
              new MediaScannerConnectionClient() {

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

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

    if (progressDialog == null) {
      progressDialog = new ProgressDialog(this);
      progressDialog.setMessage("processing...");
      progressDialog.setCancelable(false);
    }
    progressDialog.show();
    msc.connect();
  }
  public static String savePhoto(byte[] data, Context context) {
    File pictureFileDir = getDir();

    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

      Log.d(TAG, "Can't create directory to save image.");
      return null;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
    String date = dateFormat.format(new Date());
    String photoFile = BitmapUtils.PICTURE_PREFIX + date + ".jpg";

    String filename = pictureFileDir.getPath() + File.separator + photoFile;

    File pictureFile = new File(filename);

    try {
      FileOutputStream fos = new FileOutputStream(pictureFile);
      fos.write(data);
      fos.close();
      Log.d(TAG, "New Image saved:" + photoFile);

      // Let media scanner scan the image so it will be immediately visible in the gallery
      MediaScannerConnection.scanFile(context, new String[] {filename}, null, null);

      return filename;
    } catch (Exception error) {
      Log.d(TAG, "File" + filename + "not saved: " + error.getMessage());
    }
    return null;
  }
Example #9
0
 public static void informPathsDeleted(Context c, List<String> paths) {
   MediaScannerConnection.scanFile(
       c.getApplicationContext(),
       paths.toArray(new String[paths.size()]),
       null,
       sLogScannerListener);
 }
  @SuppressLint("SimpleDateFormat")
  private void storePictureInGallery(String url) {
    // Setting up file to write the image to.
    SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
    String s = getAlbumDir() + "/img" + gmtDateFormat.format(new Date()) + ".png";
    MRAIDLog.i(TAG, "Saving image into: " + s);
    File f = new File(s);
    // Open InputStream to download the image.
    InputStream is;
    try {
      is = new URL(url).openStream();
      // Set up OutputStream to write data into image file.
      OutputStream os = new FileOutputStream(f);
      copyStream(is, os);
      MediaScannerConnection.scanFile(
          context,
          new String[] {f.getAbsolutePath()},
          null,
          new OnScanCompletedListener() {

            @Override
            public void onScanCompleted(String path, Uri uri) {
              MRAIDLog.d("File saves successfully to " + path);
            }
          });
      MRAIDLog.i(TAG, "Saved image successfully");
    } catch (MalformedURLException e) {
      MRAIDLog.e(TAG, "Not able to save image due to invalid URL: " + e.getLocalizedMessage());
    } catch (IOException e) {
      MRAIDLog.e(TAG, "Unable to save image: " + e.getLocalizedMessage());
    }
  }
Example #11
0
  private void saveWave(String fileName, File fileToSave) throws IOException {
    int dataLength = (int) fileToSave.length();
    byte[] rawData = new byte[dataLength];

    DataInputStream input = null;
    try {
      input = new DataInputStream(new FileInputStream(fileToSave));
      input.read(rawData);
    } finally {
      if (input != null) {
        input.close();
      }
    }

    DataOutputStream output = null;
    try {
      File file = new File(fileDir + fileName + ".wav");
      output = new DataOutputStream(new FileOutputStream(file, false));
      // WAVE header
      // see http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
      writeString(output, "RIFF"); // chunk id
      writeInt(output, 36 + dataLength); // chunk size
      writeString(output, "WAVE"); // format
      writeString(output, "fmt "); // subchunk 1 id
      writeInt(output, 16); // subchunk 1 size
      writeShort(output, (short) 1); // audio format (1 = PCM)
      writeShort(output, (short) 1); // number of channels
      writeInt(output, SAMPLE_RATE); // sample rate
      writeInt(output, SAMPLE_RATE * 2); // byte rate
      writeShort(output, (short) 2); // block align
      writeShort(output, (short) 16); // bits per sample
      writeString(output, "data"); // subchunk 2 id
      writeInt(output, dataLength); // subchunk 2 size
      // Audio data (conversion big endian -> little endian)
      short[] shorts = new short[rawData.length / 2];
      ByteBuffer.wrap(rawData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
      ByteBuffer bytes = ByteBuffer.allocate(shorts.length * 2);
      for (short s : shorts) {
        bytes.putShort(s);
      }
      output.write(bytes.array());

      MediaScannerConnection.scanFile(
          ctx,
          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);
            }
          });

    } finally {
      if (output != null) {
        output.close();
      }
    }
  }
Example #12
0
 private void scanForGallery(Uri newImage) {
   this.scanMe = newImage;
   if (this.conn != null) {
     this.conn.disconnect();
   }
   this.conn =
       new MediaScannerConnection(this.cordova.getActivity().getApplicationContext(), this);
   conn.connect();
 }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case TAKE_IMAGE:
        try {
          if (resultCode == RESULT_OK) {

            // we need to update the gallery by starting MediaSanner service.
            mScanner =
                new MediaScannerConnection(
                    AndroidCustomGalleryActivity.this,
                    new MediaScannerConnection.MediaScannerConnectionClient() {
                      public void onMediaScannerConnected() {
                        mScanner.scanFile(imageUri.getPath(), null /* mimeType */);
                      }

                      public void onScanCompleted(String path, Uri uri) {
                        // we can use the uri, to get the newly added image, but it will return path
                        // to full sized image
                        // e.g. content://media/external/images/media/7
                        // we can also update this path by replacing media by thumbnail to get the
                        // thumbnail
                        // because thumbnail path would be like
                        // content://media/external/images/thumbnail/7
                        // But the thumbnail is created after some delay by Android OS
                        // So you may not get the thumbnail. This is why I started new UI thread
                        // and it'll only run after the current thread completed.
                        if (path.equals(imageUri.getPath())) {
                          mScanner.disconnect();
                          // we need to create new UI thread because, we can't update our mail
                          // thread from here
                          // Both the thread will run one by one, see documentation of android
                          AndroidCustomGalleryActivity.this.runOnUiThread(
                              new Runnable() {
                                public void run() {
                                  updateUI();
                                }
                              });
                        }
                      }
                    });
            mScanner.connect();
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
        break;
      case UPLOAD_IMAGES:
        if (resultCode == RESULT_OK) {
          // do some code where you integrate this project
        }
        break;
    }
  }
Example #14
0
  public static void informFolderAdded(Context c, File parentFile) {
    if (parentFile == null) return;

    ArrayList<String> filePaths = new ArrayList<String>();
    informFolderAddedCore(filePaths, parentFile);

    MediaScannerConnection.scanFile(
        c.getApplicationContext(),
        filePaths.toArray(new String[filePaths.size()]),
        null,
        sLogScannerListener);
  }
Example #15
0
  /**
   * Adds file and returns content uri.
   *
   * @param file
   * @return
   */
  private Uri addToMediaDB(File file) {
    ContentValues cv = new ContentValues();
    long current = System.currentTimeMillis();
    long modDate = file.lastModified();
    Date date = new Date(current);

    String sTime = DateFormat.getTimeFormat(mContext).format(date);
    String sDate = DateFormat.getDateFormat(mContext).format(date);
    String title = sDate + " " + sTime;

    // Lets label the recorded audio file as NON-MUSIC so that the file
    // won't be displayed automatically, except for in the playlist.

    // Currently if scan media, all db information will be cleared
    // so no need to put all information except MediaStore.Audio.Media.DATA

    // cv.put(MediaStore.Audio.Media.IS_MUSIC, "0");
    // cv.put(MediaStore.Audio.Media.TITLE, title);
    cv.put(MediaStore.Audio.Media.DATA, file.getAbsolutePath());
    // cv.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
    cv.put(MediaStore.Audio.Media.MIME_TYPE, mRequestedType);

    // cv.put(MediaStore.Audio.Media.ARTIST,
    // mContext.getString(R.string.your_recordings));
    // cv.put(MediaStore.Audio.Media.ALBUM,
    // mContext.getString(R.string.audio_recordings));
    // cv.put(MediaStore.Audio.Media.DURATION, this.sampleLength());
    // Log.d(TAG, "Inserting audio record: " + cv.toString());
    ContentResolver resolver = mContext.getContentResolver();
    Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    // Log.d(TAG, "ContentURI: " + base);
    Uri result = resolver.insert(base, cv);

    if (result == null) {
      Log.e(TAG, "----- Unable to save recorded audio !!");
      return null;
    }

    if (getPlaylistId() == -1) {
      createPlaylist(resolver);
    }
    int audioId = Integer.valueOf(result.getLastPathSegment());
    addToPlaylist(resolver, audioId, getPlaylistId());

    // Notify those applications such as Music listening to the
    // scanner events that a recorded audio file just created.
    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));

    // scan file
    MediaScannerConnection.scanFile(mContext, new String[] {file.getAbsolutePath()}, null, null);

    return result;
  }
Example #16
0
 /**
  * 浏览某种类型的文件
  *
  * @param context
  * @param files 待浏览的文件夹
  * @param mimeTypes 文件类型
  */
 public static void scanMediaFiles(final Context context, String[] files, String[] mimeTypes) {
   MediaScannerConnection.scanFile(
       context,
       files,
       mimeTypes,
       new OnScanCompletedListener() {
         @Override
         public void onScanCompleted(String arg0, Uri arg1) {
           Log.i("weitu", "arg0:" + arg0 + ";arg1:" + arg1);
         }
       });
 }
Example #17
0
  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
      case R.id.buttonSaveFile:
        String fileName = saveFile.getText().toString();
        // constructor with two parameters
        file = new File(path, fileName + ".png");
        checkState();
        if (writable == readable == true) {
          path.mkdirs();
          try {
            InputStream inputstream = getResources().openRawResource(R.drawable.blacksmiley);
            OutputStream outstream = new FileOutputStream(file);
            byte[] data = new byte[inputstream.available()];
            inputstream.read(data);
            outstream.write(data);
            inputstream.close();
            outstream.close();

            Toast t = Toast.makeText(ExternalData.this, "file has been saved", Toast.LENGTH_SHORT);
            t.show();
            // update files for the user to use
            MediaScannerConnection.scanFile(
                ExternalData.this,
                new String[] {file.toString()},
                null,
                new MediaScannerConnection.OnScanCompletedListener() {

                  @Override
                  public void onScanCompleted(String path, Uri uri) {
                    // TODO Auto-generated method stub
                    Toast t =
                        Toast.makeText(ExternalData.this, "scan complete", Toast.LENGTH_SHORT);
                    t.show();
                  }
                });

          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        break;
      case R.id.buttonConfirmSaveAs:
        save.setVisibility(View.VISIBLE);
        break;
    }
  }
 /** Send broadcast to notify system to scan music file. */
 private void scanSDCard() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
     // whether SDK is over 4.4
     String[] paths = new String[] {Environment.getExternalStorageDirectory().toString()};
     MediaScannerConnection.scanFile(mActivity, paths, null, null);
   } else {
     Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
     intent.setClassName(
         "com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
     intent.setData(Uri.parse("file://" + MusicUtils.getMusicDir()));
     mActivity.sendBroadcast(intent);
   }
 }
Example #19
0
  public void scanFileToPhotoAlbum(String path) {

    MediaScannerConnection.scanFile(
        getActivity(),
        new String[] {path},
        null,
        new MediaScannerConnection.OnScanCompletedListener() {

          public void onScanCompleted(String path, Uri uri) {
            Log.i("TAG", "Finished scanning " + path);
          }
        });
  }
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.bSaveFile:
        String f = saveFile.getText().toString();
        file = new File(path, f + ".png");

        checkState();
        if (canW == canR == true) {
          path.mkdirs();
          try {
            InputStream is = getResources().openRawResource(R.drawable.plusselected);
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

            Toast t = Toast.makeText(ExternalData.this, "File has been saved", Toast.LENGTH_LONG);
            t.show();

            // Update files for the user to use
            MediaScannerConnection.scanFile(
                ExternalData.this,
                new String[] {file.toString()},
                null,
                new MediaScannerConnection.OnScanCompletedListener() {

                  @Override
                  public void onScanCompleted(String path, Uri uri) {
                    Toast t =
                        Toast.makeText(ExternalData.this, "Scan Complete", Toast.LENGTH_SHORT);
                    t.show();
                  }
                });

          } catch (FileNotFoundException e) {
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        break;

      case R.id.bConfirmSaveAs:
        save.setVisibility(View.VISIBLE);
        break;
    }
  }
  void scanMedia(final String fp) {
    mc =
        new MediaScannerConnection(
            this,
            new MediaScannerConnection.MediaScannerConnectionClient() {
              public void onScanCompleted(String path, Uri uri) {
                disconnect();
              }

              public void onMediaScannerConnected() {
                scanFile(fp);
              }
            });
    mc.connect();
  }
Example #22
0
  /** Method that access the internal storage on the tablet in order to access log files */
  private void rescanSD(final File toScan) {

    MediaScannerConnection.MediaScannerConnectionClient MSCC =
        new MediaScannerConnection.MediaScannerConnectionClient() {

          public void onScanCompleted(String path, Uri uri) {
            Log.i(TAG, "Media Scan Completed.");
          }

          public void onMediaScannerConnected() {
            MSC.scanFile(toScan.getAbsolutePath(), null);
            Log.i(TAG, "Media Scanner Connected.");
          }
        };
    MSC = new MediaScannerConnection(getApplicationContext(), MSCC);
    MSC.connect();
  }
Example #23
0
  public void scanPhoto(final String imageFileName) {
    msConn =
        new MediaScannerConnection(
            CameraActivity.this,
            new MediaScannerConnectionClient() {
              public void onMediaScannerConnected() {
                msConn.scanFile(imageFileName, null);
                Log.i("msClient obj  in Photo Utility", "connection established");
              }

              public void onScanCompleted(String path, Uri uri) {
                msConn.disconnect();
                Log.i("msClient obj in Photo Utility", "scan completed");
              }
            });
    msConn.connect();
  }
Example #24
0
 public static void saveObjectToExternalStorage(
     Context context, Serializable obj, String filename) {
   File root = android.os.Environment.getExternalStorageDirectory();
   File myFolder = new File(root, "PicWorld");
   myFolder.mkdir();
   File file = new File(myFolder, filename);
   try {
     FileOutputStream f = new FileOutputStream(file);
     ObjectOutputStream os = new ObjectOutputStream(f);
     os.writeObject(obj);
     os.close();
     f.close();
   } catch (Exception e) {
     Log.e("F**K", "Exception while saving serialized object to file! " + e.getMessage());
   }
   MediaScannerConnection.scanFile(context, new String[] {file.getAbsolutePath()}, null, null);
 }
  protected void
      scanlist() { // cap nhat file photo vua duoc restore (trong /mtn/sdcardDCIM/.thumbnails)

    if (MyHiddenPhotoActivity.listToScan != null) {
      String[] temp = (String[]) MyHiddenPhotoActivity.listToScan.toArray(new String[0]);
      MediaScannerConnection.scanFile(
          this,
          temp,
          null,
          new OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {
              Log.i("ExternalStorage", "Scanned " + path + ":");
              Log.i("ExternalStorage", "-> uri=" + uri);
            }
          });
    }
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_save_image) {
      File file = getImageBitmap();
      ProgressDialog dialog = new ProgressDialog(ImageActivity.this);
      dialog.setMessage("Please Wait");
      dialog.setIndeterminate(true);
      dialog.show();
      MediaScannerConnection.scanFile(
          ImageActivity.this,
          new String[] {file.getAbsolutePath()},
          null,
          new MediaScannerConnection.OnScanCompletedListener() {

            public void onScanCompleted(String path, Uri uri) {
              Log.i("TAG", "Finished scanning " + path);
            }
          });
      if (f) {
        Toast toast = Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
        putSharedPreference(getApplicationContext(), "COUNT", ++count);
      } else {
        Toast toast =
            Toast.makeText(getApplicationContext(), "Couldn\'t Save Image ", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
      }
      dialog.cancel();
    } else if (item.getItemId() == R.id.action_image_share) {
      File file = getImageBitmap();
      Uri uri = Uri.fromFile(file);
      Intent sendIntent = new Intent();
      sendIntent.setAction(Intent.ACTION_SEND);
      sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
      sendIntent.setType("image/*");
      startActivity(Intent.createChooser(sendIntent, "Share Image"));
    } else if (item.getItemId() == android.R.id.home) {
      onBackPressed();
    }

    return super.onOptionsItemSelected(item);
  }
  @Override
  public void confirmStorePhotoDialogPositiveClick(DialogFragment dialog) {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {

      File path =
          new File(
              Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                  + "/"
                  + getResources().getString(R.string.app_name));
      File img = new File(path, room.getRoomNumber() + ".jpg");

      if (path.mkdirs() || path.isDirectory()) {
        try {
          InputStream is = getResources().openRawResource(resource);
          OutputStream os = new FileOutputStream(img);
          byte[] data = new byte[is.available()];
          is.read(data);
          os.write(data);
          is.close();
          os.close();

          final Toast success_toast =
              Toast.makeText(
                  getApplicationContext(),
                  getResources().getString(R.string.msg_photo_stored_succesfull),
                  Toast.LENGTH_SHORT);
          MediaScannerConnection.scanFile(
              this,
              new String[] {img.toString()},
              null,
              new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                  success_toast.show();
                }
              });
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #28
0
  public boolean scanNewMovie() {
    connection =
        new MediaScannerConnection(
            getActivity(),
            new MediaScannerConnection.MediaScannerConnectionClient() {
              @Override
              public void onMediaScannerConnected() {
                connection.scanFile(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI.getPath(), "video/*");
              }

              @Override
              public void onScanCompleted(String path, Uri uri) {
                connection.disconnect();
              }
            });
    connection.connect();
    return true;
  }
  private void scanFile(String path, final boolean edit) {

    MediaScannerConnection.scanFile(
        SlideImageActivity.this,
        new String[] {path},
        null,
        new MediaScannerConnection.OnScanCompletedListener() {

          public void onScanCompleted(String path, Uri uri) {
            Log.i("TAG", "Finished scanning " + path);
            if (edit) {
              Intent editIntent = new Intent(Intent.ACTION_EDIT);
              // editIntent.setType("image/*");
              editIntent.setDataAndType(uri, "image/*");
              startActivity(Intent.createChooser(editIntent, null));
            }
          }
        });
  }
Example #30
0
  /** 通知系统扫描SDCard,及时更新媒体库 */
  public static void scanSdCard(Context mContext) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
      mContext.sendBroadcast(
          new Intent(
              Intent.ACTION_MEDIA_MOUNTED,
              Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
    } else {
      mContext.sendBroadcast(
          new Intent(
              Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
              Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
    }

    // 4.4之后的系统无法通过广播更新,所以使用下面这个方法扫描更新
    MediaScannerConnection.scanFile(
        mContext,
        new String[] {Environment.getExternalStorageDirectory().getAbsolutePath()},
        null,
        null);
  }