Android: Permite que el usuario elija una imagen o un video de la Galería

¿Es posible iniciar Gallery de tal manera que se muestren tanto las imágenes como los videos?

Gracias

Seleccionar archivo de audio de la Galería:

//Use MediaStore.Audio.Media.EXTERNAL_CONTENT_URI Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI); 

Seleccionar archivo de vídeo de la Galería:

 //Use MediaStore.Audio.Media.EXTERNAL_CONTENT_URI Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI); 

Escoge la imagen de la galería:

 //Use MediaStore.Images.Media.EXTERNAL_CONTENT_URI Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

Seleccionar archivos de medios o imágenes:

  Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/* video/*"); 

Inicia la galería como tal:

 Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setType("image/* video/*"); startActivityForResult(pickIntent, IMAGE_PICKER_SELECT); 

A continuación, en su onActivityResult puede comprobar si el video o la imagen se ha seleccionado haciendo esto:

 public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { Uri selectedMediaUri = data.getData(); if (selectedMediaUri.toString().contains("image")) { //handle image } else if (selectedMediaUri.toString().contains("video")) { //handle video } } 

(EDIT: Ya no lo utilizo, volvimos a las dos opciones "escoger imagen" y "escoger video" El problema fue con algunos teléfonos Sony Así que, no es 100% solución a continuación, ten cuidado!)

Esto es lo que uso:

 if (Build.VERSION.SDK_INT < 19) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/* video/*"); startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)), SELECT_GALLERY); } else { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"}); startActivityForResult(intent, SELECT_GALLERY_KITKAT); } 

La clave aquí es intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});

 intent.setType("*/*"); 

Esto presenta al usuario con el diálogo, pero funciona en al menos ICS. No se han probado en otras plataformas.

Cuando necesite determinar qué tipo de contenido se devolvió, puede hacerlo utilizando la resolución de contenido para obtener el tipo MIME del contenido devuelto:

 if( data != null) { Uri selectedUri = data.getData(); String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.MIME_TYPE }; Cursor cursor = getContentResolver().query(selectedUri, columns, null, null, null); cursor.moveToFirst(); int pathColumnIndex = cursor.getColumnIndex( columns[0] ); int mimeTypeColumnIndex = cursor.getColumnIndex( columns[1] ); String contentPath = cursor.getString(pathColumnIndex); String mimeType = cursor.getString(mimeTypeColumnIndex); cursor.close(); if(mimeType.startsWith("image")) { //It's an image } else if(mimeType.startsWith("video")) { //It's a video } } else { // show error or do nothing } 

Necesita utilizar lo siguiente como objetivo de picking

 Intent photoLibraryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); photoLibraryIntent.setType("image/* video/*"); 

CoolIris que viene con mi pestaña de galaxia puede hacerlo. Sin embargo, el cooliris en mi acer betouch no: S En mi hito no se puede iniciar la galería con una intención de selección en el url de vídeo sin embargo, cuando se inicia en la url de imágenes, puede seleccionar un video y se devolverá un url de vídeo también.

No, no es posible con la aplicación Stock Gallery. Puedes intentar buscar una aplicación que haga esto.

 private static final String TAG = MainActivity.class.getSimpleName(); public Button buttonUpload; public Button buttonChoose; public VideoView vdoView; private ImageView imageView; private ProgressDialog progressBar; public String path=null; long totalSize = 0; String mediapath; public static final String KEY_VIDEO = "video"; public static final String KEY_NAME = "name"; private int PICK_IMAGE_REQUEST = 1; private int serverResponseCode; private Bitmap bitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.edittext); buttonChoose=(Button)findViewById(R.id.buttonChoosevdo); buttonUpload = (Button) findViewById(R.id.buttonUpload); vdoView = (VideoView) findViewById(R.id.videoView); buttonChoose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showFileChooser(); } }); buttonUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { uploadVideo(); } }); } public void showFileChooser() { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } @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) { try { path = data.getData().toString(); vdoView.setVideoPath(path); vdoView.requestFocus(); vdoView.start(); } catch(Exception ex) { ex.printStackTrace(); } } } public String uploadVideo() { String UPLOAD_URL = "http://192.168.10.15/uploadVideo.php"; HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; //Log.d(TAG,path); File sourceFile = new File(path); if (!sourceFile.isFile()) { Log.e("Huzza ->>>>)}]------> ", "Source File Does not exist"); return null; } String fileName = path; //Log.d(TAG,fileName); try { FileInputStream fileInputStream = new FileInputStream(path); Log.d(TAG, String.valueOf(fileInputStream)); URL url = new URL(UPLOAD_URL); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("myFile", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); Log.i("Huzza", "Initial .available : " + bytesAvailable); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); serverResponseCode = conn.getResponseCode(); Log.d(TAG, String.valueOf(serverResponseCode)); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if (serverResponseCode == 200) { StringBuilder sb = new StringBuilder(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn .getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); } catch (IOException ioex) { } return sb.toString(); }else { return "Could not upload"; } } 
  • Cómo evitar los tipos * / * mime en filtros de intención
  • ¿Existe alguna manera de obtener el nombre de un archivo mediante la API de Google Drive?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.