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.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);/*from w  w  w. j  a v  a  2s  . c  o m*/
        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:com.activiti.android.platform.provider.transfer.ContentTransferManager.java

public static final void requestGetContent(Fragment fr, String mimetype) {
    String tmpMimetype = mimetype;
    if (TextUtils.isEmpty(mimetype)) {
        tmpMimetype = "*/*";
    }/*from   w  w  w. j  av  a 2s .  co  m*/

    if (AndroidVersion.isKitKatOrAbove()) {
        isMediaProviderSupported(fr.getActivity());

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType(tmpMimetype);
        fr.startActivityForResult(Intent.createChooser(intent, "chooser"), PICKER_REQUEST_CODE);
    } else {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType(tmpMimetype);
        fr.startActivityForResult(intent, PICKER_REQUEST_CODE);
    }
}

From source file:com.compassites.texteditor.RichTextEditorDemoActivity.java

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath());
    intent.setDataAndType(uri, "text/*");
    startActivityForResult(Intent.createChooser(intent, "Open folder"), FILE_SELECT_CODE);
}

From source file:com.concavenp.nanodegree.popularmoviesimproved.MovieDetailsFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // Handle item selection
    switch (item.getItemId()) {

    case R.id.share_trailer_item: {

        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, mTrailersCard.getFirstTrailer());
        sendIntent.setType("text/plain");
        startActivity(Intent.createChooser(sendIntent, "Share movie link"));

        return true;

    }//  w ww  .j  a  v  a2s.  c  o  m
    default: {
        return super.onOptionsItemSelected(item);
    }

    }
}

From source file:ayushi.view.fragment.SettingsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.frag_settings, container, false);

    getActivity().setTitle("About App");

    mToolbar = (Toolbar) rootView.findViewById(R.id.htab_toolbar);
    if (mToolbar != null) {
        ((ECartHomeActivity) getActivity()).setSupportActionBar(mToolbar);
    }/*w  w w . j a va2  s .c o m*/

    if (mToolbar != null) {
        ((ECartHomeActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mToolbar.setNavigationIcon(R.drawable.ic_drawer);

    }

    mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((ECartHomeActivity) getActivity()).getmDrawerLayout().openDrawer(GravityCompat.START);
        }
    });

    mToolbar.setTitleTextColor(Color.WHITE);

    submitLog = (TextView) rootView.findViewById(R.id.submit_log_txt);

    if (PreferenceHelper.getPrefernceHelperInstace().getBoolean(getActivity(), PreferenceHelper.SUBMIT_LOGS,
            true)) {

        submitLog.setText("Disable");
    } else {
        submitLog.setText("Enable");
    }

    rootView.findViewById(R.id.submit_log).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (PreferenceHelper.getPrefernceHelperInstace().getBoolean(getActivity(),
                    PreferenceHelper.SUBMIT_LOGS, true)) {
                PreferenceHelper.getPrefernceHelperInstace().setBoolean(getActivity(),
                        PreferenceHelper.SUBMIT_LOGS, false);

                submitLog.setText("Disable");
            } else {
                PreferenceHelper.getPrefernceHelperInstace().setBoolean(getActivity(),
                        PreferenceHelper.SUBMIT_LOGS, true);
                submitLog.setText("Enable");
            }

        }
    });

    rootView.setFocusableInTouchMode(true);
    rootView.requestFocus();
    rootView.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {

                Utils.switchContent(R.id.frag_container, Utils.HOME_FRAGMENT,
                        ((ECartHomeActivity) (getContext())), AnimationType.SLIDE_UP);

            }
            return true;
        }
    });

    rootView.findViewById(R.id.picasso).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://github.com/square/picasso"));
            startActivity(browserIntent);

        }
    });

    rootView.findViewById(R.id.acra).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/ACRA/acra"));
            startActivity(browserIntent);

        }
    });

    rootView.findViewById(R.id.pull_zoom_view).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://github.com/Frank-Zhu/PullZoomView"));
            startActivity(browserIntent);

        }
    });

    rootView.findViewById(R.id.list_buddies).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://github.com/jpardogo/ListBuddies"));
            startActivity(browserIntent);

        }
    });

    rootView.findViewById(R.id.list_jazzy).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://github.com/twotoasters/JazzyListView"));
            startActivity(browserIntent);

        }
    });

    rootView.findViewById(R.id.email_dev).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setType("text/plain");
            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                    new String[] { "serveroverloadofficial@gmail.com" });
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hello There");
            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Add Message here");

            emailIntent.setType("message/rfc822");

            try {
                startActivity(Intent.createChooser(emailIntent, "Send email using..."));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(getActivity(), "No email clients installed.", Toast.LENGTH_SHORT).show();
            }

        }
    });

    return rootView;
}

From source file:com.akalizakeza.apps.ishusho.activity.NewPostActivity.java

@AfterPermissionGranted(RC_CAMERA_PERMISSIONS)
private void showImagePicker() {
    // Check for camera permissions
    if (!EasyPermissions.hasPermissions(this, cameraPerms)) {
        EasyPermissions.requestPermissions(this, "This sample will upload a picture from your Camera",
                RC_CAMERA_PERMISSIONS, cameraPerms);
        return;/*from w  w w.jav a 2s.co m*/
    }

    // Choose file storage location
    File file = new File(getExternalCacheDir(), UUID.randomUUID().toString());
    mFileUri = Uri.fromFile(file);

    // Camera
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    final PackageManager packageManager = 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(packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
        cameraIntents.add(intent);
    }

    // Image Picker
    Intent pickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    Intent chooserIntent = Intent.createChooser(pickerIntent, getString(R.string.picture_chooser_title));
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
            cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
    startActivityForResult(chooserIntent, TC_PICK_IMAGE);
}

From source file:com.example.linhdq.test.documents.creation.NewDocumentActivity.java

protected void startGallery() {
    cameraPicUri = null;/*from w  ww. j a va  2  s  . c o m*/
    Intent i;
    if (Build.VERSION.SDK_INT >= 19) {
        i = new Intent(Intent.ACTION_GET_CONTENT, null);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        i.setType("image/*");
        i.putExtra(Intent.EXTRA_MIME_TYPES, new String[] { "image/png", "image/jpg", "image/jpeg" });
    } else {
        i = new Intent(Intent.ACTION_GET_CONTENT, null);
        i.setType("image/png,image/jpg, image/jpeg");
    }

    Intent chooser = Intent.createChooser(i, this.getResources().getString(R.string.image_source));
    try {
        startActivityForResult(chooser, REQUEST_CODE_PICK_PHOTO);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, R.string.no_gallery_found, Toast.LENGTH_LONG).show();
    }
}

From source file:com.agateau.equiv.ui.Kernel.java

public void shareCustomProductList(Context context) {
    File file = context.getFileStreamPath(CUSTOM_PRODUCTS_CSV);
    Uri contentUri = FileProvider.getUriForFile(context, "com.agateau.equiv.fileprovider", file);
    final Resources res = context.getResources();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[] { Constants.CUSTOM_PRODUCTS_EMAIL });
    intent.putExtra(Intent.EXTRA_SUBJECT, res.getString(R.string.share_email_subject));
    intent.putExtra(Intent.EXTRA_STREAM, contentUri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    context.startActivity(Intent.createChooser(intent, res.getString(R.string.share_via)));
}

From source file:im.delight.android.baselib.Social.java

/**
 * Constructs an SMS Intent for the given message details and opens the application chooser for this Intent
 *
 * @param recipient the recipient's phone number or `null`
 * @param body the body of the message//w  w  w  .  j  av  a  2s .c o  m
 * @param captionRes the string resource ID for the application chooser's window title
 * @param context the Context instance to start the Intent from
 * @throws Exception if there was an error trying to launch the SMS Intent
 */
public static void sendSMS(final String recipient, final String body, final int captionRes,
        final Context context) throws Exception {
    final Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setType(HTTP.PLAIN_TEXT_TYPE);
    if (recipient != null && recipient.length() > 0) {
        intent.setData(Uri.parse("smsto:" + recipient));
    } else {
        intent.setData(Uri.parse("sms:"));
    }
    intent.putExtra("sms_body", body);
    intent.putExtra(Intent.EXTRA_TEXT, body);
    if (context != null) {
        // offer a selection of all applications that can handle the SMS Intent
        context.startActivity(Intent.createChooser(intent, context.getString(captionRes)));
    }
}

From source file:com.example.android.wardrobe.HomeActivity.java

public void loadImage(final int what) {
    ContextOption[] items = new ContextOption[] {
            new ContextOption("Take picture from camera", R.drawable.camera),
            new ContextOption("Select picture from gallery", R.drawable.gallery) };
    SimpleMenuAdapter contextMenuAdapter = new SimpleMenuAdapter(this, Arrays.asList(items));
    new AlertDialog.Builder(this)
            // .setTitle("Share Appliction")
            .setAdapter(contextMenuAdapter, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int menuId) {
                    Intent intent = null;
                    switch (menuId) {
                    case 0:
                        addWhat = what;/*from  www  .jav  a2  s.c  om*/
                        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".png"));

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());

                        try {
                            intent.putExtra("return-data", true);

                            startActivityForResult(intent, PICK_FROM_CAMERA);
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                            /**
                            * TODO show message to user
                            */
                        }
                        break;
                    case 1:
                        addWhat = what;
                        intent = new Intent();

                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);

                        startActivityForResult(Intent.createChooser(intent, "Complete action using"),
                                PICK_FROM_FILE);
                        break;
                    }
                }
            }).show();
}