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.fvd.nimbus.PaintActivity.java

void setCustomBackground(DrawView v) {
    Intent fileChooserIntent = new Intent();
    fileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
    fileChooserIntent.setType("image/*");
    fileChooserIntent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(fileChooserIntent, "Select Picture"), 1);
    //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
    overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
}

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

public void getPicture() {
    try {//from   w w w  .j  a  v a 2s  .c  om
        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);
    }
}

From source file:com.apptentive.android.sdk.module.messagecenter.view.MessageCenterActivityContent.java

@Override
public void onAttachImage() {
    try {/*from   w  ww .java  2  s.  co  m*/
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {//prior Api level 19
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            Intent chooserIntent = Intent.createChooser(intent, null);
            viewActivity.startActivityForResult(chooserIntent, Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            Intent chooserIntent = Intent.createChooser(intent, null);
            viewActivity.startActivityForResult(chooserIntent, Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER);
        }
        imagePickerLaunched = true;
    } catch (Exception e) {
        e.printStackTrace();
        imagePickerLaunched = false;
        Log.d("can't launch image picker");
    }
}

From source file:com.android.calendar.EventInfoFragment.java

/**
 * Generates an .ics formatted file with the event info and launches intent chooser to
 * share said file//from   w  w  w  .  j  a v a2  s . c o  m
 */
public void shareEvent(ShareType type) {
    VCalendar calendar = generateVCalendar();
    // create and share ics file
    boolean isShareSuccessful = false;
    try {
        // event title serves as the file name prefix
        String filePrefix = calendar.getFirstEvent().getProperty(VEvent.SUMMARY);
        if (filePrefix == null || filePrefix.length() < 3) {
            // default to a generic filename if event title doesn't qualify
            // prefix length constraint is imposed by File#createTempFile
            filePrefix = "invite";
        }

        filePrefix = filePrefix.replaceAll("\\W+", " ");

        if (!filePrefix.endsWith(" ")) {
            filePrefix += " ";
        }

        File dir;
        if (type == ShareType.SDCARD) {
            dir = EXPORT_SDCARD_DIRECTORY;
            if (!dir.exists()) {
                dir.mkdir();
            }
        } else {
            dir = mActivity.getExternalCacheDir();
        }

        File inviteFile = IcalendarUtils.createTempFile(filePrefix, ".ics", dir);

        if (IcalendarUtils.writeCalendarToFile(calendar, inviteFile)) {
            if (type == ShareType.INTENT) {
                inviteFile.setReadable(true, false); // set world-readable
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(inviteFile));
                // the ics file is sent as an extra, the receiving application decides whether
                // to parse the file to extract calendar events or treat it as a regular file
                shareIntent.setType("application/octet-stream");

                Intent chooserIntent = Intent.createChooser(shareIntent,
                        getResources().getString(R.string.cal_share_intent_title));

                // The MMS app only responds to "text/x-vcalendar" so we create a chooser intent
                // that includes the targeted mms intent + any that respond to the above general
                // purpose "application/octet-stream" intent.
                File vcsInviteFile = File.createTempFile(filePrefix, ".vcs", mActivity.getExternalCacheDir());

                // for now , we are duplicating ics file and using that as the vcs file
                // TODO: revisit above
                if (IcalendarUtils.copyFile(inviteFile, vcsInviteFile)) {
                    Intent mmsShareIntent = new Intent();
                    mmsShareIntent.setAction(Intent.ACTION_SEND);
                    mmsShareIntent.setPackage("com.android.mms");
                    mmsShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcsInviteFile));
                    mmsShareIntent.setType("text/x-vcalendar");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { mmsShareIntent });
                }
                startActivity(chooserIntent);
            } else {
                if (!mInNonUiMode) {
                    String msg = getString(R.string.cal_export_succ_msg);
                    Toast.makeText(mActivity, String.format(msg, inviteFile), Toast.LENGTH_SHORT).show();
                }
            }
            isShareSuccessful = true;

        } else {
            // error writing event info to file
            isShareSuccessful = false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        isShareSuccessful = false;
    }

    if (!isShareSuccessful) {
        Log.e(TAG, "Couldn't generate ics file");
        Toast.makeText(mActivity, R.string.error_generating_ics, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.andrewshu.android.reddit.comments.CommentsListActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int rowId = (int) info.id;

    switch (item.getItemId()) {
    case Constants.SAVE_CONTEXT_ITEM:
        new SaveTask(true, getOpThingInfo(), mSettings, this).execute();
        return true;

    case Constants.UNSAVE_CONTEXT_ITEM:
        new SaveTask(false, getOpThingInfo(), mSettings, this).execute();
        return true;

    case Constants.HIDE_CONTEXT_ITEM:
        new HideTask(true, getOpThingInfo(), mSettings, this).execute();
        return true;

    case Constants.UNHIDE_CONTEXT_ITEM:
        new HideTask(false, getOpThingInfo(), mSettings, this).execute();
        return true;

    case Constants.SHARE_CONTEXT_ITEM:
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");

        intent.putExtra(Intent.EXTRA_TEXT, getOpThingInfo().getUrl());

        try {//from w ww.java  2  s  . co  m
            startActivity(Intent.createChooser(intent, "Share Link"));
        } catch (android.content.ActivityNotFoundException ex) {

        }

        return true;

    case Constants.DIALOG_HIDE_COMMENT:
        hideComment(rowId);
        return true;

    case Constants.DIALOG_SHOW_COMMENT:
        showComment(rowId);
        return true;

    case Constants.DIALOG_GOTO_PARENT:
        int myIndent = mCommentsAdapter.getItem(rowId).getIndent();
        int parentRowId;
        for (parentRowId = rowId - 1; parentRowId >= 0; parentRowId--)
            if (mCommentsAdapter.getItem(parentRowId).getIndent() < myIndent)
                break;
        getListView().setSelection(parentRowId);
        return true;

    case Constants.DIALOG_VIEW_PROFILE:
        Intent i = new Intent(this, ProfileActivity.class);
        i.setData(Util.createProfileUri(mCommentsAdapter.getItem(rowId).getAuthor()));
        startActivity(i);
        return true;

    case Constants.DIALOG_EDIT:
        mReplyTargetName = mCommentsAdapter.getItem(rowId).getName();
        mEditTargetBody = mCommentsAdapter.getItem(rowId).getBody();
        showDialog(Constants.DIALOG_EDIT);
        return true;

    case Constants.DIALOG_DELETE:
        mReplyTargetName = mCommentsAdapter.getItem(rowId).getName();
        // It must be a comment, since the OP selftext is reached via options menu, not context menu
        mDeleteTargetKind = Constants.COMMENT_KIND;
        showDialog(Constants.DIALOG_DELETE);
        return true;

    case Constants.DIALOG_REPORT:
        mReportTargetName = mCommentsAdapter.getItem(rowId).getName();
        showDialog(Constants.DIALOG_REPORT);
        return true;

    default:
        return super.onContextItemSelected(item);
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java

private void generateAndSendGeoJsonToolReport() {
    FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();
    JSONObject featureCollection = new JSONObject();

    try {/*from  w w  w.  j a  va  2s. co m*/
        Set<Map.Entry<String, ArrayList<ToolEntry>>> tools = user.getToolLog().myLog.entrySet();
        JSONArray featureList = new JSONArray();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED
                        || toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                }

                toolEntry.setToolStatus(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        : ToolEntryStatus.STATUS_SENT_UNCONFIRMED);
                JSONObject gjsonTool = toolEntry.toGeoJson(mGpsLocationTracker);
                featureList.put(gjsonTool);
            }
        }

        if (featureList.length() == 0) {
            Toast.makeText(getActivity(), getString(R.string.no_changes_to_report), Toast.LENGTH_LONG).show();

            return;
        }

        user.writeToSharedPref(getActivity());
        featureCollection.put("features", featureList);
        featureCollection.put("type", "FeatureCollection");
        featureCollection.put("crs", JSONObject.NULL);
        featureCollection.put("bbox", JSONObject.NULL);

        String toolString = featureCollection.toString(4);

        if (fiskInfoUtility.isExternalStorageWritable()) {
            fiskInfoUtility.writeMapLayerToExternalStorage(getActivity(), toolString.getBytes(),
                    getString(R.string.tool_report_file_name), getString(R.string.format_geojson), null, false);
            String directoryPath = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            String fileName = directoryPath + "/FiskInfo/api_setting.json";
            File apiSettingsFile = new File(fileName);
            String recipient = null;

            if (apiSettingsFile.exists()) {
                InputStream inputStream;
                InputStreamReader streamReader;
                JsonReader jsonReader;

                try {
                    inputStream = new BufferedInputStream(new FileInputStream(apiSettingsFile));
                    streamReader = new InputStreamReader(inputStream, "UTF-8");
                    jsonReader = new JsonReader(streamReader);

                    jsonReader.beginObject();
                    while (jsonReader.hasNext()) {
                        String name = jsonReader.nextName();
                        if (name.equals("email")) {
                            recipient = jsonReader.nextString();
                        } else {
                            jsonReader.skipValue();
                        }
                    }
                    jsonReader.endObject();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
            }

            recipient = recipient == null ? getString(R.string.tool_report_recipient_email) : recipient;
            String[] recipients = new String[] { recipient };
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("plain/plain");

            String toolIds;
            StringBuilder sb = new StringBuilder();

            sb.append("Redskapskoder:\n");

            for (int i = 0; i < featureList.length(); i++) {
                sb.append(Integer.toString(i + 1));
                sb.append(": ");
                sb.append(featureList.getJSONObject(i).getJSONObject("properties").getString("ToolId"));
                sb.append("\n");
            }

            toolIds = sb.toString();

            intent.putExtra(Intent.EXTRA_EMAIL, recipients);
            intent.putExtra(Intent.EXTRA_TEXT, toolIds);
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.tool_report_email_header));
            File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()
                            + "/FiskInfo/Redskapsrapport.geojson");
            Uri uri = Uri.fromFile(file);
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            startActivity(Intent.createChooser(intent, getString(R.string.send_tool_report_intent_header)));

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.dish.browser.activity.BrowserActivity.java

@Override
/**//  w w w  .  j  av a  2 s  .c o  m
 * opens a file chooser
 * param ValueCallback is the message from the WebView indicating a file chooser
 * should be opened
 */
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
    mUploadMessage = uploadMsg;
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    i.setType("*/*");
    startActivityForResult(Intent.createChooser(i, getString(R.string.title_file_chooser)), 1);
}

From source file:com.androzic.MapActivity.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menuSearch:
        onSearchRequested();/*from w  w w . ja va 2  s  .  co m*/
        return true;
    case R.id.menuAddWaypoint: {
        double[] loc = application.getMapCenter();
        Waypoint waypoint = new Waypoint("", "", loc[0], loc[1]);
        waypoint.date = Calendar.getInstance().getTime();
        int wpt = application.addWaypoint(waypoint);
        waypoint.name = "WPT" + wpt;
        application.saveDefaultWaypoints();
        map.update();
        return true;
    }
    case R.id.menuNewWaypoint:
        startActivityForResult(new Intent(this, WaypointProperties.class).putExtra("INDEX", -1),
                RESULT_SAVE_WAYPOINT);
        return true;
    case R.id.menuProjectWaypoint:
        startActivityForResult(new Intent(this, WaypointProject.class), RESULT_SAVE_WAYPOINT);
        return true;
    case R.id.menuManageWaypoints:
        startActivityForResult(new Intent(this, WaypointList.class), RESULT_MANAGE_WAYPOINTS);
        return true;
    case R.id.menuLoadWaypoints:
        startActivityForResult(new Intent(this, WaypointFileList.class), RESULT_LOAD_WAYPOINTS);
        return true;
    case R.id.menuManageTracks:
        startActivityForResult(new Intent(this, TrackList.class), RESULT_MANAGE_TRACKS);
        return true;
    case R.id.menuExportCurrentTrack:
        FragmentManager fm = getSupportFragmentManager();
        TrackExportDialog trackExportDialog = new TrackExportDialog(locationService);
        trackExportDialog.show(fm, "track_export");
        return true;
    case R.id.menuExpandCurrentTrack:
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.warning)
                .setMessage(R.string.msg_expandcurrenttrack)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (application.currentTrackOverlay != null) {
                            Track track = locationService.getTrack();
                            track.show = true;
                            application.currentTrackOverlay.setTrack(track);
                        }
                    }
                }).setNegativeButton(R.string.no, null).show();
        return true;
    case R.id.menuClearCurrentTrack:
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.warning)
                .setMessage(R.string.msg_clearcurrenttrack)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (application.currentTrackOverlay != null)
                            application.currentTrackOverlay.clear();
                        locationService.clearTrack();
                    }
                }).setNegativeButton(R.string.no, null).show();
        return true;
    case R.id.menuManageRoutes:
        startActivityForResult(new Intent(this, RouteList.class).putExtra("MODE", RouteList.MODE_MANAGE),
                RESULT_MANAGE_ROUTES);
        return true;
    case R.id.menuStartNavigation:
        if (application.getRoutes().size() > 1) {
            startActivity(new Intent(this, RouteList.class).putExtra("MODE", RouteList.MODE_START));
        } else {
            startActivity(new Intent(this, RouteStart.class).putExtra("INDEX", 0));
        }
        return true;
    case R.id.menuNavigationDetails:
        startActivity(new Intent(this, RouteDetails.class)
                .putExtra("index", application.getRouteIndex(navigationService.navRoute))
                .putExtra("nav", true));
        return true;
    case R.id.menuNextNavPoint:
        navigationService.nextRouteWaypoint();
        return true;
    case R.id.menuPrevNavPoint:
        navigationService.prevRouteWaypoint();
        return true;
    case R.id.menuStopNavigation: {
        navigationService.stopNavigation();
        return true;
    }
    case R.id.menuHSI:
        startActivity(new Intent(this, HSIActivity.class));
        return true;
    case R.id.menuInformation:
        startActivity(new Intent(this, Information.class));
        return true;
    case R.id.menuMapInfo:
        startActivity(new Intent(this, MapInformation.class));
        return true;
    case R.id.menuCursorMaps:
        startActivityForResult(new Intent(this, MapList.class).putExtra("pos", true),
                RESULT_LOAD_MAP_ATPOSITION);
        return true;
    case R.id.menuAllMaps:
        startActivityForResult(new Intent(this, MapList.class), RESULT_LOAD_MAP);
        return true;
    case R.id.menuShare:
        Intent i = new Intent(android.content.Intent.ACTION_SEND);
        i.setType("text/plain");
        i.putExtra(Intent.EXTRA_SUBJECT, R.string.currentloc);
        double[] sloc = application.getMapCenter();
        String spos = StringFormatter.coordinates(application.coordinateFormat, " ", sloc[0], sloc[1]);
        i.putExtra(Intent.EXTRA_TEXT, spos);
        startActivity(Intent.createChooser(i, getString(R.string.menu_share)));
        return true;
    case R.id.menuCopyLocation: {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        double[] cloc = application.getMapCenter();
        String cpos = StringFormatter.coordinates(application.coordinateFormat, " ", cloc[0], cloc[1]);
        clipboard.setText(cpos);
        return true;
    }
    case R.id.menuPasteLocation: {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        if (clipboard.hasText()) {
            String q = clipboard.getText().toString();
            try {
                double c[] = CoordinateParser.parse(q);
                if (!Double.isNaN(c[0]) && !Double.isNaN(c[1])) {
                    boolean mapChanged = application.setMapCenter(c[0], c[1], true, false);
                    if (mapChanged)
                        map.updateMapInfo();
                    map.update();
                    map.setFollowing(false);
                }
            } catch (IllegalArgumentException e) {
            }
        }
        return true;
    }
    case R.id.menuSetAnchor:
        if (showDistance > 0) {
            application.distanceOverlay.setAncor(application.getMapCenter());
            application.distanceOverlay.setEnabled(true);
        }
        return true;
    case R.id.menuPreferences:
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            startActivity(new Intent(this, Preferences.class));
        } else {
            startActivity(new Intent(this, PreferencesHC.class));
        }
        return true;
    }
    return false;
}

From source file:biz.bokhorst.xprivacy.ActivityShare.java

public void fileChooser() {
    Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/.xprivacy/");
    chooseFile.setDataAndType(uri, "text/xml");
    Intent intent = Intent.createChooser(chooseFile, getString(R.string.app_name));
    startActivityForResult(intent, ACTIVITY_IMPORT_SELECT);
}

From source file:com.android.launcher2.Launcher.java

private void startWallpaper() {
    showWorkspace(true);/*from w  ww .jav  a2  s. com*/
    final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
    Intent chooser = Intent.createChooser(pickWallpaper, getText(R.string.chooser_wallpaper));
    // NOTE: Adds a configure option to the chooser if the wallpaper supports it
    //       Removed in Eclair MR1
    //        WallpaperManager wm = (WallpaperManager)
    //                getSystemService(Context.WALLPAPER_SERVICE);
    //        WallpaperInfo wi = wm.getWallpaperInfo();
    //        if (wi != null && wi.getSettingsActivity() != null) {
    //            LabeledIntent li = new LabeledIntent(getPackageName(),
    //                    R.string.configure_wallpaper, 0);
    //            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
    //            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
    //        }
    startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
}