android.provider.MediaStore Java Examples

The following examples show how to use android.provider.MediaStore. 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: MainActivity.java    From PhotoEdit with Apache License 2.0 7 votes vote down vote up
private void getPictureFormCamera() {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

    tempPhotoPath = FileUtils.DCIMCamera_PATH + FileUtils.getNewFileName()
            + ".jpg";

    mCurrentPhotoFile = new File(tempPhotoPath);

    if (!mCurrentPhotoFile.exists()) {
        try {
            mCurrentPhotoFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(mCurrentPhotoFile));
    startActivityForResult(intent, CAMERA_WITH_DATA);
}
 
Example #2
Source File: SongLoader.java    From flutter_audio_query with MIT License 7 votes vote down vote up
/**
 * This method creates a SQL CASE WHEN THEN in order to get specific songs
 * from Media table where the query results is sorted matching [songIds] list values order.
 *
 * @param songIds Song ids list
 * @return Sql String case when then or null if songIds size is not greater then 1.
 */
private String prepareIDsSongsSortOrder(final List<String> songIds){
    if (songIds.size() == 1)
        return null;

    StringBuilder orderStr = new StringBuilder("CASE ")
            .append(MediaStore.MediaColumns._ID)
            .append(" WHEN '")
            .append(songIds.get(0))
            .append("'")
            .append(" THEN 0");

    for(int i = 1; i < songIds.size(); i++){
        orderStr.append(" WHEN '")
                .append( songIds.get(i) )
                .append("'")
                .append(" THEN ")
                .append(i);
    }

    orderStr.append(" END, ")
            .append(MediaStore.MediaColumns._ID)
            .append(" ASC");
    return orderStr.toString();
}
 
Example #3
Source File: MediaStoreUtil.java    From Augendiagnose with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get an Uri from an file path.
 *
 * @param path The file path.
 * @return The Uri.
 */
public static Uri getUriFromFile(final String path) {
	ContentResolver resolver = Application.getAppContext().getContentResolver();

	Cursor filecursor = resolver.query(MediaStore.Files.getContentUri("external"),
			new String[]{BaseColumns._ID}, MediaColumns.DATA + " = ?",
			new String[]{path}, MediaColumns.DATE_ADDED + " desc");
	if (filecursor == null) {
		return null;
	}
	filecursor.moveToFirst();

	if (filecursor.isAfterLast()) {
		filecursor.close();
		ContentValues values = new ContentValues();
		values.put(MediaColumns.DATA, path);
		return resolver.insert(MediaStore.Files.getContentUri("external"), values);
	}
	else {
		int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
		Uri uri = MediaStore.Files.getContentUri("external").buildUpon().appendPath(
				Integer.toString(imageId)).build();
		filecursor.close();
		return uri;
	}
}
 
Example #4
Source File: MainActivity.java    From MagicLight-Controller with Apache License 2.0 6 votes vote down vote up
/**
 * onActivityResult, request ble system enable
 * @param requestCode
 * @param resultCode
 * @param data
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // user chose not to enable bluetooth.
    if (requestCode == REQUEST_WRITE_STORAGE && resultCode == Activity.RESULT_CANCELED) {
        Toast.makeText(this, R.string.ble_canceled, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    // user choose a picture from gallery
    else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        Drawable drawable = new BitmapDrawable(getResources(), bitmap);
        colorPickerView.setPaletteDrawable(drawable);
    }
}
 
Example #5
Source File: GLSurfaceCamera2Activity.java    From CameraDemo with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.toolbar_close_iv:
            finish();
            break;
        case R.id.toolbar_switch_iv:
            mCameraProxy.switchCamera(mCameraView.getWidth(), mCameraView.getHeight());
            mCameraProxy.startPreview();
            break;
        case R.id.take_picture_iv:
            mCameraProxy.setImageAvailableListener(mOnImageAvailableListener);
            mCameraProxy.captureStillPicture(); // 拍照
            break;
        case R.id.picture_iv:
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivity(intent);
            break;
    }
}
 
Example #6
Source File: DetailPlayer.java    From GSYVideoPlayer with Apache License 2.0 6 votes vote down vote up
private void getPathForSearch(Uri uri) {
    String[] selectionArgs = new String[]{DocumentsContract.getDocumentId(uri).split(":")[1]};
    Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + "=?",
            selectionArgs, null);
    if (null != cursor) {
        if (cursor.moveToFirst()) {
            int index = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
            if (index > -1) {
                detailPlayer.setUp(uri.toString(), false, "File");
                detailPlayer.startPlayLogic();
            }
        }
        cursor.close();
    }
}
 
Example #7
Source File: MainActivity.java    From Password-Storage with MIT License 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            if(flag==1) {passwordDatabase.updatePic(bitmap); }
            else if(flag==0) {passwordDatabase.setPic(bitmap); flag=1; }

            profile.setImageBitmap(bitmap);
            //round image
            RoundedBitmapDrawable roundedImageDrawable = createRoundedBitmapImageDrawableWithBorder(bitmap);
            profile.setImageDrawable(roundedImageDrawable);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #8
Source File: MsgImgHolder.java    From Android with MIT License 6 votes vote down vote up
@Override
public void saveInPhone() {
    super.saveInPhone();
    final MsgDefinBean bean = baseEntity.getMsgDefinBean();
    String local = TextUtils.isEmpty(bean.getContent()) ? bean.getUrl() : bean.getContent();
    Glide.with(BaseApplication.getInstance())
            .load(local)
            .asBitmap()
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    File file = FileUtil.createAbsNewFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/connect/" + bean.getMessage_id() + FileUtil.FileType.IMG.getFileType());
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), resource, "connect", "");
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                }
            });
}
 
Example #9
Source File: ArtistLoader.java    From flutter_audio_query with MIT License 6 votes vote down vote up
/**
 * This method creates a SQL CASE WHEN THEN in order to get specific elements
 * where the query results is sorted matching [IDs] list values order.
 *
 * @param idList Song IDs list
 * @return Sql String case when then or null if idList size is not greater then 1.
 */
private String prepareIDsSortOrder(final List<String> idList){
    if (idList.size() == 1)
        return null;

    StringBuilder orderStr = new StringBuilder("CASE ")
            .append(MediaStore.MediaColumns._ID)
            .append(" WHEN '")
            .append(idList.get(0))
            .append("'")
            .append(" THEN 0");

    for(int i = 1; i < idList.size(); i++){
        orderStr.append(" WHEN '")
                .append( idList.get(i) )
                .append("'")
                .append(" THEN ")
                .append(i);
    }

    orderStr.append(" END, ")
            .append(MediaStore.MediaColumns._ID)
            .append(" ASC");
    return orderStr.toString();
}
 
Example #10
Source File: CompatHelper.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
public static Uri getImageContentUri(Context context, File imageFile) {
    String filePath = imageFile.getAbsolutePath();
    Cursor cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Images.Media._ID },
            MediaStore.Images.Media.DATA + "=? ",
            new String[] { filePath }, null);

    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor
                .getColumnIndex(MediaStore.MediaColumns._ID));
        Uri baseUri = Uri.parse("content://media/external/images/media");
        return Uri.withAppendedPath(baseUri, "" + id);
    } else {
        if (imageFile.exists()) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            return context.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }
}
 
Example #11
Source File: genersBtns.java    From Android-Music-Player with MIT License 6 votes vote down vote up
String getFirstPath(){

        String searchString = MediaStore.Audio.Genres.Members.IS_MUSIC+"=?";
        String[] searchPram = new String[]{"1"};
        String[] cols = new String[] {  MediaStore.Audio.Genres.Members.DATA };
        Cursor cursor = Ui.ef.getBaseContext().getContentResolver().query(MediaStore.Audio.Genres.Members.getContentUri("external", Long.parseLong(data[1])),cols, searchString,searchPram, MediaStore.Audio.Media.TITLE +" COLLATE NOCASE ASC");


        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            return  cursor.getString(0);
        }
        cursor.close();
        return  null;

    }
 
Example #12
Source File: PlaylistsUtil.java    From MusicPlayer with GNU General Public License v3.0 6 votes vote down vote up
public static void removeFromPlaylist(@NonNull final Context context, @NonNull final List<PlaylistSong> songs) {
    final int playlistId = songs.get(0).playlistId;
    Uri uri = MediaStore.Audio.Playlists.Members.getContentUri(
            "external", playlistId);
    String selectionArgs[] = new String[songs.size()];
    for (int i = 0; i < selectionArgs.length; i++) {
        selectionArgs[i] = String.valueOf(songs.get(i).idInPlayList);
    }
    String selection = MediaStore.Audio.Playlists.Members._ID + " in (";
    //noinspection unused
    for (String selectionArg : selectionArgs) selection += "?, ";
    selection = selection.substring(0, selection.length() - 2) + ")";

    try {
        context.getContentResolver().delete(uri, selection, selectionArgs);
    } catch (SecurityException ignored) {
    }
}
 
Example #13
Source File: PlaylistsUtil.java    From Phonograph with GNU General Public License v3.0 6 votes vote down vote up
public static String getNameForPlaylist(@NonNull final Context context, final long id) {
    try {
        Cursor cursor = context.getContentResolver().query(EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.PlaylistsColumns.NAME},
                BaseColumns._ID + "=?",
                new String[]{String.valueOf(id)},
                null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    return cursor.getString(0);
                }
            } finally {
                cursor.close();
            }
        }
    } catch (SecurityException ignored) {
    }
    return "";
}
 
Example #14
Source File: ImagePickerActivity.java    From Android-Image-Picker-and-Cropping with GNU General Public License v3.0 6 votes vote down vote up
private void takeCameraImage() {
    Dexter.withActivity(this)
            .withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {
                        fileName = System.currentTimeMillis() + ".jpg";
                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, getCacheImagePath(fileName));
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                        }
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
}
 
Example #15
Source File: MediaResourceManager.java    From GreenDamFileExploere with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 获取图片地址列表
 * 
 * @return list
 */
public static List<String> getImagesFromMedia() {
    ArrayList<String> pictures = new ArrayList<String>();
    Cursor c = null;
    try {
        FileCategoryPageFragment.mAllPictureSize = 0;
        c = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { "_id", "_data", "_size" }, null, null, null);
        while (c.moveToNext()) {
            String path = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            if (!FileUtils.isExists(path)) {
                continue;
            }
            long size = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
            FileCategoryPageFragment.mAllPictureSize += size;
            pictures.add(path);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return pictures;
}
 
Example #16
Source File: UriUtils.java    From ImageSelector with Apache License 2.0 6 votes vote down vote up
/**
 * 图片路径转uri
 * @param context
 * @param path
 * @return
 */
public static Uri getImageContentUri(Context context, String path) {
    Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
            new String[] { path }, null);
    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
        Uri baseUri = Uri.parse("content://media/external/images/media");
        return Uri.withAppendedPath(baseUri, "" + id);
    } else {
        if (new File(path).exists()) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, path);
            return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }
}
 
Example #17
Source File: LocalContentUriThumbnailFetchProducer.java    From fresco with MIT License 6 votes vote down vote up
private @Nullable EncodedImage getCameraImage(Uri uri, @Nullable ResizeOptions resizeOptions)
    throws IOException {
  if (resizeOptions == null) {
    return null;
  }
  @Nullable Cursor cursor = mContentResolver.query(uri, PROJECTION, null, null, null);
  if (cursor == null) {
    return null;
  }
  try {
    if (cursor.moveToFirst()) {
      final int imageIdColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID);
      final EncodedImage thumbnail =
          getThumbnail(resizeOptions, cursor.getLong(imageIdColumnIndex));
      if (thumbnail != null) {
        final String pathname =
            cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
        thumbnail.setRotationAngle(getRotationAngle(pathname));
        return thumbnail;
      }
    }
  } finally {
    cursor.close();
  }
  return null;
}
 
Example #18
Source File: ContentFragment.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
private ArrayList<BaseFile> listVideos() {
	ArrayList<BaseFile> songs = new ArrayList<>(1024);
	final String[] projection = {MediaStore.Images.Media.DATA};
	final Cursor cursor = activity.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
															  projection, null, null, null);
	if (cursor.getCount() > 0 && cursor.moveToFirst()) {
		do {
			final String path = cursor.getString(cursor.getColumnIndex
										   (MediaStore.Files.FileColumns.DATA));
			final BaseFile strings = RootHelper.generateBaseFile(new File(path), SHOW_HIDDEN);
			if (strings != null) 
				songs.add(strings);
			final long present = System.currentTimeMillis();
			if (present - prevUpdate > 1000 && !busyNoti) {
				prevUpdate = present;
				publishProgress(songs);
				songs = new ArrayList<>(1024);
			}
		} while (cursor.moveToNext());
	}
	publishProgress(songs);
	cursor.close();
	return songs;
}
 
Example #19
Source File: VideoChooserManager.java    From memoir with Apache License 2.0 6 votes vote down vote up
private boolean captureVideo() {
    try {
        File videoPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File videoFile = MediaUtils.createUniqueFile(videoPath, CAPTURED_VIDEO_TEMPLATE, false);
        videoPath.mkdirs();

        if (videoPath.exists() && videoPath.createNewFile()) {
            setOriginalFile(videoFile.getAbsolutePath());
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE)
                    .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getOriginalFile())));
            startActivity(intent);
        } else {
            Toast.makeText(mActivity, "Can't take picture without an sdcard", Toast.LENGTH_SHORT).show();
            return false;
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), e.getMessage(), e);
    }

    return true;
}
 
Example #20
Source File: ProfileSetting.java    From XERUNG with Apache License 2.0 6 votes vote down vote up
private void selectImage() {

        final CharSequence[] items = {"Take Photo", "Choose from Gallery", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(ProfileSetting.this);
        builder.setTitle("Select Photo");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                    }
                } else if (items[item].equals("Choose from Gallery")) {
                    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                    photoPickerIntent.setType("image/*");
                    startActivityForResult(photoPickerIntent, SELECT_PHOTO);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
 
Example #21
Source File: MediaStoreUtils.java    From FileManager with Apache License 2.0 6 votes vote down vote up
public static Uri getUriFromFile(final String path, Context context) {
    ContentResolver resolver = context.getContentResolver();

    Cursor filecursor = resolver.query(MediaStore.Files.getContentUri("external"),
            new String[]{BaseColumns._ID}, MediaColumns.DATA + " = ?",
            new String[]{path}, MediaColumns.DATE_ADDED + " desc");
    filecursor.moveToFirst();

    if (filecursor.isAfterLast()) {
        filecursor.close();
        ContentValues values = new ContentValues();
        values.put(MediaColumns.DATA, path);
        return resolver.insert(MediaStore.Files.getContentUri("external"), values);
    } else {
        int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
        Uri uri = MediaStore.Files.getContentUri("external").buildUpon().appendPath(
                Integer.toString(imageId)).build();
        filecursor.close();
        return uri;
    }
}
 
Example #22
Source File: RingtoneSetting.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
public static void setting(Context context) {
	// 外部调用者传来的context
	mContext = context;
	// 设置歌曲路径
	File filePath = new File(mUrl);
	ContentValues values = new ContentValues();
	// The data stream for the file
	values.put(MediaStore.MediaColumns.DATA, filePath.getAbsolutePath());
	// The title of the content
	values.put(MediaStore.MediaColumns.TITLE, filePath.getName());
	// The MIME type of the file
	values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
	// values.put(MediaStore.Audio.Media.ARTIST, "Madonna");
	// values.put(MediaStore.Audio.Media.DURATION, 230);
	// 来电铃声
	// 第二个参数若是true则会在铃音库中显示
	values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
	// 通知/短信铃声
	values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
	// 闹钟铃声
	values.put(MediaStore.Audio.Media.IS_ALARM, true);
	// 系统铃声
	values.put(MediaStore.Audio.Media.IS_MUSIC, true);
	// Insert it into the database
	Uri uri = MediaStore.Audio.Media.getContentUriForPath(filePath
			.getAbsolutePath());
	// 下面这一句很重要
	mContext.getContentResolver().delete(
			uri,
			MediaStore.MediaColumns.DATA + "=\""
					+ filePath.getAbsolutePath() + "\"", null);
	Uri newUri = mContext.getContentResolver().insert(uri, values);
	RingtoneManager.setActualDefaultRingtoneUri(mContext,
			RingtoneManager.TYPE_RINGTONE, newUri);

}
 
Example #23
Source File: popupAdapter.java    From Android-Music-Player with MIT License 5 votes vote down vote up
public String getAudiopath(int Id) {
    String[] projection = { MediaStore.Audio.Media.DATA };
    Cursor DataCursor = Ui.ef.getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection,
            MediaStore.Audio.Media._ID + " = " + Id, null, null);

    DataCursor.moveToNext();
    String audioPath = DataCursor.getString(0);
    DataCursor.close();
    return audioPath;
}
 
Example #24
Source File: Album.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public Album(Resources res, Cursor cur) {
    albumId = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Albums._ID));
    albumName = parseUnknown(
            cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM)),
            res.getString(R.string.unknown_album));
    artistName = parseUnknown(
            cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)),
            res.getString(R.string.unknown_artist));
    artistId = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
    year = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Albums.LAST_YEAR));
    artUri = cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));

    sortableName = sortableTitle(albumName, res);
}
 
Example #25
Source File: LocalMediaLoader.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
/**
 * Query conditions in all modes
 *
 * @param time_condition
 * @param isGif
 * @return
 */
private static String getSelectionArgsForAllMediaCondition(String time_condition, boolean isGif) {
    String condition = "(" + MediaStore.Files.FileColumns.MEDIA_TYPE + "=?"
            + (isGif ? "" : " AND " + MediaStore.MediaColumns.MIME_TYPE + NOT_GIF)
            + " OR "
            + (MediaStore.Files.FileColumns.MEDIA_TYPE + "=? AND " + time_condition) + ")"
            + " AND " + MediaStore.MediaColumns.SIZE + ">0";
    return condition;
}
 
Example #26
Source File: CameraActivity.java    From PracticeDemo with Apache License 2.0 5 votes vote down vote up
private void cropPhoto(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 144);//5.1.1 两个outputX设置成一样就奔溃 坑爹啊
    intent.putExtra("outputY", 300);
    intent.putExtra("scale", true);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.putExtra("return-data", true);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true);
    startActivityForResult(intent, CROP_PIC);
}
 
Example #27
Source File: QueueProviderPlaylistsMediaStore.java    From PainlessMusicPlayer with Apache License 2.0 5 votes vote down vote up
@NonNull
private Observable<List<Media>> loadMediasForIds(@NonNull final long[] mediaIds) {
    return mMediaProvider.load(
            SelectionUtils.inSelectionLong(MediaStore.Audio.Media._ID, mediaIds),
            null,
            SelectionUtils.orderByLongField(MediaStore.Audio.Media._ID, mediaIds),
            null);
}
 
Example #28
Source File: FlashTemplate.java    From BuildmLearn-Toolkit-Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Bitmap grabImage(Context context) {
    context.getContentResolver().notifyChange(mImageUri, null);
    ContentResolver cr = context.getContentResolver();
    Bitmap bitmap;
    try {
        bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
        return bitmap;
    } catch (Exception e) {
        Log.d(TAG, "Failed to load", e);
    }
    return null;
}
 
Example #29
Source File: UriUtil.java    From Common with Apache License 2.0 5 votes vote down vote up
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    final String[] projection = {MediaStore.MediaColumns.DATA,
            MediaStore.MediaColumns.DISPLAY_NAME};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            final String path = column_index > -1 ? cursor.getString(column_index) : null;
            if (path != null) {
                return path;
            } else {
                final int indexDisplayName = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
                final String fileName = cursor.getString(indexDisplayName);
                final File fileWritten = writeToFile(context, fileName, uri);
                return fileWritten.getAbsolutePath();
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return null;
}
 
Example #30
Source File: OSUtilities.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
public static Uri getMediaUri(String ringtoneTitle) {

        Uri parcialUri = Uri.parse("content://media/external/audio/media"); // also can be "content://media/internal/audio/media", depends on your needs
        Uri finalSuccessfulUri;

        RingtoneManager rm = new RingtoneManager(ApplicationLoader.applicationContext);
        rm.setType(RingtoneManager.TYPE_ALL);

        Cursor cursor = rm.getCursor();
        cursor = ApplicationLoader.applicationContext.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null,
                null,
                null,
                MediaStore.Audio.Media.TITLE);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            // FileLog.e("finalSuccessfulUri",cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
            if (ringtoneTitle.equalsIgnoreCase(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)))) {
                int ringtoneID = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));

                finalSuccessfulUri = Uri.withAppendedPath(parcialUri, "" + ringtoneID);
                // FileLog.e("finalSuccessfulUri",finalSuccessfulUri.getPath());
                return finalSuccessfulUri;
            }
            cursor.moveToNext();
        }
        return null;
    }