Example usage for android.content Intent createChooser

List of usage examples for android.content Intent createChooser

Introduction

In this page you can find the example usage for android.content Intent createChooser.

Prototype

public static Intent createChooser(Intent target, CharSequence title) 

Source Link

Document

Convenience function for creating a #ACTION_CHOOSER Intent.

Usage

From source file:com.appteam.nimbus.activity.homeActivity.java

@SuppressWarnings("StatementWithEmptyBody")
@Override/*from w w  w  . ja va 2 s  . co  m*/
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.navigation_to_profile) {
        // Handle the camera action
        Intent i = new Intent(homeActivity.this, Profile.class);
        startActivity(i);

    } else if (id == R.id.aboutus_nav) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(String.format("%1$s", getString(R.string.app_name)));
        builder.setMessage(getResources().getText(R.string.aboutus_text));
        builder.setPositiveButton("OK", null);
        builder.setIcon(R.mipmap.nimbus16);
        AlertDialog welcomeAlert = builder.create();
        welcomeAlert.show();
        ((TextView) welcomeAlert.findViewById(android.R.id.message))
                .setMovementMethod(LinkMovementMethod.getInstance());
    } else if (id == R.id.feedback_nav) {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        String uriText = "mailto:" + Uri.encode("appteam.nith@gmail.com") + "?subject="
                + Uri.encode("Reporting A Bug/Feedback") + "&body=" + Uri.encode(
                        "Hello, Appteam \nI want to report a bug/give feedback corresponding to the app Nimbus 2k16.\n.....\n\n-Your name");

        Uri uri = Uri.parse(uriText);
        intent.setData(uri);
        startActivity(Intent.createChooser(intent, "Send Email"));
    } else if (id == R.id.opensourcelicenses_nav) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(String.format("%1$s", getString(R.string.open_source_licenses)));
        builder.setMessage(getResources().getText(R.string.licenses_text));
        builder.setPositiveButton("OK", null);
        //builder.setIcon(R.mipmap.nimbus_icon);
        AlertDialog welcomeAlert = builder.create();
        welcomeAlert.show();
        ((TextView) welcomeAlert.findViewById(android.R.id.message))
                .setMovementMethod(LinkMovementMethod.getInstance());
    } else if (id == R.id.contributors_nav) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(String.format("%1$s", getString(R.string.contributors)));
        builder.setMessage(getResources().getText(R.string.contributors_text));
        builder.setPositiveButton("OK", null);
        //builder.setIcon(R.mipmap.nimbus_icon);
        AlertDialog welcomeAlert = builder.create();
        welcomeAlert.show();
        ((TextView) welcomeAlert.findViewById(android.R.id.message))
                .setMovementMethod(LinkMovementMethod.getInstance());
    } else if (id == R.id.notifications) {
        startActivity(new Intent(homeActivity.this, ViewActivity.class));
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.EditFragment.java

/**
 * Allows the user to change the image attached to their comment or remove it
 * entirely. Prompts the user with an AlertDialog as to which option they would like
 * to select. /*  w  w w .j a va2  s  .c o  m*/
 * @param view The Button pressed to call editImage.
 */
public void editImage(View view) {
    if (view.getId() == R.id.attach_image_button) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.attach_image_title);
        dialog.setMessage(R.string.attach_image_dialog);
        dialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Test"), ImageHelper.REQUEST_GALLERY);
            }
        });
        dialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                try {
                    imageFile = ImageHelper.createImageFile();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
                    startActivityForResult(Intent.createChooser(intent, "Test"), ImageHelper.REQUEST_CAMERA);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.setNeutralButton("Remove Image", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                editComment.setImage(null);
                editComment.setImageThumb(null);
            }
        });
        dialog.show();
    }
}

From source file:com.wikonos.fingerprint.activities.MainActivity.java

/**
 * Create dialog list of logs/* w w w  .  j  a v a2s  .  c o  m*/
 * 
 * @return
 */
public AlertDialog getDialogReviewLogs() {
    /**
     * List of logs
     */
    File folder = new File(LogWriter.APPEND_PATH);
    final String[] files = folder.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            if (filename.contains(".log") && !filename.equals(LogWriter.DEFAULT_NAME)
                    && !filename.equals(LogWriterSensors.DEFAULT_NAME)
                    && !filename.equals(ErrorLog.DEFAULT_NAME))
                return true;
            else
                return false;
        }
    });

    Arrays.sort(files);
    ArrayUtils.reverse(files);

    String[] files_with_status = new String[files.length];
    String[] sent_mode = { "", "(s) ", "(e) ", "(s+e) " };
    for (int i = 0; i < files.length; ++i) {
        //0 -- not sent
        //1 -- server
        //2 -- email
        files_with_status[i] = sent_mode[getSentFlags(files[i], this)] + files[i];
    }

    if (files != null && files.length > 0) {

        final boolean[] selected = new boolean[files.length];

        final AlertDialog ald = new AlertDialog.Builder(MainActivity.this)
                .setMultiChoiceItems(files_with_status, selected,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                selected[which] = isChecked;
                            }
                        })
                .setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                })
                /**
                * Delete log
                */
                .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        //Show delete confirm
                        standardConfirmDialog("Delete Logs", "Are you sure you want to delete selected logs?",
                                new OnClickListener() {
                                    //Confrim Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        int deleteCount = 0;
                                        boolean flagSelected = false;
                                        for (int i = 0; i < selected.length; i++) {
                                            if (selected[i]) {
                                                flagSelected = true;
                                                LogWriter.delete(files[i]);
                                                LogWriter.delete(files[i].replace(".log", ".dev"));
                                                deleteCount++;
                                            }
                                        }

                                        reviewLogsCheckItems(flagSelected);

                                        removeDialog(DIALOG_ID_REVIEW);

                                        Toast.makeText(getApplicationContext(), deleteCount + " logs deleted.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, new OnClickListener() {
                                    //Cancel Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //Do nothing
                                        dialog.dismiss();
                                        Toast.makeText(getApplicationContext(), "Delete cancelled.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, false);
                    }
                })
                /**
                * Send to server functional
                **/
                .setNeutralButton("Send to Server", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (isOnline()) {
                            ArrayList<String> filesList = new ArrayList<String>();

                            for (int i = 0; i < selected.length; i++)
                                if (selected[i]) {

                                    filesList.add(LogWriter.APPEND_PATH + files[i]);
                                    //Move to httplogsender
                                    //setSentFlags(files[i], 1, MainActivity.this);   //Mark file as sent
                                }

                            if (reviewLogsCheckItems(filesList.size() > 0 ? true : false)) {
                                DataPersistence d = new DataPersistence(getApplicationContext());
                                new HttpLogSender(MainActivity.this,
                                        d.getServerName() + getString(R.string.submit_log_url), filesList)
                                                .setToken(getToken()).execute();
                            }

                            // removeDialog(DIALOG_ID_REVIEW);
                        } else {
                            standardAlertDialog(getString(R.string.msg_alert),
                                    getString(R.string.msg_no_internet), null);
                        }
                    }
                })
                /**
                * Email
                **/
                .setPositiveButton("eMail", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        boolean flagSelected = false;
                        // convert from paths to Android friendly
                        // Parcelable Uri's
                        ArrayList<Uri> uris = new ArrayList<Uri>();
                        for (int i = 0; i < selected.length; i++)
                            if (selected[i]) {
                                flagSelected = true;
                                /** wifi **/
                                File fileIn = new File(LogWriter.APPEND_PATH + files[i]);
                                Uri u = Uri.fromFile(fileIn);
                                uris.add(u);

                                /** sensors **/
                                File fileInSensors = new File(
                                        LogWriter.APPEND_PATH + files[i].replace(".log", ".dev"));
                                Uri uSens = Uri.fromFile(fileInSensors);
                                uris.add(uSens);

                                setSentFlags(files[i], 2, MainActivity.this); //Mark file as emailed
                            }

                        if (reviewLogsCheckItems(flagSelected)) {
                            /**
                             * Run sending email activity
                             */
                            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
                            emailIntent.setType("plain/text");
                            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                    "Wifi Searcher Scan Log");
                            emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                        }

                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                }).create();

        ald.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

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

                AlertDialog segmentNameAlert = segmentNameDailog("Rename Segment", ald.getContext(),
                        files[position], null, view, files, position);
                segmentNameAlert.setCanceledOnTouchOutside(false);
                segmentNameAlert.show();
                return false;
            }
        });
        return ald;
    } else {
        return standardAlertDialog(getString(R.string.msg_alert), getString(R.string.msg_log_nocount),
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        removeDialog(DIALOG_ID_REVIEW);
                    }
                });
    }
}

From source file:com.wellsandwhistles.android.redditsp.reddit.api.RedditAPICommentAction.java

public static void onActionMenuItemSelected(final RedditRenderableComment renderableComment,
        final RedditCommentView commentView, final AppCompatActivity activity,
        final CommentListingFragment commentListingFragment, final RedditCommentAction action,
        final RedditChangeDataManager changeDataManager) {

    final RedditComment comment = renderableComment.getParsedComment().getRawComment();

    switch (action) {

    case UPVOTE:/*w w w  . j ava 2 s  .  c o m*/
        action(activity, comment, RedditAPI.ACTION_UPVOTE, changeDataManager);
        break;

    case DOWNVOTE:
        action(activity, comment, RedditAPI.ACTION_DOWNVOTE, changeDataManager);
        break;

    case UNVOTE:
        action(activity, comment, RedditAPI.ACTION_UNVOTE, changeDataManager);
        break;

    case SAVE:
        action(activity, comment, RedditAPI.ACTION_SAVE, changeDataManager);
        break;

    case UNSAVE:
        action(activity, comment, RedditAPI.ACTION_UNSAVE, changeDataManager);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        action(activity, comment, RedditAPI.ACTION_REPORT, changeDataManager);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case REPLY: {
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra(CommentReplyActivity.PARENT_ID_AND_TYPE_KEY, comment.getIdAndType());
        intent.putExtra(CommentReplyActivity.PARENT_MARKDOWN_KEY,
                StringEscapeUtils.unescapeHtml4(comment.body));
        activity.startActivity(intent);
        break;
    }

    case EDIT: {
        final Intent intent = new Intent(activity, CommentEditActivity.class);
        intent.putExtra("commentIdAndType", comment.getIdAndType());
        intent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(comment.body));
        activity.startActivity(intent);
        break;
    }

    case DELETE: {
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        action(activity, comment, RedditAPI.ACTION_DELETE, changeDataManager);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        break;
    }

    case COMMENT_LINKS:
        final HashSet<String> linksInComment = comment.computeAllLinks();

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_comment);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_comment_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;

    case SHARE:

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comment by " + comment.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.body) + "\r\n\r\n"
                + comment.getContextUrl().generateNonJsonUri().toString());

        activity.startActivityForResult(Intent.createChooser(mailer, activity.getString(R.string.action_share)),
                1);

        break;

    case COPY_TEXT: {
        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.body));
        break;
    }

    case COPY_URL: {
        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(comment.getContextUrl().context(null).generateNonJsonUri().toString());
        break;
    }

    case COLLAPSE: {
        commentListingFragment.handleCommentVisibilityToggle(commentView);
        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(comment.author).toString());
        break;

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment).show(activity.getSupportFragmentManager(), null);
        break;

    case GO_TO_COMMENT: {
        LinkHandler.onLinkClicked(activity, comment.getContextUrl().context(null).toString());
        break;
    }

    case CONTEXT: {
        LinkHandler.onLinkClicked(activity, comment.getContextUrl().toString());
        break;
    }
    case ACTION_MENU:
        showActionMenu(activity, commentListingFragment, renderableComment, commentView, changeDataManager,
                comment.isArchived());
        break;

    case BACK:
        activity.onBackPressed();
        break;
    }
}

From source file:com.game.simple.Game3.java

public static void sendEmail(String address, String subject, String content) {
    //---timer---//
    //StartReConnect();
    //-----------//
    String[] _address = { address.toString() };
    Intent email = new Intent(Intent.ACTION_SEND);
    email.putExtra(Intent.EXTRA_EMAIL, _address);
    email.putExtra(Intent.EXTRA_SUBJECT, subject);
    email.putExtra(Intent.EXTRA_TEXT, content);
    email.setType("message/rfc822");
    self.startActivity(Intent.createChooser(email, "Choose an Email client :"));

}

From source file:com.fvd.nimbus.MainActivity.java

public void onButtonClick(View v) {
    switch (v.getId()) {
    case R.id.bTakePhoto:
        showProgress(true);/*w  w w  . ja v a  2 s  .  c  o m*/
        getPhoto();
        break;
    case R.id.bFromGallery:
        try {
            showProgress(true);
            Intent fileChooserIntent = new Intent();
            fileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
            fileChooserIntent.setType("image/*");
            fileChooserIntent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(fileChooserIntent, "Select Picture"), TAKE_PICTURE);
        } catch (Exception e) {
            appSettings.appendLog("main:onClick  " + e.getMessage());
            showProgress(false);
        }
        break;
    case R.id.bWebClipper:
        Intent iBrowse = new Intent();
        iBrowse.setClassName("com.fvd.nimbus", "com.fvd.nimbus.BrowseActivity");
        startActivity(iBrowse);
        //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
        overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
        break;
    case R.id.bPdfAnnotate:
        Intent ip = new Intent();
        ip.setClassName("com.fvd.nimbus", "com.fvd.nimbus.ChoosePDFActivity");
        startActivity(ip);
        //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
        overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
        break;
    case R.id.ibSettings:
        Intent inten = new Intent(getApplicationContext(), SettingsActivity.class);
        startActivityForResult(inten, SHOW_SETTINGS);
        //overridePendingTransition(R.anim.carbon_slide_in,R.anim.carbon_slide_out);
        overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
        break;
    /*case R.id.bssSettings:
       Intent i = new Intent(getApplicationContext(), PrefsActivity.class);
        startActivity(i);
        overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
       break;
    case R.id.bssRegister:
       Intent intent = new Intent(getApplicationContext(), RegisterDlg.class);
       intent.putExtra("userMail", userMail==null?"":userMail);
       startActivityForResult(intent, 5);
       overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
       break;   
    case R.id.bssHelp:
       Uri uri = Uri.parse("http://help.everhelper.me/customer/portal/articles/1376820-nimbus-clipper-for-android---quick-guide");
       Intent it = new Intent(Intent.ACTION_VIEW, uri);
       startActivity(it);
       overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
       break;
    case R.id.bssLogin:
       if(serverHelper.getInstance().getSession().length() == 0) showLogin();
       else {
     String sessionId="";
     serverHelper.getInstance().setSessionId(sessionId);
     appSettings.storeUserData(this, userMail, "", "");
     Editor e = prefs.edit();
     e.putString("userMail", userMail);
       e.putString("userPass", "");
       e.putString("sessionId", sessionId);
       e.commit();
     showLogin();
     }
       break;
    case R.id.bssRateUs:
       try{
       startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getApplicationInfo().packageName)));
    }
    catch(Exception e){
    }
       break;*/
    }
}

From source file:com.android.gallery3d.ui.MenuExecutor.java

public void onMenuClicked(int action, ProgressListener listener, boolean waitOnStop, boolean showDialog) {
    int title;//w ww. j a v  a 2  s  .c  o m
    switch (action) {
    case R.id.action_select_all:
        if (mSelectionManager.inSelectAllMode()) {
            mSelectionManager.deSelectAll();
        } else {
            mSelectionManager.selectAll();
        }
        return;
    case R.id.action_crop: {
        Intent intent = getIntentBySingleSelectedPath(CropActivity.CROP_ACTION);
        ((Activity) mActivity).startActivity(intent);
        return;
    }
    case R.id.action_edit: {
        Intent intent = getIntentBySingleSelectedPath(Intent.ACTION_EDIT)
                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        ((Activity) mActivity).startActivity(Intent.createChooser(intent, null));
        return;
    }
    case R.id.action_setas: {
        Intent intent = getIntentBySingleSelectedPath(Intent.ACTION_ATTACH_DATA)
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra("mimeType", intent.getType());
        Activity activity = mActivity;
        activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.set_as)));
        return;
    }
    case R.id.action_delete:
        title = R.string.delete;
        break;
    case R.id.action_rotate_cw:
        title = R.string.rotate_right;
        break;
    case R.id.action_rotate_ccw:
        title = R.string.rotate_left;
        break;
    case R.id.action_show_on_map:
        title = R.string.show_on_map;
        break;
    default:
        return;
    }
    startAction(action, title, listener, waitOnStop, showDialog);
}

From source file:com.ephemeraldreams.gallyshuttle.ui.ScheduleActivity.java

/**
 * Display reminder confimation dialog and set alarm.
 *
 * @param event Event to get {@link PrepareAlarmReminderEvent#hour}, {@link PrepareAlarmReminderEvent#minute},
 *              and {@link PrepareAlarmReminderEvent#reminderDialogMessage}.
 */// ww w  .java2s  .  co  m
@Subscribe
public void setAlarm(PrepareAlarmReminderEvent event) {

    final Intent alarmIntent = buildAlarmIntent(event.hour, event.minute);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Set Alarm Reminder").setMessage(event.reminderDialogMessage)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(Intent.createChooser(alarmIntent, "Set alarm"));
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
    AlertDialog setReminderDialog = builder.create();
    setReminderDialog.show();
}

From source file:com.actionbarsherlock.sample.hcgallery.ContentFragment.java

void shareCurrentPhoto() {
    File externalCacheDir = getActivity().getExternalCacheDir();
    if (externalCacheDir == null) {
        Toast.makeText(getActivity(), "Error writing to USB/external storage.", Toast.LENGTH_SHORT).show();
        return;//  ww  w. j a v a  2s .  c  o  m
    }

    // Prevent media scanning of the cache directory.
    final File noMediaFile = new File(externalCacheDir, ".nomedia");
    try {
        noMediaFile.createNewFile();
    } catch (IOException e) {
    }

    // Write the bitmap to temporary storage in the external storage directory (e.g. SD card).
    // We perform the actual disk write operations on a separate thread using the
    // {@link AsyncTask} class, thus avoiding the possibility of stalling the main (UI) thread.

    final File tempFile = new File(externalCacheDir, "tempfile.jpg");

    new AsyncTask<Void, Void, Boolean>() {
        /**
         * Compress and write the bitmap to disk on a separate thread.
         * @return TRUE if the write was successful, FALSE otherwise.
         */
        protected Boolean doInBackground(Void... voids) {
            try {
                FileOutputStream fo = new FileOutputStream(tempFile, false);
                if (!mBitmap.compress(Bitmap.CompressFormat.JPEG, 60, fo)) {
                    Toast.makeText(getActivity(), "Error writing bitmap data.", Toast.LENGTH_SHORT).show();
                    return Boolean.FALSE;
                }
                return Boolean.TRUE;

            } catch (FileNotFoundException e) {
                Toast.makeText(getActivity(), "Error writing to USB/external storage.", Toast.LENGTH_SHORT)
                        .show();
                return Boolean.FALSE;
            }
        }

        /**
         * After doInBackground completes (either successfully or in failure), we invoke an
         * intent to share the photo. This code is run on the main (UI) thread.
         */
        protected void onPostExecute(Boolean result) {
            if (result != Boolean.TRUE) {
                return;
            }

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
            shareIntent.setType("image/jpeg");
            startActivity(Intent.createChooser(shareIntent, "Share photo"));
        }
    }.execute();
}

From source file:com.collecdoo.fragment.main.RegisterDriverPhotoFragment.java

private void openImageIntent(int uploadIndex) {
    //EasyImage.openChooserWithGallery(this,"Please choose",0);

    File imageFile = ImageHelper.createFile(context, "extend_picture.jpg");
    String cameraImageFullPath = imageFile.getAbsolutePath();
    cameraOutputFileUri = Uri.fromFile(imageFile);

    // Camera./*from   www  .  j  a va  2s  . c o  m*/
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    final PackageManager packageManager = context.getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraOutputFileUri);
        cameraIntents.add(intent);
    }

    // Filesystem.
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("image/*");
    galleryIntent.setAction(Intent.ACTION_PICK);

    // Chooser of filesystem options.
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

    // Add the camera options.
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[] {}));

    startActivityForResult(chooserIntent, uploadIndex);
}