Example usage for android.net Uri fromFile

List of usage examples for android.net Uri fromFile

Introduction

In this page you can find the example usage for android.net Uri fromFile.

Prototype

public static Uri fromFile(File file) 

Source Link

Document

Creates a Uri from a file.

Usage

From source file:dentex.youtube.downloader.DashboardActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    BugSenseHandler.leaveBreadcrumb("DashboardActivity_onCreate");
    //Utils.logger("v", "TotalRxBeforeTest: " + TotalRxBeforeTest, DEBUG_TAG);

    // Theme init
    Utils.themeInit(this);

    setContentView(R.layout.activity_dashboard);

    // Language init
    Utils.langInit(this);

    // Detect screen orientation
    int or = this.getResources().getConfiguration().orientation;
    isLandscape = (or == 2) ? true : false;

    sDashboard = DashboardActivity.this;

    if (da != null) {
        clearAdapterAndLists();/*from   w w  w  . j a v a 2s.  com*/
    }

    countdown = 10;

    parseJson(this);
    updateProgressBars();
    buildList();

    lv = (ListView) findViewById(R.id.dashboard_list);

    da = new DashboardAdapter(itemsList, this);

    if (da.isEmpty()) {
        showEmptyListInfo(this);
    } else {
        lv.setAdapter(da);
    }

    /*Log.i(DEBUG_TAG, "ADML Maps:" +
     "\ndtMap:                 " + Maps.dtMap +
     "\nmDownloadPercentMap:   " + Maps.mDownloadPercentMap +
     "\nmDownloadSizeMap:      " + Maps.mDownloadSizeMap + 
     "\nmTotalSizeMap:         " + Maps.mTotalSizeMap);*/

    lv.setTextFilterEnabled(true);

    lv.setClickable(true);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            if (!isAnyAsyncInProgress) {
                currentItem = da.getItem(position); // in order to refer to the filtered item
                newClick = true;

                final boolean ffmpegEnabled = YTD.settings.getBoolean("enable_advanced_features", false);

                AlertDialog.Builder builder = new AlertDialog.Builder(boxThemeContextWrapper);
                builder.setTitle(currentItem.getFilename());

                if (currentItem.getStatus().equals(getString(R.string.json_status_completed))
                        || currentItem.getStatus().equals(getString(R.string.json_status_imported))) {

                    final boolean audioIsSupported = !currentItem.getAudioExt().equals("unsupported");
                    final File in = new File(currentItem.getPath(), currentItem.getFilename());

                    if (currentItem.getType().equals(YTD.JSON_DATA_TYPE_V)) {

                        // handle click on a **VIDEO** file entry
                        builder.setItems(R.array.dashboard_click_entries,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                        switch (which) {
                                        case 0: // open
                                            BugSenseHandler.leaveBreadcrumb("video_open");
                                            Intent openIntent = new Intent(Intent.ACTION_VIEW);
                                            openIntent.setDataAndType(Uri.fromFile(in), "video/*");
                                            startActivity(Intent.createChooser(openIntent,
                                                    getString(R.string.open_chooser_title)));
                                            break;
                                        case 1: // extract audio only
                                            if (!isFfmpegRunning) {
                                                BugSenseHandler.leaveBreadcrumb("video_ffmpeg_extract");
                                                if (audioIsSupported) {
                                                    if (ffmpegEnabled) {
                                                        AlertDialog.Builder builder0 = new AlertDialog.Builder(
                                                                boxThemeContextWrapper);
                                                        LayoutInflater inflater0 = getLayoutInflater();
                                                        final View view0 = inflater0
                                                                .inflate(R.layout.dialog_audio_extr_only, null);

                                                        String type = null;
                                                        if (currentItem.getAudioExt().equals(".aac"))
                                                            type = aac;
                                                        if (currentItem.getAudioExt().equals(".ogg"))
                                                            type = ogg;
                                                        if (currentItem.getAudioExt().equals(".mp3"))
                                                            type = mp3;
                                                        //if (currentItem.getAudioExt().equals(".auto")) type = aac_mp3;

                                                        TextView info = (TextView) view0
                                                                .findViewById(R.id.audio_extr_info);
                                                        info.setText(getString(R.string.audio_extr_info)
                                                                + "\n\n" + type);

                                                        builder0.setView(view0).setPositiveButton("OK",
                                                                new DialogInterface.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(DialogInterface dialog,
                                                                            int id) {

                                                                        CheckBox cb0 = (CheckBox) view0
                                                                                .findViewById(R.id.rem_video_0);
                                                                        removeVideo = cb0.isChecked();

                                                                        Utils.logger("v",
                                                                                "Launching FFmpeg on: " + in
                                                                                        + "\n-> mode: extraction only"
                                                                                        + "\n-> remove video: "
                                                                                        + removeVideo,
                                                                                DEBUG_TAG);

                                                                        ffmpegJob(in, null, null);
                                                                    }
                                                                }).setNegativeButton(R.string.dialogs_negative,
                                                                        new DialogInterface.OnClickListener() {
                                                                            public void onClick(
                                                                                    DialogInterface dialog,
                                                                                    int id) {
                                                                                // cancel
                                                                            }
                                                                        });

                                                        secureShowDialog(builder0);
                                                    } else {
                                                        notifyFfmpegNotInstalled();
                                                    }
                                                } else {
                                                    notifyOpsNotSupported();
                                                }
                                            } else {
                                                notifyFfmpegIsAlreadyRunning();
                                            }

                                            break;
                                        case 2: // extract audio and convert to mp3
                                            if (!isFfmpegRunning) {
                                                BugSenseHandler.leaveBreadcrumb("video_ffmpeg_mp3");
                                                if (audioIsSupported) {
                                                    if (ffmpegEnabled) {
                                                        AlertDialog.Builder builder1 = new AlertDialog.Builder(
                                                                boxThemeContextWrapper);
                                                        LayoutInflater inflater1 = getLayoutInflater();

                                                        final View view1 = inflater1.inflate(
                                                                R.layout.dialog_audio_extr_mp3_conv, null);

                                                        builder1.setView(view1).setPositiveButton("OK",
                                                                new DialogInterface.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(DialogInterface dialog,
                                                                            int id) {

                                                                        final Spinner sp = (Spinner) view1
                                                                                .findViewById(R.id.mp3_spinner);
                                                                        String[] bitrateData = retrieveBitrateValueFromSpinner(
                                                                                sp);

                                                                        CheckBox cb1 = (CheckBox) view1
                                                                                .findViewById(R.id.rem_video_1);
                                                                        removeVideo = cb1.isChecked();

                                                                        Utils.logger("v",
                                                                                "Launching FFmpeg on: " + in
                                                                                        + "\n-> mode: conversion to mp3 from video file"
                                                                                        + "\n-> remove video: "
                                                                                        + removeVideo,
                                                                                DEBUG_TAG);

                                                                        ffmpegJob(in, bitrateData[0],
                                                                                bitrateData[1]);
                                                                    }
                                                                }).setNegativeButton(R.string.dialogs_negative,
                                                                        new DialogInterface.OnClickListener() {
                                                                            public void onClick(
                                                                                    DialogInterface dialog,
                                                                                    int id) {
                                                                                //
                                                                            }
                                                                        });

                                                        secureShowDialog(builder1);
                                                    } else {
                                                        notifyFfmpegNotInstalled();
                                                    }
                                                } else {
                                                    notifyOpsNotSupported();
                                                }
                                            } else {
                                                notifyFfmpegIsAlreadyRunning();
                                            }
                                        }
                                    }
                                });

                        secureShowDialog(builder);

                    } else if (currentItem.getType().equals(YTD.JSON_DATA_TYPE_A_E)
                            || currentItem.getType().equals(YTD.JSON_DATA_TYPE_A_M)) {

                        // handle click on a **AUDIO** file entry
                        builder.setItems(R.array.dashboard_click_entries_audio,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                        switch (which) {
                                        case 0: // open
                                            BugSenseHandler.leaveBreadcrumb("audio_open");
                                            Intent openIntent = new Intent(Intent.ACTION_VIEW);
                                            openIntent.setDataAndType(Uri.fromFile(in), "audio/*");
                                            startActivity(Intent.createChooser(openIntent,
                                                    getString(R.string.open_chooser_title)));
                                            break;
                                        case 1: // convert to mp3
                                            if (!isFfmpegRunning) {
                                                if (ffmpegEnabled) {
                                                    BugSenseHandler.leaveBreadcrumb("audio_ffmpeg_mp3");
                                                    AlertDialog.Builder builder0 = new AlertDialog.Builder(
                                                            boxThemeContextWrapper);
                                                    LayoutInflater inflater0 = getLayoutInflater();
                                                    final View view2 = inflater0
                                                            .inflate(R.layout.dialog_audio_mp3_conv, null);

                                                    builder0.setView(view2).setPositiveButton("OK",
                                                            new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog,
                                                                        int id) {

                                                                    final Spinner sp = (Spinner) view2
                                                                            .findViewById(R.id.mp3_spinner_a);
                                                                    String[] bitrateData = retrieveBitrateValueFromSpinner(
                                                                            sp);

                                                                    CheckBox cb2 = (CheckBox) view2
                                                                            .findViewById(
                                                                                    R.id.rem_original_audio);
                                                                    removeAudio = cb2.isChecked();

                                                                    Utils.logger("v", "Launching FFmpeg on: "
                                                                            + in
                                                                            + "\n-> mode: conversion to mp3 from audio file"
                                                                            + "\n-> remove audio: "
                                                                            + removeAudio, DEBUG_TAG);

                                                                    ffmpegJob(in, bitrateData[0],
                                                                            bitrateData[1]);
                                                                }
                                                            }).setNegativeButton(R.string.dialogs_negative,
                                                                    new DialogInterface.OnClickListener() {
                                                                        public void onClick(
                                                                                DialogInterface dialog,
                                                                                int id) {
                                                                            //
                                                                        }
                                                                    });

                                                    secureShowDialog(builder0);
                                                } else {
                                                    notifyFfmpegNotInstalled();
                                                }
                                            } else {
                                                notifyFfmpegIsAlreadyRunning();
                                            }
                                        }
                                    }
                                });

                        secureShowDialog(builder);
                    }
                } /*else if (currentItem.getStatus().equals(getString(R.string.json_status_imported))) {
                   Utils.logger("v", "IMPORTED video clicked", DEBUG_TAG);
                           
                   // handle click on an  **IMPORTED VIDEO** entry
                   builder.setItems(R.array.dashboard_click_entries_imported, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                          
                   final File in = new File (currentItem.getPath(), currentItem.getFilename());
                           
                   switch (which) {
                   case 0: // open
                      Intent openIntent = new Intent(Intent.ACTION_VIEW);
                      openIntent.setDataAndType(Uri.fromFile(in), "video/*");
                      startActivity(Intent.createChooser(openIntent, getString(R.string.open_chooser_title)));
                      break;
                   }
                    }
                   });
                          
                   secureShowDialog(builder);
                  }*/
            }
        }
    });

    lv.setLongClickable(true);
    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

            if (!isAnyAsyncInProgress) {
                currentItem = da.getItem(position); // in order to refer to the filtered item

                int COPY = 0;
                int MOVE = 1;
                int RENAME = 2;
                int REDOWNLOAD = 3;
                int REMOVE = 4;
                int DELETE = 5;
                int PAUSERESUME = 6;

                int[] disabledItems = null;

                if (currentItem.getStatus().equals(getString(R.string.json_status_in_progress))
                        || currentItem.getStatus().equals(getString(R.string.json_status_paused))) {
                    // show: DELETE and  PAUSERESUME
                    disabledItems = new int[] { COPY, MOVE, RENAME, REDOWNLOAD, REMOVE };
                } else if (currentItem.getStatus().equals(getString(R.string.json_status_failed))) {
                    // check if the item has a real YouTube ID, otherwise it's an imported video.
                    if (currentItem.getYtId().length() == 11) {
                        // show: REMOVE and REDOWNLOAD
                        disabledItems = new int[] { COPY, MOVE, RENAME, DELETE, PAUSERESUME };
                    } else {
                        // show: REMOVE only
                        disabledItems = new int[] { COPY, MOVE, RENAME, REDOWNLOAD, DELETE, PAUSERESUME };
                    }

                } else if (currentItem.getStatus().equals(getString(R.string.json_status_imported)) ||
                //case for audio entries _completed but from _imported
                (currentItem.getStatus().equals(getString(R.string.json_status_completed))
                        && !(currentItem.getYtId().length() == 11))) {
                    // show: COPY, MOVE, RENAME, REMOVE and DELETE
                    disabledItems = new int[] { REDOWNLOAD, PAUSERESUME };
                } else if (currentItem.getStatus().equals(getString(R.string.json_status_completed))) {
                    // show: all items except PAUSERESUME
                    disabledItems = new int[] { PAUSERESUME };
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(boxThemeContextWrapper);
                builder.setTitle(currentItem.getFilename());

                final ArrayAdapter<CharSequence> cla = DashboardLongClickAdapter.createFromResource(
                        boxThemeContextWrapper, R.array.dashboard_long_click_entries,
                        android.R.layout.simple_list_item_1, disabledItems);

                builder.setAdapter(cla, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0:
                            BugSenseHandler.leaveBreadcrumb("copy");
                            copy(currentItem);
                            break;
                        case 1:
                            BugSenseHandler.leaveBreadcrumb("move");
                            move(currentItem);
                            break;
                        case 2:
                            BugSenseHandler.leaveBreadcrumb("rename");
                            rename(currentItem);
                            break;
                        case 3:
                            if (currentItem.getStatus().equals(getString(R.string.json_status_failed))) {
                                BugSenseHandler.leaveBreadcrumb("reDownload_RESTART");
                                reDownload(currentItem, "RESTART");
                            } else {
                                BugSenseHandler.leaveBreadcrumb("reDownload");
                                reDownload(currentItem, "-");
                            }
                            break;
                        case 4:
                            BugSenseHandler.leaveBreadcrumb("removeFromDashboard");
                            removeFromDashboard(currentItem);
                            break;
                        case 5:
                            BugSenseHandler.leaveBreadcrumb("delete");
                            delete(currentItem);
                            break;
                        case 6:
                            BugSenseHandler.leaveBreadcrumb("pauseresume");
                            pauseresume(currentItem);
                        }

                    }
                });

                secureShowDialog(builder);
            }

            return true;
        }
    });
}

From source file:com.fanfou.app.opensource.service.DownloadService.java

@SuppressWarnings("unused")
private PendingIntent getInstallPendingIntent(final String fileName) {
    final String mimeType = MimeTypeMap.getSingleton()
            .getMimeTypeFromExtension(CommonHelper.getExtension(fileName));
    if (mimeType != null) {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(fileName)), mimeType);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        final PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        return pi;
    }/*  www .  j a v a  2  s  .  co  m*/
    return null;
}

From source file:com.androidquery.simplefeed.activity.PostActivity.java

public void photoClicked(View view) {

    File file = makePhotoFile();/*from w  w  w.j av a2  s  .  c o  m*/

    if (file == null)
        return;

    Uri outputFileUri = Uri.fromFile(file);

    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

    startActivityForResult(intent, Constants.ACTIVITY_CAMERA);

}

From source file:com.abc.driver.PersonalActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CellSiteConstants.TAKE_USER_PORTRAIT
            || requestCode == CellSiteConstants.PICK_USER_PORTRAIT) {
        Uri uri = null;/*from w  w w  .  j ava  2  s  .  c  o m*/
        if (requestCode == CellSiteConstants.TAKE_USER_PORTRAIT) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_USER_PORTRAIT) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            imageUri = Uri.fromFile(new File(filePath));
        } else // This is a bug, in some cases, some images like
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().setProfileImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        doCrop();
        Log.d(TAG, "onActivityResult PICK_PICTURE");

    } else if (requestCode == CellSiteConstants.CROP_PICTURE) {
        Log.d(TAG, "crop picture");
        // processFile();

        if (data != null) {
            Bundle extras = data.getExtras();
            Bitmap photo = extras.getParcelable("data");

            app.setPortaritBitmap(photo);
            mUserPortraitIv.setImageBitmap(photo);
            mUpdateImageTask = new UpdateImageTask();
            mUpdateImageTask.execute("" + app.getUser().getId(), Utils.bitmap2String(photo),
                    CellSiteConstants.UPDATE_USER_PORTRAIT_URL);

            isPortraitChanged = true;
        }
    } else if (requestCode == CellSiteConstants.TAKE_IDENTITY
            || requestCode == CellSiteConstants.PICK_IDENTITY) {

        Uri uri = null;
        if (requestCode == CellSiteConstants.TAKE_IDENTITY) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_IDENTITY) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "filePath =" + filePath);
            Log.d(TAG, "uri=" + uri.toString());
            imageUri = Uri.fromFile(new File(filePath));
        } else //
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().setIdentityImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        Bitmap tmpBmp = BitmapFactory.decodeFile(imageUri.getPath(), null);
        Bitmap scaledBmp = Bitmap.createScaledBitmap(tmpBmp, CellSiteConstants.IDENTITY_IMAGE_WIDTH,
                CellSiteConstants.IDENTITY_IMAGE_HEIGHT, false);

        mUserIdentityIv.setImageBitmap(scaledBmp);
        // s isChanged = true;
        mUpdateImageTask = new UpdateImageTask();
        mUpdateImageTask.execute("" + app.getUser().getId(), Utils.bitmap2String(scaledBmp),
                CellSiteConstants.UPDATE_USER_IDENTITY_URL);

    } else if (requestCode == CellSiteConstants.TAKE_DRIVER_LICENSE
            || requestCode == CellSiteConstants.PICK_DRIVER_LICENSE) {

        Uri uri = null;
        if (requestCode == CellSiteConstants.TAKE_DRIVER_LICENSE) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_DRIVER_LICENSE) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "filePath =" + filePath);
            Log.d(TAG, "uri=" + uri.toString());
            imageUri = Uri.fromFile(new File(filePath));
        } else //
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().setDriverLicenseImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        Bitmap tmpBmp = BitmapFactory.decodeFile(imageUri.getPath(), null);
        Bitmap scaledBmp = Bitmap.createScaledBitmap(tmpBmp, CellSiteConstants.IDENTITY_IMAGE_WIDTH,
                CellSiteConstants.IDENTITY_IMAGE_HEIGHT, false);

        mUserDriverLicenseIv.setImageBitmap(scaledBmp);
        // s isChanged = true;
        mUpdateImageTask = new UpdateImageTask();
        mUpdateImageTask.execute("" + app.getUser().getId(), Utils.bitmap2String(scaledBmp),
                CellSiteConstants.UPDATE_DRIVER_LICENSE_URL);

    }
}

From source file:io.ingame.squarecamera.CameraLauncher.java

/**
 * Get image from photo library./*from ww w  .  j a  va2s  . co m*/
 *
 * @param srcType           The album to get image from.
 * @param returnType        Set the type of image to return.
 * @param encodingType
 */
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
// TODO: Images from kitkat filechooser not going into crop function
public void getImage(int srcType, int returnType, int encodingType) {
    Intent intent = new Intent();
    String title = GET_PICTURE;
    croppedUri = null;
    if (this.mediaType == PICTURE) {
        intent.setType("image/*");
        if (this.allowEdit) {
            intent.setAction(Intent.ACTION_PICK);
            intent.putExtra("crop", "true");
            if (targetWidth > 0) {
                intent.putExtra("outputX", targetWidth);
            }
            if (targetHeight > 0) {
                intent.putExtra("outputY", targetHeight);
            }
            if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
            }
            File photo = createCaptureFile(encodingType);
            croppedUri = Uri.fromFile(photo);
            setOutputUri(intent, croppedUri);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }
    } else if (this.mediaType == VIDEO) {
        intent.setType("video/*");
        title = GET_VIDEO;
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
    } else if (this.mediaType == ALLMEDIA) {
        // I wanted to make the type 'image/*, video/*' but this does not work on all versions
        // of android so I had to go with the wildcard search.
        intent.setType("*/*");
        title = GET_All;
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
    }
    if (this.cordova != null) {
        this.cordova.startActivityForResult((CordovaPlugin) this,
                Intent.createChooser(intent, new String(title)), (srcType + 1) * 16 + returnType + 1);
    }
}

From source file:com.richtodd.android.quiltdesign.app.QuiltEditActivity.java

private Uri saveQuiltDesign() throws IOException, RepositoryException {

    QuiltEditFragment fragment = getQuiltEditFragment();
    Quilt quilt = fragment.getQuilt();// ww w  . j  a va 2  s. co  m

    File file = new File(StorageUtility.getPublicFolder(), getCurrentQuiltName() + ".quiltdesign");

    saveQuiltDesign(quilt, file);

    Uri uri = Uri.fromFile(file);

    return uri;
}

From source file:edu.mit.mobile.android.locast.data.MediaSync.java

private void updateLocalFile(Uri castMediaUri, File localFile, File localThumbnail) {
    final ContentValues cv = new ContentValues();
    cv.put(CastMedia._LOCAL_URI, Uri.fromFile(localFile).toString());
    if (localThumbnail != null) {
        cv.put(CastMedia._THUMB_LOCAL, Uri.fromFile(localFile).toString());
    }/*from w  w w  . ja v a  2s  . co  m*/
    cv.put(MediaProvider.CV_FLAG_DO_NOT_MARK_DIRTY, true);

    getContentResolver().update(castMediaUri, cv, null, null);

}

From source file:com.snappy.CameraCropActivity.java

public void startCamera() {
    // Check if camera exists
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Toast.makeText(this, R.string.no_camera, Toast.LENGTH_LONG).show();
        finish();//from  w  ww . j a va2s  .c o m
    } else {
        try {
            long date = System.currentTimeMillis();
            String filename = DateFormat.format("yyyy-MM-dd_kk.mm.ss", date).toString() + ".jpg";
            _path = this.getExternalCacheDir() + "/" + filename;
            File file = new File(_path);
            //            File file = new File(getFileDir(getBaseContext()), filename);
            Uri outputFileUri = Uri.fromFile(file);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            startActivityForResult(intent, CAMERA);
        } catch (Exception ex) {
            Toast.makeText(this, R.string.no_camera, Toast.LENGTH_LONG).show();
            finish();
        }

    }
}

From source file:com.firesoft.member.Activity.F9_SettingActivity.java

private String startPhotoZoom(Uri uri) {

    if (mFileZoomDir == null) {
        mFileZoomDir = new File(MemberAppConst.FILEPATH + "img/");
        if (!mFileZoomDir.exists()) {
            mFileZoomDir.mkdirs();/*ww  w. j  a v  a 2  s . com*/
        }
    }

    String fileName;
    fileName = "/temp.jpg";

    String filePath = mFileZoomDir + fileName;
    File loadingFile = new File(filePath);

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 400);
    intent.putExtra("aspectY", 400);
    intent.putExtra("output", Uri.fromFile(loadingFile));// 
    intent.putExtra("outputFormat", "PNG");// ?
    intent.putExtra("noFaceDetection", true); // ?
    intent.putExtra("return-data", false); // ??Intent
    startActivityForResult(intent, REQUEST_PHOTOZOOM);

    return filePath;

}

From source file:com.karura.framework.plugins.Capture.java

/**
 * Sets up an intent to capture images. Result handled by onActivityResult()
 */// w ww.j a  va  2  s .c om
@Asynchronous(retVal = "Returns a json object which contains the file name, type, modified date, size and path if successful.")
@Description("Sets up an intent to capture images, and then starts the component.")
@JavascriptInterface
@SupportJavascriptInterface
@Params({ @Param(name = "callId", description = "The method correlator between javascript and java.") })
public void captureImage(final String callId) {
    // Save the number of images currently on disk for later
    this.numPics = queryImgDB(whichContentStore()).getCount();

    Intent captureImageIntent = new Intent(ACTION_IMAGE_CAPTURE);

    // Specify file so that large image is captured and returned
    File photoFile = new File(DirectoryManager.getTempDirectoryPath(getActivity()), "Capture.jpg");
    captureImageIntent.putExtra(EXTRA_OUTPUT, Uri.fromFile(photoFile));

    requestCallIdMap.append(CAPTURE_IMAGE, callId);
    getActivity().startActivityForResult(captureImageIntent, CAPTURE_IMAGE);
}