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:com.layer.atlas.messenger.AtlasMessagesScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.uiHandler = new Handler();
    this.app = (MessengerApp) getApplication();

    setContentView(R.layout.atlas_screen_messages);

    boolean convIsNew = getIntent().getBooleanExtra(EXTRA_CONVERSATION_IS_NEW, false);
    String convUri = getIntent().getStringExtra(EXTRA_CONVERSATION_URI);
    if (convUri != null) {
        Uri uri = Uri.parse(convUri);/*  w w  w.j  a  va2  s  .  c  om*/
        conv = app.getLayerClient().getConversation(uri);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(convUri.hashCode()); // Clear notifications for this Conversation
    }

    participantsPicker = (AtlasParticipantPicker) findViewById(R.id.atlas_screen_messages_participants_picker);
    participantsPicker.init(new String[] { app.getLayerClient().getAuthenticatedUserId() },
            app.getParticipantProvider());
    if (convIsNew) {
        participantsPicker.setVisibility(View.VISIBLE);
    }

    messageComposer = (AtlasMessageComposer) findViewById(R.id.atlas_screen_messages_message_composer);
    messageComposer.init(app.getLayerClient(), conv);
    messageComposer.setListener(new AtlasMessageComposer.Listener() {
        public boolean beforeSend(Message message) {
            boolean conversationReady = ensureConversationReady();
            if (!conversationReady)
                return false;

            // push
            preparePushMetadata(message);
            return true;
        }

    });

    messageComposer.registerMenuItem("Photo", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            String fileName = "cameraOutput" + System.currentTimeMillis() + ".jpg";
            photoFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName);
            final Uri outputUri = Uri.fromFile(photoFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            if (debug)
                Log.w(TAG, "onClick() requesting photo to file: " + fileName + ", uri: " + outputUri);
            startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
        }
    });

    messageComposer.registerMenuItem("Image", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            // in onCreate or any event where your want the user to select a file
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_GALLERY);
        }
    });

    messageComposer.registerMenuItem("Location", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            if (lastKnownLocation == null) {
                Toast.makeText(v.getContext(), "Inserting Location: Location is unknown yet",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            String locationString = "{\"lat\":" + lastKnownLocation.getLatitude() + ", \"lon\":"
                    + lastKnownLocation.getLongitude() + "}";
            MessagePart part = app.getLayerClient().newMessagePart(Atlas.MIME_TYPE_ATLAS_LOCATION,
                    locationString.getBytes());
            Message message = app.getLayerClient().newMessage(Arrays.asList(part));

            preparePushMetadata(message);
            conv.send(message);

            if (debug)
                Log.w(TAG, "onSendLocation() loc:  " + locationString);
        }
    });

    messagesList = (AtlasMessagesList) findViewById(R.id.atlas_screen_messages_messages_list);
    messagesList.init(app.getLayerClient(), app.getParticipantProvider());
    if (USE_QUERY) {
        Query<Message> query = Query.builder(Message.class)
                .predicate(new Predicate(Message.Property.CONVERSATION, Predicate.Operator.EQUAL_TO, conv))
                .sortDescriptor(new SortDescriptor(Message.Property.POSITION, SortDescriptor.Order.ASCENDING))
                .build();
        messagesList.setQuery(query);
    } else {
        messagesList.setConversation(conv);
    }

    messagesList.setItemClickListener(new ItemClickListener() {
        public void onItemClick(Cell cell) {
            if (Atlas.MIME_TYPE_ATLAS_LOCATION.equals(cell.messagePart.getMimeType())) {
                String jsonLonLat = new String(cell.messagePart.getData());
                JSONObject json;
                try {
                    json = new JSONObject(jsonLonLat);
                    double lon = json.getDouble("lon");
                    double lat = json.getDouble("lat");
                    Intent openMapIntent = new Intent(Intent.ACTION_VIEW);
                    String uriString = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f", lat, lon, 18,
                            lat, lon);
                    final Uri geoUri = Uri.parse(uriString);
                    openMapIntent.setData(geoUri);
                    if (openMapIntent.resolveActivity(getPackageManager()) != null) {
                        startActivity(openMapIntent);
                        if (debug)
                            Log.w(TAG, "onItemClick() starting Map: " + uriString);
                    } else {
                        if (debug)
                            Log.w(TAG, "onItemClick() No Activity to start Map: " + geoUri);
                    }
                } catch (JSONException ignored) {
                }
            } else if (cell instanceof ImageCell) {
                Intent intent = new Intent(AtlasMessagesScreen.this.getApplicationContext(),
                        AtlasImageViewScreen.class);
                app.setParam(intent, cell);
                startActivity(intent);
            }
        }
    });

    typingIndicator = (AtlasTypingIndicator) findViewById(R.id.atlas_screen_messages_typing_indicator);
    typingIndicator.init(conv,
            new AtlasTypingIndicator.DefaultTypingIndicatorCallback(app.getParticipantProvider()));

    // location manager for inserting locations:
    this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    prepareActionBar();
}

From source file:org.golang.app.WViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Fixed Portrait orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    /*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

    setContentView(R.layout.webview);/*  w  w w.  jav a 2  s . c  o  m*/
    WebView webView = (WebView) findViewById(R.id.webView1);

    initWebView(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("JavaGoWV: ", url);

            final Pattern p = Pattern.compile("dcoinKey&password=(.*)$");
            final Matcher m = p.matcher(url);
            if (m.find()) {
                try {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //File root = android.os.Environment.getExternalStorageDirectory();
                                File dir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                                Log.d("JavaGoWV", "dir " + dir);

                                URL keyUrl = new URL(
                                        "http://127.0.0.1:8089/ajax?controllerName=dcoinKey&first=1"); //you can write here any link
                                //URL keyUrl = new URL("http://yandex.ru/"); //you can write here any link
                                File file = new File(dir, "dcoin-key.png");

                                long startTime = System.currentTimeMillis();
                                Log.d("JavaGoWV", "download begining");
                                Log.d("JavaGoWV", "download keyUrl:" + keyUrl);

                                /* Open a connection to that URL. */
                                URLConnection ucon = keyUrl.openConnection();

                                Log.d("JavaGoWV", "0");
                                /*
                                * Define InputStreams to read from the URLConnection.
                                */
                                InputStream is = ucon.getInputStream();

                                Log.d("JavaGoWV", "01");

                                BufferedInputStream bis = new BufferedInputStream(is);

                                Log.d("JavaGoWV", "1");
                                /*
                                * Read bytes to the Buffer until there is nothing more to read(-1).
                                */
                                ByteArrayBuffer baf = new ByteArrayBuffer(5000);
                                int current = 0;
                                while ((current = bis.read()) != -1) {
                                    baf.append((byte) current);
                                }

                                Log.d("JavaGoWV", "2");
                                /* Convert the Bytes read to a String. */
                                FileOutputStream fos = new FileOutputStream(file);
                                fos.write(baf.toByteArray());
                                fos.flush();
                                fos.close();

                                Log.d("JavaGoWV", "3");
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri contentUri = Uri.fromFile(file);
                                    mediaScanIntent.setData(contentUri);
                                    WViewActivity.this.sendBroadcast(mediaScanIntent);
                                } else {
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                                            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                                }

                                Log.d("JavaGoWV", "4");
                            } catch (Exception e) {
                                Log.e("JavaGoWV error 0", e.toString());
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("JavaGoWV error", e.toString());
                    e.printStackTrace();
                }
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.e("JavaGoWV", "shouldOverrideUrlLoading " + url);

            if (url.endsWith(".mp4")) {
                Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(in);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("JavaGoWV",
                    "failed: " + failingUrl + ", error code: " + errorCode + " [" + description + "]");
        }
    });

    SystemClock.sleep(1500);
    //if (MyService.DcoinStarted(8089)) {
    webView.loadUrl("http://localhost:8089/");
    //}

}

From source file:com.qiscus.sdk.presenter.QiscusChatPresenter.java

public void sendFile(File file) {
    File compressedFile = file;/*from   w w w  . j  a  va2  s .c  o  m*/
    if (file.getName().endsWith(".gif")) {
        compressedFile = QiscusFileUtil.saveFile(compressedFile, currentTopicId);
    } else if (QiscusImageUtil.isImage(file)) {
        try {
            compressedFile = QiscusImageUtil.compressImage(Uri.fromFile(file), currentTopicId);
        } catch (NullPointerException e) {
            view.showError("Can not read file, please make sure that is not corrupted file!");
            return;
        }

    } else {
        compressedFile = QiscusFileUtil.saveFile(compressedFile, currentTopicId);
    }

    QiscusComment qiscusComment = QiscusComment.generateMessage(
            String.format("[file] %s [/file]", compressedFile.getPath()), room.getId(), currentTopicId);
    qiscusComment.setDownloading(true);
    view.onSendingComment(qiscusComment);

    File finalCompressedFile = compressedFile;
    QiscusApi.getInstance()
            .uploadFile(compressedFile, percentage -> qiscusComment.setProgress((int) percentage))
            .doOnSubscribe(() -> Qiscus.getDataStore().add(qiscusComment)).flatMap(uri -> {
                qiscusComment.setMessage(String.format("[file] %s [/file]", uri.toString()));
                return QiscusApi.getInstance().postComment(qiscusComment);
            }).doOnNext(commentSend -> {
                Qiscus.getDataStore().addOrUpdateLocalPath(commentSend.getTopicId(), commentSend.getId(),
                        finalCompressedFile.getAbsolutePath());
                qiscusComment.setDownloading(false);
                commentSuccess(commentSend);
            }).doOnError(throwable -> {
                qiscusComment.setDownloading(false);
                commentFail(qiscusComment);
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).compose(bindToLifecycle())
            .subscribe(commentSend -> {
                if (commentSend.getTopicId() == currentTopicId) {
                    view.onSuccessSendComment(commentSend);
                }
            }, throwable -> {
                throwable.printStackTrace();
                if (qiscusComment.getTopicId() == currentTopicId) {
                    view.onFailedSendComment(qiscusComment);
                }
            });
}

From source file:com.grupohqh.carservices.operator.ManipulateCarActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manipulate_car);

    if (getIntent().getExtras().containsKey("userId"))
        userId = getIntent().getExtras().getInt("userId");
    if (getIntent().getExtras().containsKey("carOwnerId"))
        carOwnerId = getIntent().getExtras().getInt("carOwnerId");

    CARBRAND_URL = getString(R.string.base_url) + getString(R.string.carbrands_url);
    CARLINE_URL = getString(R.string.base_url) + getString(R.string.carmodels_url);
    SAVECAR_URL = getString(R.string.base_url) + "savecar/";
    SAVEPHOTO_URL = getString(R.string.base_url) + "savephoto/";
    hasCamera = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);

    etTagNumber = (EditText) findViewById(R.id.etTagNumber);
    etUsernameOwner = (EditText) findViewById(R.id.etUsernameOwner);
    etCarBrand = (EditText) findViewById(R.id.etCarBrand);
    etCarModel = (EditText) findViewById(R.id.etCarModel);
    etCarYear = (EditText) findViewById(R.id.etCarYear);
    etColor = (EditText) findViewById(R.id.etCarColor);
    etSerialNumber = (EditText) findViewById(R.id.etSerialNumber);
    etLicensePlate = (EditText) findViewById(R.id.etLicensePlate);
    etKM = (EditText) findViewById(R.id.etKm);
    imgCar = (ImageView) findViewById(R.id.imgCar);
    spCarBrand = (Spinner) findViewById(R.id.spCarBrand);
    spCarModel = (Spinner) findViewById(R.id.spCarModel);
    btnSaveCar = (Button) findViewById(R.id.btnSaveCar);
    btnTakePicture = (Button) findViewById(R.id.btnTakePicture);
    bar = (ProgressBar) findViewById(R.id.progressBar);
    viewUsername = findViewById(R.id.viewUsername);

    if (savedInstanceState != null) {
        bm = savedInstanceState.getParcelable("bm");
        if (bm != null)
            imgCar.setImageBitmap(bm);/*  w  ww.jav a  2 s.c  om*/
    }

    bar.setVisibility(View.GONE);
    etCarBrand.setVisibility(View.GONE);
    etCarModel.setVisibility(View.GONE);
    viewUsername.setVisibility(carOwnerId == 0 ? View.VISIBLE : View.GONE);

    btnTakePicture.setEnabled(hasCamera);
    btnTakePicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(ManipulateCarActivity.this)));
            startActivityForResult(intent, CAPTURE_IMAGE);
        }
    });

    btnSaveCar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validate())
                new SaveCarAsyncTask().execute(SAVECAR_URL);
        }
    });

    spCarBrand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                ((TextView) parent.getChildAt(position)).setTextColor(Color.GRAY);
            if (mapBrands.get(brands.get(position)) == otherId) {
                etCarBrand.setVisibility(View.VISIBLE);
                etCarModel.setVisibility(View.VISIBLE);
                spCarModel.setVisibility(View.GONE);
                etCarBrand.requestFocus();
            } else {
                etCarBrand.setVisibility(View.GONE);
                etCarModel.setVisibility(View.GONE);
                spCarModel.setVisibility(View.VISIBLE);
                new LoadCarModelsAsyncTask().execute(CARLINE_URL + mapBrands.get(brands.get(position)) + "/");
                reload = true;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    spCarModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                ((TextView) parent.getChildAt(position)).setTextColor(Color.GRAY);
            if (mapModels.get(models.get(position)) == otherId) {
                etCarModel.setVisibility(View.VISIBLE);
                etCarModel.requestFocus();
            } else {
                etCarModel.setVisibility(View.GONE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    if (useMiniMe) {
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        usbCommunication = UsbCommunication.newInstance();

        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); // will intercept by system
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(usbReceiver, filter);

        etEPC = (EditText) findViewById(R.id.etEPC);
        btnReadTAG = (Button) findViewById(R.id.btnReadTAG);
        txtStatus = (TextView) findViewById(R.id.txtStatus);
        btnReadTAG.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etEPC.setText("");
                if (txtStatus.getText().toString().equals("conectado")) {
                    readTag();
                } else {
                    Toast.makeText(getBaseContext(), "dispositivo " + txtStatus.getText(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        });
    }

    etKM.addTextChangedListener(new NumberTextWatcher(etKM));
}

From source file:com.hivewallet.androidclient.wallet.AddressBookProvider.java

/**
 * Resizes the provided bitmap and stores it in private storage, returning a URI to it.
 * It will be deleted on the next clean up cycle, unless marked as permanent in the mean time.  */
public static Uri storeBitmap(@Nonnull Context context, @Nonnull Bitmap bitmap) {
    if (bitmap == null)
        return null;

    Bitmap bitmapScaled = ensureReasonableSize(bitmap);
    if (bitmapScaled == null)
        return null;

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    bitmapScaled.compress(CompressFormat.PNG, 100, outStream);
    byte[] photoScaled = outStream.toByteArray();

    Uri photoUri = null;/*from  ww w  . ja  v  a2  s .  com*/
    try {
        /* for some reason calling DigestUtils.sha1Hex() does not work on Android */
        String hash = new String(Hex.encodeHex(DigestUtils.sha1(photoScaled)));

        /* create photo asset and database entry */
        File dir = context.getDir(Constants.PHOTO_ASSETS_FOLDER, Context.MODE_PRIVATE);
        File photoAsset = new File(dir, hash + ".png");
        photoUri = Uri.fromFile(photoAsset);
        boolean alreadyPresent = AddressBookProvider.insertOrUpdatePhotoUri(context, photoUri);
        if (!alreadyPresent) {
            FileUtils.writeByteArrayToFile(photoAsset, photoScaled);
            log.info("Saved photo asset with uri {}", photoUri);
        }

        /* use opportunity to clean up photo assets */
        List<Uri> stalePhotoUris = AddressBookProvider.deleteStalePhotoAssets(context);
        for (Uri stalePhotoUri : stalePhotoUris) {
            File stalePhotoAsset = new File(stalePhotoUri.getPath());
            FileUtils.deleteQuietly(stalePhotoAsset);
            log.info("Deleting stale photo asset with uri {}", stalePhotoUri);
        }
    } catch (IOException ignored) {
    }

    return photoUri;
}

From source file:li.barter.fragments.EditProfileFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    init(container, savedInstanceState);
    setHasOptionsMenu(true);/*ww  w  . j  a v  a  2  s. c om*/
    final View view = inflater.inflate(R.layout.fragment_profile_edit, null);
    setActionBarTitle(R.string.text_edit_profile);
    mAvatarBitmapTransformation = new AvatarBitmapTransformation(AvatarBitmapTransformation.AvatarSize.LARGE);

    mFirstNameTextView = (TextView) view.findViewById(R.id.text_first_name);
    mLastNameTextView = (TextView) view.findViewById(R.id.text_last_name);
    mAboutMeTextView = (TextView) view.findViewById(R.id.text_about_me);
    mPreferredLocationTextView = (TextView) view.findViewById(R.id.text_current_location);
    mProfileImageView = (RoundedCornerImageView) view.findViewById(R.id.image_profile_pic);

    mPreferredLocationTextView.setOnClickListener(this);

    mProfileImageView.setOnClickListener(this);
    mAvatarfile = new File(Environment.getExternalStorageDirectory(), mAvatarFileName);

    if (mAvatarfile.exists()) {
        final Bitmap bmp = BitmapFactory.decodeFile(mAvatarfile.getAbsolutePath());
        mProfileImageView.setImageBitmap(bmp);
    }

    if (SharedPreferenceHelper.contains(R.string.pref_first_name)) {
        mFirstNameTextView.setText(SharedPreferenceHelper.getString(R.string.pref_first_name));
    } else {
        mFirstNameTextView.setText(UserInfo.INSTANCE.getFirstName());
    }

    if (SharedPreferenceHelper.contains(R.string.pref_last_name)) {
        mLastNameTextView.setText(SharedPreferenceHelper.getString(R.string.pref_last_name));
    }

    if (SharedPreferenceHelper.contains(R.string.pref_description)) {
        mAboutMeTextView.setText(SharedPreferenceHelper.getString(R.string.pref_description));
    }

    if (SharedPreferenceHelper.contains(R.string.pref_location)) {
        loadPreferredLocation();
    }

    // for loading profile image

    String mProfileImageUrl = "";
    if (SharedPreferenceHelper.contains(R.string.pref_profile_image)) {
        mProfileImageUrl = SharedPreferenceHelper.getString(R.string.pref_profile_image);

    }
    Picasso.with(getActivity()).load(mProfileImageUrl).transform(mAvatarBitmapTransformation)
            .error(R.drawable.pic_avatar).into(mProfileImageView.getTarget());

    mCameraImageCaptureUri = Uri
            .fromFile(new File(android.os.Environment.getExternalStorageDirectory(), "barterli_avatar.jpg"));

    mChoosePictureDialogFragment = (SingleChoiceDialogFragment) getFragmentManager()
            .findFragmentByTag(FragmentTags.DIALOG_TAKE_PICTURE);
    return view;
}

From source file:com.intel.xdk.camera.Camera.java

public synchronized void takePicture(final int quality, final String saveToLibYN, final String picType) {
    //saveToLibYN is not used because the camera activity always saves to gallery

    PackageManager pm = activity.getPackageManager();
    if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false) {
        fireJSEvent("camera.picture.add", false, null,
                new String[] { String.format("ev.error='device has no camera';") });
    }/* w  ww.j  a va2  s. co  m*/

    if (busy) {
        cameraBusy();
    }
    this.busy = true;

    File outputFile = new File(Environment.getExternalStorageDirectory(), "test." + picType);

    //put required info in shared prefs
    SharedPreferences.Editor prefsEditor = activity.getSharedPreferences(cameraPrefsKey, 0).edit();
    prefsEditor.putString(cameraPrefsFileName, outputFile.getAbsolutePath());
    prefsEditor.putBoolean(cameraPrefsIsPNG, "png".equalsIgnoreCase(picType));
    prefsEditor.putInt(cameraPrefsQuality, quality);
    prefsEditor.commit();

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputFile));

    //cordova.setActivityResultCallback(this);
    // TODO: figure this out
    cordova.startActivityForResult(this, intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    //activity.setLaunchedChildActivity(true);
    //activity.startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}

From source file:com.maskyn.fileeditorpro.activity.SelectFileActivity.java

/**
 * Finish this Activity with a result code and URI of the selected file.
 *
 * @param file The file selected./* w w  w  . j  a  v  a  2s.c o m*/
 */
private void finishWithResult(File file) {
    if (file != null) {
        Uri uri = Uri.fromFile(file);
        //Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK, new Intent().setData(uri));
        finish();
    } else {
        setResult(RESULT_CANCELED);
        finish();
    }
}