Java Code Examples for android.provider.MediaStore

The following are top voted examples for showing how to use android.provider.MediaStore. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Hotspot-master-devp   File: MediaUtils.java   Source Code and License 7 votes vote down vote up
/**
 * 获取本地图片信息
 * @param context
 * @param map
 */
public static void getImgInfo(Context context, HashMap<String, ArrayList<String>> map) {
    //获取图片信息表
    Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    ContentResolver mContentResolver = context.getContentResolver();
    Cursor mCursor = mContentResolver.query(imageUri, null,
            MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
            new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_TAKEN + " DESC");
    while (mCursor.moveToNext()) {
        String imgPath = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
        //获取图片父路径
        String parentPath = new File(imgPath).getParentFile().getName();
        if (!map.containsKey(parentPath)) {
            ArrayList<String> childList = new ArrayList<String>();
            childList.add(imgPath);
            map.put(parentPath, childList);
        } else {
            map.get(parentPath).add(imgPath);
        }
    }
    mCursor.close();
}
 
Example 2
Project: siiMobilityAppKit   File: CameraLauncher.java   Source Code and License 7 votes vote down vote up
/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *
 * @param type FILE_URI or DATA_URL
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
        cursor.close();
    }
}
 
Example 3
Project: ActivityBuilder   File: CameraActivity.java   Source Code and License 6 votes vote down vote up
private void takePhoto() {
  Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  ComponentName componentName = intentPhoto.resolveActivity(getPackageManager());
  if (componentName != null) {
    // 使用 lambda 表达式捕获局部变量,避免了将 tmpFile 作为类变量。
    File tmpFile = getTempFile(FileType.IMG);
    if (tmpFile != null) {
      BuilderUtil.createBuilder(this, intentPhoto)
          .asIntent()
          .setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
          .putExtra(MediaStore.EXTRA_OUTPUT, getUri(componentName, tmpFile))
          .asBuilder()
          .forOk((context, intent) -> context.showPicture(tmpFile))
          .start();
    }
  }
}
 
Example 4
Project: ChenYan   File: PublishAActivity.java   Source Code and License 6 votes vote down vote up
/**
     * 裁剪图片
     *
     * @param uri
     */
    private void cropImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
//        图片处于可裁剪状态
        intent.putExtra("crop", "true");
//        aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 4);
        intent.putExtra("aspectY", 3);
//        是否缩放
        intent.putExtra("scale", true);
//        设置图片的大小,提高头像的上传速度
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
//        以Uri的方式传递照片
        File cropFile = new File(getFilePath() + "crop.jpg");
        cropFileUri = Uri.fromFile(cropFile);
//        把裁剪好的图片保存到这个路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropFileUri);

        startActivityForResult(intent, CROP_REQUEST);


    }
 
Example 5
Project: chat-sdk-android-push-firebase   File: CatchImageClickListener.java   Source Code and License 6 votes vote down vote up
private void catchIntent(){
    if (file == null)
        throw new NullPointerException("You need to set the file you want to save the image in.");

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    selectedFilePath = file.getPath();
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

    if (activity==null)
        return;

    // start the image capture Intent
    if (dialogFragment != null)
        activity.startActivityFromFragment(dialogFragment, intent, requestCode);
    else if (fragment!= null)
        activity.startActivityFromFragment(fragment, intent, requestCode);
    else activity.startActivityForResult(intent, requestCode);
}
 
Example 6
Project: PlusGram   File: AvatarUpdater.java   Source Code and License 6 votes vote down vote up
public void openCamera() {
    try {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File image = AndroidUtilities.generatePicturePath();
        if (image != null) {
            if (Build.VERSION.SDK_INT >= 24) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(parentFragment.getParentActivity(), BuildConfig.APPLICATION_ID + ".provider", image));
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
            }
            currentPicturePath = image.getAbsolutePath();
        }
        parentFragment.startActivityForResult(takePictureIntent, 13);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}
 
Example 7
Project: Matisse   File: AlbumLoader.java   Source Code and License 6 votes vote down vote up
@Override
public Cursor loadInBackground() {
    Cursor albums = super.loadInBackground();
    MatrixCursor allAlbum = new MatrixCursor(COLUMNS);
    int totalCount = 0;
    String allAlbumCoverPath = "";
    if (albums != null) {
        while (albums.moveToNext()) {
            totalCount += albums.getInt(albums.getColumnIndex(COLUMN_COUNT));
        }
        if (albums.moveToFirst()) {
            allAlbumCoverPath = albums.getString(albums.getColumnIndex(MediaStore.MediaColumns.DATA));
        }
    }
    allAlbum.addRow(new String[]{Album.ALBUM_ID_ALL, Album.ALBUM_ID_ALL, Album.ALBUM_NAME_ALL, allAlbumCoverPath,
            String.valueOf(totalCount)});

    return new MergeCursor(new Cursor[]{allAlbum, albums});
}
 
Example 8
Project: SharePanel   File: Utils.java   Source Code and License 6 votes vote down vote up
public static String getPathOfImage(Context context, Uri uri) throws URISyntaxException {
    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
    if (cursor.moveToFirst()) {
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        if (cursor.moveToFirst()) {
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            cursor.close();
            return path;
        } else return null;
    } else return null;
}
 
Example 9
Project: OSS-green-07   File: CardNewsPagerAdapter.java   Source Code and License 6 votes vote down vote up
public Object instantiateItem(ViewGroup container, int position){
    View v = inflater.inflate(R.layout.viewpager_image,null);
    ImageView imgView = (ImageView) v.findViewById(R.id.viewPagerImage);
    //이미지를 가져옴
    Uri uri = Uri.fromFile(new File(cards.get(position)));

    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(inflater.getContext().getContentResolver(),uri);
        int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);

        imgView.setImageBitmap(scaled);

    } catch (IOException e) {
        e.printStackTrace();
    }
    container.addView(v);

    return v;
}
 
Example 10
Project: Sega   File: ImagePickerActivity.java   Source Code and License 6 votes vote down vote up
/**
 * Start camera intent
 * Create a temporary file and pass file Uri to camera intent
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        File imageFile = ImageUtils.createImageFile(imageDirectory);
        if (imageFile != null) {
            String authority = getPackageName() + ".fileprovider";
            Uri uri = FileProvider.getUriForFile(this, authority, imageFile);
            currentImagePath = "file:" + imageFile.getAbsolutePath();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, Constants.REQUEST_CODE_CAPTURE);
        } else {
            Toast.makeText(this, getString(R.string.error_create_image_file), Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, getString(R.string.error_no_camera), Toast.LENGTH_LONG).show();
    }
}
 
Example 11
Project: nat-camera   File: CameraModule.java   Source Code and License 6 votes vote down vote up
public void captureVideo(Activity activity, final ModuleResultListener listener) {
    if (mIsTakingVideo) {
        listener.onResult(Util.getError(Constant.CAMERA_BUSY, Constant.CAMERA_BUSY_CODE));
        return;
    }

    mCaptureVideoStartTime = System.currentTimeMillis();
    mIsTakingVideo = true;
    String fileName = "nat_video_" + new Date().getTime() + ".mov";
    Intent intent = new Intent();
    intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    try {
        videoFile = Util.getFile(fileName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Uri uri = Uri.fromFile(videoFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    activity.startActivityForResult(intent, Constant.VIDEO_REQUEST_CODE);
}
 
Example 12
Project: QNewsDemo   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
public void handleImageOnKitKat(Intent data) {
    String imagePath=null;
    Uri uri=data.getData();
    if (DocumentsContract.isDocumentUri(this,uri)){
        //如果是document类型的Uri,则通过document id处理
        String docId=DocumentsContract.getDocumentId(uri);
        if ("com.android.providers.media.documents".equals(uri.getAuthority())){
            String id=docId.split(":")[1];//解析数字可是的id
            String selection=MediaStore.Images.Media._ID+"="+id;
            imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);

        }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
            Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/punlic_downloads"),Long.valueOf(docId));
            imagePath=getImagePath(contentUri,null);
        }
    }else if ("content".equalsIgnoreCase(uri.getScheme())){
        //如果是content类型的Uri,则使用普通方法
        imagePath=getImagePath(uri,null);
    }else  if ("file".equalsIgnoreCase(uri.getScheme())){
        imagePath=uri.getPath();
    }
    displayImage(imagePath);//根据图片路径显示图片
}
 
Example 13
Project: nat-camera   File: CameraModule.java   Source Code and License 6 votes vote down vote up
public void captureImage(Activity activity, final ModuleResultListener listener){
    if (mIsTakingPhoto) {
        listener.onResult(Util.getError(Constant.CAMERA_BUSY, Constant.CAMERA_BUSY_CODE));
        return;
    }
    mCaptureImgStartTime = System.currentTimeMillis();

    mIsTakingPhoto = true;

    String fileName = "nat_img_" + new Date().getTime() + ".jpg";
    Intent intent = new Intent();
    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    try {
        finalImageFile = Util.getFile(fileName);
    } catch (IOException e) {
        e.printStackTrace();
        listener.onResult(Util.getError(Constant.CAMERA_INTERNAL_ERROR, Constant.CAMERA_INTERNAL_ERROR_CODE));
    }
    Uri uri = Uri.fromFile(finalImageFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

    activity.startActivityForResult(intent, Constant.IMAGE_REQUEST_CODE);
}
 
Example 14
Project: TakingPhotosSimply   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void dispatchTakePictureIntentTest3() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile(false);
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.ge.droid.takingphotossimply.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PICTURE_TEST_3);
        }
    }
}
 
Example 15
Project: MyCalendar   File: FunctionHelper.java   Source Code and License 6 votes vote down vote up
public static String getRealPathFromURI(Context context, Uri contentURI) throws Exception {
    String result;
    String[] proj = {MediaStore.Images.Media.DATA};
    try {
        Cursor cursor = context.getContentResolver().query(contentURI, proj, null, null, null);
        if (cursor == null || cursor.getCount() == 0) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            result = cursor.getString(idx);
            if (result == null) {
                result = contentURI.getPath();
            }
            cursor.close();
        }
        return result;
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }
}
 
Example 16
Project: Paprika   File: FileUtils.java   Source Code and License 6 votes vote down vote up
public static String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] projection = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return null;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
 
Example 17
Project: Custom-Vison-Service   File: MainActivity.java   Source Code and License 6 votes vote down vote up
public void openGallery() {
    Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
    getIntent.setType("image/*");

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

    Intent chooserIntent = Intent.createChooser(getIntent, "Select An Image");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});

    startActivityForResult(chooserIntent, SELECT_PICTURE);
}
 
Example 18
Project: android-titanium-imagecropper   File: CropImage.java   Source Code and License 6 votes vote down vote up
/** Get all Camera intents for capturing image using device camera apps. */
public static List<Intent> getCameraIntents(
    @NonNull Context context, @NonNull PackageManager packageManager) {

  List<Intent> allIntents = new ArrayList<>();

  // Determine Uri of camera image to  save.
  Uri outputFileUri = getCaptureImageOutputUri(context);

  Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
  for (ResolveInfo res : listCam) {
    Intent intent = new Intent(captureIntent);
    intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
    intent.setPackage(res.activityInfo.packageName);
    if (outputFileUri != null) {
      intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    }
    allIntents.add(intent);
  }

  return allIntents;
}
 
Example 19
Project: android-ringtone-picker   File: RingtoneUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Get the title of the ringtone from the uri of ringtone.
 *
 * @param context instance of the caller
 * @param uri     uri of the tone to search
 * @return title of the tone or return null if no tone found.
 */
@Nullable
public static String getRingtoneName(@NonNull Context context,
                                     @NonNull Uri uri) {
    Ringtone ringtone = RingtoneManager.getRingtone(context, uri);
    if (ringtone != null) {
        return ringtone.getTitle(context);
    } else {
        Cursor cur = context
                .getContentResolver()
                .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Audio.Media.TITLE},
                        MediaStore.Audio.Media._ID + " =?",
                        new String[]{uri.getLastPathSegment()},
                        null);

        String title = null;
        if (cur != null) {
            title = cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE));
            cur.close();
        }
        return title;
    }
}
 
Example 20
Project: TripBuyer   File: UploadAirTicketActivity.java   Source Code and License 6 votes vote down vote up
/**
     * 启动手机相册
     */
    private void fromGallery() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_NAME)));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            startActivityForResult(intent, GALLERY_KITKAT_REQUEST);
        } else {
            startActivityForResult(intent, GALLERY_REQUEST);
        }

//        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        startActivityForResult(intent, 103);103
    }
 
Example 21
Project: mobile-app-dev-book   File: JournalViewActivity.java   Source Code and License 6 votes vote down vote up
@OnClick(R.id.fab_add_video)
public void do_add_video()
{
    Intent capture = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    if (capture.resolveActivity(getPackageManager()) != null) {
        try {
            File videoFile = createFileName("traxyvid", ".mp4");
            mediaUri = FileProvider.getUriForFile(this,
                    getPackageName() + ".provider", videoFile);
            capture.putExtra(MediaStore.EXTRA_OUTPUT, mediaUri);
            startActivityForResult(capture, CAPTURE_VIDEO_REQUEST);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 22
Project: yyox   File: ImageSelectorFragment.java   Source Code and License 6 votes vote down vote up
/**
 * 选择相机
 */
private void showCameraAction() {
    // 跳转到系统照相机
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        // 设置系统相机拍照后的输出路径
        // 创建临时文件
        try {
            mTmpFile = FileUtils.createTmpFile(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mTmpFile != null && mTmpFile.exists()) {
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
            startActivityForResult(cameraIntent, REQUEST_CAMERA);
        } else {
            Toast.makeText(getActivity(), getString(R.string.kf5_image_error), Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(getActivity(), getResources().getString(R.string.kf5_no_camera_hint), Toast.LENGTH_SHORT).show();
    }
}
 
Example 23
Project: Tusky   File: ComposeActivity.java   Source Code and License 6 votes vote down vote up
private void initiateCameraApp() {
    // We don't need to ask for permission in this case, because the used calls require
    // android.permission.WRITE_EXTERNAL_STORAGE only on SDKs *older* than Kitkat, which was
    // way before permission dialogues have been introduced.
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createNewImageFile();
        } catch (IOException ex) {
            displayTransientError(R.string.error_media_upload_opening);
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            photoUploadUri = FileProvider.getUriForFile(this,
                    "com.keylesspalace.tusky.fileprovider",
                    photoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUploadUri);
            startActivityForResult(intent, MEDIA_TAKE_PHOTO_RESULT);
        }
    }
}
 
Example 24
Project: Raffler-Android   File: RegisterUserActivity.java   Source Code and License 6 votes vote down vote up
private void cameraIntent() throws IOException
{
    if (checkPermissions()){

        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();
        String file = dir+"profile.jpg";
        File newfile = new File(file);
        try {
            newfile.createNewFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        mCurrentPhotoPath = Uri.fromFile(newfile);

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoPath);
        startActivityForResult(takePictureIntent, REQUEST_CAMERA);
    }
}
 
Example 25
Project: SSTVEncoder2   File: MainActivity.java   Source Code and License 6 votes vote down vote up
public int getOrientation(ContentResolver resolver, Uri uri) {
    int orientation = 0;
    try {
        Cursor cursor = resolver.query(uri, new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, null, null, null);
        if (cursor.moveToFirst())
            orientation = cursor.getInt(0);
        cursor.close();
    } catch (Exception ignore) {
        try {
            ExifInterface exif = new ExifInterface(uri.getPath());
            orientation = Utility.convertToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0));
        } catch (Exception ex) {
            showOrientationErrorMessage(uri, ex);
        }
    }
    return orientation;
}
 
Example 26
Project: AmenEye   File: ChoosePhotoActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 拍照
 */
private void takePhoto() {
    try {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File file = new File(ViewUtil.getAppFile(this, "images"));
        File mPhotoFile = new File(ViewUtil.getAppFile(this, "images/user_take.jpg"));
        if (!file.exists()) {
            boolean result = file.mkdirs();
            if (!mPhotoFile.exists()) {
                boolean b = mPhotoFile.createNewFile();
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, "cn.aaronyi.ameneye.fileprovider", mPhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
        }
        startActivityForResult(intent, ACTION_TAKE_PHOTO);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 27
Project: Simpler   File: ImageSelectFragment.java   Source Code and License 6 votes vote down vote up
private void showCameraAction() {
    if (config.maxNum <= Global.imageList.size()) {
        AppToast.showToast(String.format(getString(R.string.max_num), config.maxNum));
        return;
    }

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE);
        return;
    }

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        tempFile = new File(FileUtils.getRootPath(getActivity()) + File.separator
                + getActivity().getString(R.string.app_name) + "_" + System.currentTimeMillis() + ".jpg");
        // 创建临时照片文件
        FileUtils.createFile(tempFile);

        Uri uri = FileProvider.getUriForFile(getActivity(), FileUtils.getApplicationId(getActivity()) + ".provider", tempFile);

        List<ResolveInfo> resInfoList = getActivity().getPackageManager()
                .queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            getActivity().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(cameraIntent, REQUEST_CAMERA);
    } else {
        AppToast.showToast(R.string.open_camera_failure);
    }
}
 
Example 28
Project: Hello-Music-droid   File: PlaylistSongLoader.java   Source Code and License 6 votes vote down vote up
private static int countPlaylist(final Context context, final long playlistId) {
    Cursor c = null;
    try {
        c = context.getContentResolver().query(
                MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId),
                new String[]{
                        MediaStore.Audio.Playlists.Members.AUDIO_ID,
                }, null, null,
                MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);

        if (c != null) {
            return c.getCount();
        }
    } finally {
        if (c != null) {
            c.close();
            c = null;
        }
    }

    return 0;
}
 
Example 29
Project: Android-Music-Player   File: artitstBtns.java   Source Code and License 6 votes vote down vote up
int[] getArtistsAIDs(){

        String searchString = MediaStore.Audio.Media.IS_MUSIC + "=?" + "AND " + MediaStore.Audio.Media.ARTIST_ID + " = " + data[1];
        String[] searchPram = new String[]{"1"};
        String[] cols = new String[] {MediaStore.Audio.Media._ID};
        Cursor cursor = Ui.ef.getBaseContext().getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,cols, searchString  ,searchPram,null);
        int[] AIDs = new int[cursor.getCount()];
        int count = 0;
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            AIDs[count] = cursor.getInt(0);
            count++;
        }
        cursor.close();
        return  AIDs;

    }
 
Example 30
Project: GCSApp   File: MyInfoActivity.java   Source Code and License 6 votes vote down vote up
public void takePicture() {
    try {
        mPhotoPath = sdcardPath + "/icon.jpg";
        mPhotoFile = new File(mPhotoPath);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (Build.VERSION.SDK_INT >= 23) {
            Uri uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", mPhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        } else {

            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
        }
        startActivityForResult(intent, 1);

    } catch (Exception e) {
    }



}
 
Example 31
Project: GitHub   File: LocalContentUriFetchProducer.java   Source Code and License 6 votes vote down vote up
private @Nullable EncodedImage getCameraImage(Uri uri) throws IOException {
  Cursor cursor = mContentResolver.query(uri, PROJECTION, null, null, null);
  if (cursor == null) {
    return null;
  }
  try {
    if (cursor.getCount() == 0) {
      return null;
    }
    cursor.moveToFirst();
    final String pathname =
        cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
    if (pathname != null) {
      return getEncodedImage(new FileInputStream(pathname), getLength(pathname));
    }
  } finally {
    cursor.close();
  }
  return null;
}
 
Example 32
Project: KTools   File: ImageActivity.java   Source Code and License 6 votes vote down vote up
private void handleAlbumData(Intent data) {
    Uri uri = data.getData();
    String[] projection = new String[]{
            MediaStore.Images.Media.DATA
    };

    Cursor cursor = getContentResolver().query(
            uri,
            projection,
            null,
            null,
            null
    );
    if (cursor != null && cursor.moveToFirst()) {
        int dataIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        String imagePath = cursor.getString(dataIndex);
        cursor.close();
        showBitmap(imagePath);
    }

}
 
Example 33
Project: PlusGram   File: CameraController.java   Source Code and License 6 votes vote down vote up
public void stopVideoRecording(CameraSession session, boolean abandon) {
    try {
        CameraInfo info = session.cameraInfo;
        Camera camera = info.camera;
        if (camera != null && recorder != null) {
            MediaRecorder tempRecorder = recorder;
            recorder = null;
            tempRecorder.stop();
            tempRecorder.release();
            camera.reconnect();
            camera.startPreview();
            session.stopVideoRecording();
        }
        if (!abandon) {
            final Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(recordedFile, MediaStore.Video.Thumbnails.MINI_KIND);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    onVideoTakeCallback.onFinishVideoRecording(bitmap);
                }
            });
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}
 
Example 34
Project: GitHub   File: LocalVideoThumbnailProducerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testLocalVideoMicroThumbnailReturnsNull() throws Exception {
  when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true);
  when(
      android.media.ThumbnailUtils.createVideoThumbnail(
          mFile.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND))
      .thenReturn(null);
  mLocalVideoThumbnailProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();
  verify(mConsumer).onNewResult(null, Consumer.IS_LAST);
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  Map<String, String> thumbnailNotFoundMap =
      ImmutableMap.of(LocalVideoThumbnailProducer.CREATED_THUMBNAIL, "false");
  verify(mProducerListener).onProducerFinishWithSuccess(
      mRequestId, PRODUCER_NAME, thumbnailNotFoundMap);
  verify(mProducerListener).onUltimateProducerReached(mRequestId, PRODUCER_NAME, false);
}
 
Example 35
Project: PeSanKita-android   File: AttachmentManager.java   Source Code and License 6 votes vote down vote up
public void capturePhoto(Activity activity, int requestCode) {
  try {
    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (captureIntent.resolveActivity(activity.getPackageManager()) != null) {
      if (captureUri == null) {
        captureUri = PersistentBlobProvider.getInstance(context)
                                           .createForExternal(ContentType.IMAGE_JPEG);
      }
      Log.w(TAG, "captureUri path is " + captureUri.getPath());
      captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri);
      activity.startActivityForResult(captureIntent, requestCode);
    }
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
  }
}
 
Example 36
Project: Sendroid   File: ImageDecorder.java   Source Code and License 6 votes vote down vote up
protected InputStream getStreamFromContent(String imageUri) throws FileNotFoundException {
    ContentResolver res = context.getContentResolver();
    Uri uri = Uri.parse(imageUri);
    if (isVideoContentUri(uri)) { // video thumbnail
        Long origId = Long.valueOf(uri.getLastPathSegment());
        Bitmap bitmap = MediaStore.Video.Thumbnails
                .getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
        if (bitmap != null) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
            return new ByteArrayInputStream(bos.toByteArray());
        }
    } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo
        return getContactPhotoStream(uri);
    }

    return res.openInputStream(uri);
}
 
Example 37
Project: localcloud_fe   File: CameraLauncher.java   Source Code and License 6 votes vote down vote up
/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *
 * @param type FILE_URI or DATA_URL
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
        cursor.close();
    }
}
 
Example 38
Project: GitHub   File: BaseImageDownloader.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}).
 *
 * @param imageUri Image URI
 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws FileNotFoundException if the provided URI could not be opened
 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
	ContentResolver res = context.getContentResolver();

	Uri uri = Uri.parse(imageUri);
	if (isVideoContentUri(uri)) { // video thumbnail
		Long origId = Long.valueOf(uri.getLastPathSegment());
		Bitmap bitmap = MediaStore.Video.Thumbnails
				.getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
		if (bitmap != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 0, bos);
			return new ByteArrayInputStream(bos.toByteArray());
		}
	} else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo
		return getContactPhotoStream(uri);
	}

	return res.openInputStream(uri);
}
 
Example 39
Project: robird-reborn   File: ComposeFragment.java   Source Code and License 6 votes vote down vote up
private void pickImage() {
    if (mAttachedImages.size() < MAX_ATTACHED_IMAGE_COUNT) {
        try {
            Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
            pickIntent.setType("image/*");

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                pickIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
            }

            mCameraImageUri = Uri.fromFile(ImageUtils.createNewImageFile());
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraImageUri);

            Intent chooserIntent = Intent.createChooser(pickIntent, getString(R.string.app_name));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takePhotoIntent});

            startActivityForResult(chooserIntent, IMAGE_REQUEST_CODE);
        } catch (IOException e) {
            Timber.w(e, "Exception while starting image picker in compose screen.");
        }
    }
}
 
Example 40
Project: AgentWebX5   File: AgentWebX5Utils.java   Source Code and License 5 votes vote down vote up
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    String[] projection = {MediaStore.Images.Media.DATA};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 41
Project: COB   File: CameraLauncher.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a cursor that can be used to determine how many images we have.
 *
 * @return a cursor
 */
private Cursor queryImgDB(Uri contentStore) {
    return this.cordova.getActivity().getContentResolver().query(
            contentStore,
            new String[]{MediaStore.Images.Media._ID},
            null,
            null,
            null);
}
 
Example 42
Project: COB   File: CameraLauncher.java   Source Code and License 5 votes vote down vote up
/**
 * Determine if we are storing the images in internal or external storage
 *
 * @return Uri
 */
private Uri whichContentStore() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else {
        return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
    }
}
 
Example 43
Project: Rey-MusicPlayer   File: CursorHelper.java   Source Code and License 5 votes vote down vote up
public static Cursor makeAlbumCursor(Context context, String selection, String[] paramArrayOfString) {
    String sort = PreferencesHelper.getInstance().getString(PreferencesHelper.Key.ALBUM_SORT_ORDER, SortOrder.AlbumSortOrder.ALBUM_DEFAULT)
            + PreferencesHelper.getInstance().getString(PreferencesHelper.Key.ALBUM_SORT_TYPE, Constants.ASCENDING);
    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[]{
            "_id", "album", "artist", "album_art"}, selection, paramArrayOfString, sort);
    return cursor;
}
 
Example 44
Project: PictureShow   File: PicShowUtils.java   Source Code and License 5 votes vote down vote up
public static boolean renameItem(Context ctx, Uri uri, boolean image, String newName) {
    Cursor c = ctx.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA},
            null, null,null);
    String absPath = null;
    String newFilePath = null;
    if(c != null && c.moveToNext())
        absPath = c.getString(0);

    boolean result = false;
    if(absPath != null) {
        File f = new File(absPath);
        if(f.exists()) {
            int index = absPath.lastIndexOf(".");
            String reg = absPath.substring(index);
            String newFileName = newName + reg;
            File p = f.getParentFile();
            File newFile = new File(p, newFileName);
            newFilePath = newFile.getAbsolutePath();
            result = f.renameTo(newFile);
        }
    }
    if(result) {
        ContentValues cv = new ContentValues();
        cv.put(MediaStore.Files.FileColumns.TITLE, newName);
        cv.put(MediaStore.Files.FileColumns.DATA, newFilePath == null ? "" : newFilePath);
        result = ctx.getContentResolver().update(uri, cv, null, null) > 0;
    }

    return result;
}
 
Example 45
Project: PSNine   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static File getImageFile(Context context, Uri selectedImage) {
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String imagePath = cursor.getString(columnIndex);
    cursor.close();
    return new File(imagePath);
}
 
Example 46
Project: COB   File: CameraLauncher.java   Source Code and License 5 votes vote down vote up
/**
 * Determine if we are storing the images in internal or external storage
 *
 * @return Uri
 */
private Uri whichContentStore() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else {
        return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
    }
}
 
Example 47
Project: Watermark   File: MediaUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 根据地址获取视频相关信息
 */
public static MediaBean getMediaBeanWithVideo(Context context, String originalPath) {
    ContentResolver contentResolver = context.getContentResolver();
    List<String> projection = new ArrayList<>();
    projection.add(MediaStore.Video.Media._ID);
    projection.add(MediaStore.Video.Media.TITLE);
    projection.add(MediaStore.Video.Media.DATA);
    projection.add(MediaStore.Video.Media.BUCKET_ID);
    projection.add(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
    projection.add(MediaStore.Video.Media.MIME_TYPE);
    projection.add(MediaStore.Video.Media.DATE_ADDED);
    projection.add(MediaStore.Video.Media.DATE_MODIFIED);
    projection.add(MediaStore.Video.Media.LATITUDE);
    projection.add(MediaStore.Video.Media.LONGITUDE);
    projection.add(MediaStore.Video.Media.SIZE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        projection.add(MediaStore.Video.Media.WIDTH);
        projection.add(MediaStore.Video.Media.HEIGHT);
    }
    Cursor cursor = contentResolver.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            projection.toArray(new String[projection.size()]),
            MediaStore.Images.Media.DATA + "=?",
            new String[]{originalPath}, null);
    MediaBean mediaBean = null;
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        mediaBean = parseVideoCursorAndCreateThumImage(context, cursor);
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    return mediaBean;
}
 
Example 48
Project: android-util2   File: GetImagePath.java   Source Code and License 5 votes vote down vote up
public static String getPath(Context context, Uri inputUri) {
    String temp = inputUri.toString();
    if(temp.startsWith("file://")){
        return temp.substring("file://".length());
    }

    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(context,
            inputUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
 
Example 49
Project: container   File: BroadcastIntent.java   Source Code and License 5 votes vote down vote up
@Override
public Object call(Object who, Method method, Object... args) throws Throwable {
    Intent intent = (Intent) args[1];
    String type = (String) args[2];
    intent.setDataAndType(redirectData(intent.getData()), type);
    if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) && intent.getData() != null) {
        ContentValues values = new ContentValues(2);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(intent.getDataString()));
        values.put("mime_type", mime);
        values.put("_data", intent.getData().getPath());
        VLog.d(getName(), "try " + values);
        if (mime.startsWith("image"))
            VirtualCore.get().getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        else if (mime.startsWith("video"))
            VirtualCore.get().getContext().getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        else if (mime.startsWith("audio"))
            VirtualCore.get().getContext().getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
    }
    if (VirtualCore.get().getComponentDelegate() != null) {
        if (!VirtualCore.get().getComponentDelegate().onSendBroadcast(intent)) return null;
    }
    Intent newIntent = handleIntent(intent);
    if (newIntent != null) {
        args[1] = newIntent;
    } else {
        return 0;
    }

    if (args[7] instanceof String || args[7] instanceof String[]) {
        // clear the permission
        args[7] = null;
    }
    VLog.d(getName(), "broadcast " + intent);
    return method.invoke(who, args);
}
 
Example 50
Project: RLibrary   File: ImagePicker.java   Source Code and License 5 votes vote down vote up
/**
 * 录制视频
 */
public void recordVideo(Activity activity, int requestCode) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    takePictureIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {

        if (Utils.existSDCard())
            takeImageFile = new File(Environment.getExternalStorageDirectory(), "/DCIM/Video/");
        else takeImageFile = Environment.getDataDirectory();
        takeImageFile = createFile(takeImageFile, "Video_", ".mp4");
        if (takeImageFile != null) {
            Uri fileUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                fileUri = FileProvider.getUriForFile(activity, activity.getPackageName(), takeImageFile);
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                fileUri = Uri.fromFile(takeImageFile);
            }
            // 默认情况下,即不需要指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            // 照相机有自己默认的存储路径,拍摄的照片将返回一个缩略图。如果想访问原始图片,
            // 可以通过dat extra能够得到原始图片位置。即,如果指定了目标uri,data就没有数据,
            // 如果没有指定uri,则data就返回有数据!
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        }
    }
    activity.startActivityForResult(takePictureIntent, requestCode);
}
 
Example 51
Project: scab   File: ChoosePhotoActivity.java   Source Code and License 5 votes vote down vote up
public String getPath(Uri uri, Activity activity) {
    String[] projection = { MediaStore.MediaColumns.DATA };
    Cursor cursor = activity
            .managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
 
Example 52
Project: MyFire   File: FileUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 根据uri获取真文件路径
 * @param context
 * @param contentUri
 * @return
 */
static String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        String realPath = cursor.getString(index);
        cursor.close();
        return realPath;
    }
}
 
Example 53
Project: GitHub   File: ThumbFetcher.java   Source Code and License 5 votes vote down vote up
@Override
public Cursor query(Uri uri) {
  String videoId = uri.getLastPathSegment();
  return contentResolver.query(
      MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
      PATH_PROJECTION,
      PATH_SELECTION,
      new String[] {videoId},
      null /*sortOrder*/);
}
 
Example 54
Project: MusicX-music-player   File: Helper.java   Source Code and License 5 votes vote down vote up
/**
 * Set Ringtone
 *
 * @param context
 * @param path
 */
private static void setRingtone(Context context, String path) {
    if (path == null) {
        return;
    }
    File file = new File(path);
    ContentValues contentValues = new ContentValues();
    contentValues.put(MediaColumns.DATA, file.getAbsolutePath());
    String filterName = path.substring(path.lastIndexOf("/") + 1);
    contentValues.put(MediaColumns.TITLE, filterName);
    contentValues.put(MediaColumns.MIME_TYPE, "audio/mp3");
    contentValues.put(MediaColumns.SIZE, file.length());
    contentValues.put(Media.IS_RINGTONE, true);
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(path);
    Cursor cursor = context.getContentResolver().query(uri, null, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
    if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
        String id = cursor.getString(0);
        contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        context.getContentResolver().update(uri, contentValues, MediaStore.MediaColumns.DATA + "=?", new String[]{path});
        Uri newuri = ContentUris.withAppendedId(uri, Long.valueOf(id));
        try {
            RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newuri);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        cursor.close();
    }
}
 
Example 55
Project: AgentWeb   File: AgentWebUtils.java   Source Code and License 5 votes vote down vote up
static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    String[] projection = {MediaStore.Images.Media.DATA};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 56
Project: yaacc-code   File: MusicGenresFolderBrowser.java   Source Code and License 5 votes vote down vote up
private Integer getSize(YaaccContentDirectory contentDirectory, String myId){
	 Integer result = 0;
			String[] projection = { "count(*) as count" };
			String selection = "";
			String[] selectionArgs = null;
			Cursor cursor = contentDirectory.getContext().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, projection, selection,
					selectionArgs, null);

			if (cursor != null) {
				cursor.moveToFirst();
				result = Integer.valueOf(cursor.getString(0));
				cursor.close();
			}
			return result;
}
 
Example 57
Project: Rey-MusicPlayer   File: CursorHelper.java   Source Code and License 5 votes vote down vote up
public static ArrayList<Album> getAlbumsList() {

        String sort = PreferencesHelper.getInstance().getString(PreferencesHelper.Key.ALBUM_SORT_ORDER, SortOrder.AlbumSortOrder.ALBUM_DEFAULT)
                + PreferencesHelper.getInstance().getString(PreferencesHelper.Key.ALBUM_SORT_TYPE, Constants.ASCENDING);

        String[] columns = {
                MediaStore.Audio.Albums._ID,
                MediaStore.Audio.Albums.ALBUM,
                MediaStore.Audio.Albums.ARTIST,
                MediaStore.Audio.Albums.ALBUM_ART
        };
        Cursor cursor = Common.getInstance().getContentResolver().query(
                MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                columns,
                null,
                null,
                sort);

        ArrayList<Album> albums = new ArrayList<>();


        if (cursor != null && cursor.moveToFirst()) {
            do {
                Album album = new Album(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
                albums.add(album);
            } while (cursor.moveToNext());
        }

        if (cursor != null) {
            cursor.close();
        }
        return albums;

    }
 
Example 58
Project: FitAndroid7   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void takePhotoNoCompress() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            String filename = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA)
                    .format(new Date()) + ".png";
            File file = new File(Environment.getExternalStorageDirectory(), filename);
            mCurrentPhotoPath = file.getAbsolutePath();

            Uri fileUri = FileProvider7.getUriForFile(this, file);

            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
        }
    }
 
Example 59
Project: localcloud_fe   File: CameraLauncher.java   Source Code and License 5 votes vote down vote up
public void takePicture(int returnType, int encodingType)
    {
        // Save the number of images currently on disk for later
        this.numPics = queryImgDB(whichContentStore()).getCount();

        // Let's use the intent and see what happens
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // Specify file so that large image is captured and returned
        File photo = createCaptureFile(encodingType);
        this.imageUri = new CordovaUri(FileProvider.getUriForFile(cordova.getActivity(),
                applicationId + ".provider",
                photo));
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri.getCorrectUri());
        //We can write to this URI, this will hopefully allow us to write files to get to the next step
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        if (this.cordova != null) {
            // Let's check to make sure the camera is actually installed. (Legacy Nexus 7 code)
            PackageManager mPm = this.cordova.getActivity().getPackageManager();
            if(intent.resolveActivity(mPm) != null)
            {

                this.cordova.startActivityForResult((CordovaPlugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);
            }
            else
            {
                LOG.d(LOG_TAG, "Error: You don't have a default camera.  Your device may not be CTS complaint.");
            }
        }
//        else
//            LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
    }
 
Example 60
Project: RetroMusicPlayer   File: LastAddedSongsLoader.java   Source Code and License 5 votes vote down vote up
public static Cursor makeLastAddedCursor(@NonNull final Context context) {
    long cutoff = PreferenceUtil.getInstance(context).getLastAddedCutoff();

    return SongLoader.makeSongCursor(
            context,
            MediaStore.Audio.Media.DATE_ADDED + ">?",
            new String[]{String.valueOf(cutoff)},
            MediaStore.Audio.Media.DATE_ADDED + " DESC");
}