下面列出了怎么用android.provider.MediaStore的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
@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;
}
}
@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();
}
}
}
/**
* 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();
}
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;
}
}
}
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) {
}
}
/**
* 图片路径转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;
}
}
}
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;
}
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();
}
/**
* 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;
}
}
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;
}
}
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;
}
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;
}
/**
*
* 获取图片地址列表
*
* @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;
}
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();
}
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 "";
}
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;
}
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();
}
}
/**
* 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);
}
}
@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)));
}
});
}
/**
* 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();
}
public String getCameraStoragePath(Uri uri) {
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
return uri.toString();
}
/**
* This checks to see if there is a suitable activity to handle the `ACTION_PICK` intent
* and returns it if found. {@link Intent#ACTION_PICK} is for picking an image from an external app.
*
* @return A prepared intent if found.
*/
@Nullable
private Intent createPickIntent() {
if (pickerType != PickerType.CAMERA) {
Intent picImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (picImageIntent.resolveActivity(getActivity().getPackageManager()) != null) {
return picImageIntent;
}
}
return null;
}
private void getNewProfileImage()
{
Intent gallery_intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
gallery_intent.setType("image/*");
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
final Intent chooserIntent = Intent.createChooser(gallery_intent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { captureIntent });
startActivityForResult(chooserIntent, PICK_IMAGE_REQUEST);
}
public static List<Album> getAllAlbum() {
if (!hasStoragePermissions()) {
return new ArrayList<>();
}
ArrayList<Album> albums = new ArrayList<>();
try (Cursor cursor = mContext.getContentResolver()
.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.ARTIST,
"count(" + Media.ALBUM_ID + ")"},
MediaStoreUtil.getBaseSelection() + ")" + " GROUP BY ("
+ MediaStore.Audio.Media.ALBUM_ID,
null,
SPUtil.getValue(mContext, SPUtil.SETTING_KEY.NAME, SPUtil.SETTING_KEY.ALBUM_SORT_ORDER,
SortOrder.AlbumSortOrder.ALBUM_A_Z))) {
if (cursor != null) {
while (cursor.moveToNext()) {
try {
albums.add(new Album(cursor.getInt(0),
cursor.getString(1),
cursor.getInt(2),
cursor.getString(3),
cursor.getInt(4)));
} catch (Exception ignored) {
}
}
}
}
return albums;
}
@Override
public Cursor loadInBackground() {
if (Permissions.hasAll(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
return context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
PROJECTION, SELECTION, null,
MediaStore.Images.ImageColumns.DATE_MODIFIED + " DESC");
} else {
return null;
}
}
/**
* sdk24之后拍照
*/
private void doTakePhotoAfterSdk24(Intent intent, File tempPicFile)
{
Uri imageUri = FileProvider.getUriForFile(this, ImagePickerProvider.getAuthorities(this), tempPicFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
startActivityForResult(intent, sREQUESTCODE_TAKE_PHOTO);
}
/**
* Builds a {@link List} of Albums from a Cursor
* @param cur A {@link Cursor} to use when reading the {@link MediaStore}. This Cursor may have
* any filters and sorting, but MUST have AT LEAST the columns in
* {@link MediaStoreUtil#ALBUM_PROJECTION}. The caller is responsible for closing
* this Cursor.
* @param res A {@link Resources} Object from {@link Context#getResources()} used to get the
* default values if an unknown value is encountered
* @return A List of albums populated by entries in the Cursor
*/
public static List<Album> buildAlbumList(Cursor cur, Resources res) {
List<Album> albums = new ArrayList<>(cur.getCount());
final int idIndex = cur.getColumnIndex(MediaStore.Audio.Albums._ID);
final int albumIndex = cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM);
final int artistIndex = cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST);
final int artistIdIndex = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID);
final int yearIndex = cur.getColumnIndex(MediaStore.Audio.Albums.LAST_YEAR);
final int artIndex = cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
final String unknownAlbum = res.getString(R.string.unknown_album);
final String unknownArtist = res.getString(R.string.unknown_artist);
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
Album next = new Album();
next.albumId = cur.getLong(idIndex);
next.albumName = parseUnknown(cur.getString(albumIndex), unknownAlbum);
next.artistName = parseUnknown(cur.getString(artistIndex), unknownArtist);
next.artistId = cur.getLong(artistIdIndex);
next.year = cur.getInt(yearIndex);
next.artUri = cur.getString(artIndex);
next.sortableName = sortableTitle(next.albumName, res);
albums.add(next);
}
return albums;
}
private void postImageToFacebook() {
Session session = Session.getActiveSession();
final Uri uri = (Uri) mExtras.get(Intent.EXTRA_STREAM);
final String extraText = mPostTextView.getText().toString();
if (session.isPermissionGranted("publish_actions"))
{
Bundle param = new Bundle();
// Add the image
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArrayData = stream.toByteArray();
param.putByteArray("picture", byteArrayData);
} catch (IOException ioe) {
// The image that was send through is now not there?
Assert.assertTrue(false);
}
// Add the caption
param.putString("message", extraText);
Request request = new Request(session,"me/photos", param, HttpMethod.POST, new Request.Callback() {
@Override
public void onCompleted(Response response) {
addNotification(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
}, null);
RequestAsyncTask asyncTask = new RequestAsyncTask(request);
asyncTask.execute();
finish();
}
}
/**
* Creates an intent to take a video from camera or gallery or any other application that can
* handle the intent.
*
* @param ctx
* @param savingUri
* @param durationInSeconds
* @return
*/
public static Intent createTakeVideoIntent(Activity ctx, Uri savingUri, int durationInSeconds) {
if (savingUri == null) {
throw new NullPointerException("Uri cannot be null");
}
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
final PackageManager packageManager = ctx.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, savingUri);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, durationInSeconds);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("video/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
return chooserIntent;
}