Example usage for android.content Intent EXTRA_STREAM

List of usage examples for android.content Intent EXTRA_STREAM

Introduction

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

Prototype

String EXTRA_STREAM

To view the source code for android.content Intent EXTRA_STREAM.

Click Source Link

Document

A content: URI holding a stream of data associated with the Intent, used with #ACTION_SEND to supply the data being sent.

Usage

From source file:com.asksven.betterbatterystats.StatsActivity.java

public Dialog getShareDialog() {

    final ArrayList<Integer> selectedSaveActions = new ArrayList<Integer>();

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean saveDumpfile = sharedPrefs.getBoolean("save_dumpfile", true);
    boolean saveLogcat = sharedPrefs.getBoolean("save_logcat", false);
    boolean saveDmesg = sharedPrefs.getBoolean("save_dmesg", false);

    if (saveDumpfile) {
        selectedSaveActions.add(0);//www  . j a va2s  . c  o  m
    }
    if (saveLogcat) {
        selectedSaveActions.add(1);
    }
    if (saveDmesg) {
        selectedSaveActions.add(2);
    }

    //----
    LinearLayout layout = new LinearLayout(this);
    LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(parms);

    layout.setGravity(Gravity.CLIP_VERTICAL);
    layout.setPadding(2, 2, 2, 2);

    final TextView editTitle = new TextView(StatsActivity.this);
    editTitle.setText(R.string.share_dialog_edit_title);
    editTitle.setPadding(40, 40, 40, 40);
    editTitle.setGravity(Gravity.LEFT);
    editTitle.setTextSize(20);

    final EditText editDescription = new EditText(StatsActivity.this);

    LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    tv1Params.bottomMargin = 5;
    layout.addView(editTitle, tv1Params);
    layout.addView(editDescription, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));

    //----

    // Set the dialog title
    builder.setTitle(R.string.title_share_dialog)
            .setMultiChoiceItems(R.array.saveAsLabels, new boolean[] { saveDumpfile, saveLogcat, saveDmesg },
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            if (isChecked) {
                                // If the user checked the item, add it to the
                                // selected items
                                selectedSaveActions.add(which);
                            } else if (selectedSaveActions.contains(which)) {
                                // Else, if the item is already in the array,
                                // remove it
                                selectedSaveActions.remove(Integer.valueOf(which));
                            }
                        }
                    })
            .setView(layout)
            // Set the action buttons
            .setPositiveButton(R.string.label_button_share, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    ArrayList<Uri> attachements = new ArrayList<Uri>();

                    Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName,
                            StatsActivity.this);
                    Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName,
                            StatsActivity.this);

                    Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);

                    // save as text is selected
                    if (selectedSaveActions.contains(0)) {
                        attachements.add(reading.writeDumpfile(StatsActivity.this,
                                editDescription.getText().toString()));
                    }
                    // save logcat if selected
                    if (selectedSaveActions.contains(1)) {
                        attachements.add(StatsProvider.getInstance().writeLogcatToFile());
                    }
                    // save dmesg if selected
                    if (selectedSaveActions.contains(2)) {
                        attachements.add(StatsProvider.getInstance().writeDmesgToFile());
                    }

                    if (!attachements.isEmpty()) {
                        Intent shareIntent = new Intent();
                        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachements);
                        shareIntent.setType("text/*");
                        startActivity(Intent.createChooser(shareIntent, "Share info to.."));
                    }
                }
            }).setNeutralButton(R.string.label_button_save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    try {
                        Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName,
                                StatsActivity.this);
                        Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName,
                                StatsActivity.this);

                        Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);

                        // save as text is selected
                        if (selectedSaveActions.contains(0)) {
                            reading.writeDumpfile(StatsActivity.this, editDescription.getText().toString());
                        }
                        // save logcat if selected
                        if (selectedSaveActions.contains(1)) {
                            StatsProvider.getInstance().writeLogcatToFile();
                        }
                        // save dmesg if selected
                        if (selectedSaveActions.contains(2)) {
                            StatsProvider.getInstance().writeDmesgToFile();
                        }

                        Snackbar.make(findViewById(android.R.id.content), getString(R.string.info_files_written)
                                + ": " + StatsProvider.getWritableFilePath(), Snackbar.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Log.e(TAG, "an error occured writing files: " + e.getMessage());
                        Snackbar.make(findViewById(android.R.id.content), R.string.info_files_write_error,
                                Snackbar.LENGTH_LONG).show();
                    }

                }
            }).setNegativeButton(R.string.label_button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // do nothing
                }
            });

    return builder.create();
}

From source file:kr.wdream.ui.PhotoViewer.java

private void onSharePressed() {
    if (parentActivity == null || !allowShare) {
        return;/*from w w  w  . ja va 2  s. c o m*/
    }
    try {
        File f = null;
        boolean isVideo = false;

        if (currentMessageObject != null) {
            isVideo = currentMessageObject.isVideo();
            /*if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
                AndroidUtilities.openUrl(parentActivity, currentMessageObject.messageOwner.media.webpage.url);
                return;
            }*/
            f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
        } else if (currentFileLocation != null) {
            f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
        }

        if (f.exists()) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            if (isVideo) {
                intent.setType("video/mp4");
            } else {
                intent.setType("image/jpeg");
            }
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));

            parentActivity.startActivityForResult(
                    Intent.createChooser(intent,
                            LocaleController.getString("ShareFile", kr.wdream.storyshop.R.string.ShareFile)),
                    500);
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
            builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
            builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null);
            builder.setMessage(
                    LocaleController.getString("PleaseDownload", kr.wdream.storyshop.R.string.PleaseDownload));
            showAlertDialog(builder);
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:net.bluehack.ui.PhotoViewer.java

private void onSharePressed() {
    if (parentActivity == null || !allowShare) {
        return;/* ww w  . j a v a2s  . c  o  m*/
    }
    try {
        File f = null;
        boolean isVideo = false;

        if (currentMessageObject != null) {
            isVideo = currentMessageObject.isVideo();
            /*if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
                AndroidUtilities.openUrl(parentActivity, currentMessageObject.messageOwner.media.webpage.url);
                return;
            }*/
            f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
        } else if (currentFileLocation != null) {
            f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
        }

        if (f.exists()) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            if (isVideo) {
                intent.setType("video/mp4");
            } else {
                intent.setType("image/jpeg");
            }
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));

            parentActivity.startActivityForResult(
                    Intent.createChooser(intent, LocaleController.getString("ShareFile", R.string.ShareFile)),
                    500);
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
            builder.setMessage(LocaleController.getString("PleaseDownload", R.string.PleaseDownload));
            showAlertDialog(builder);
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.kncwallet.wallet.ui.WalletActivity.java

private void mailPrivateKeys(@Nonnull final File file) {
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_keys_dialog_mail_subject));
    intent.putExtra(Intent.EXTRA_TEXT,/*from  ww w . j a  v  a  2  s . com*/
            getString(R.string.export_keys_dialog_mail_text) + "\n\n"
                    + String.format(Constants.WEBMARKET_APP_URL, getPackageName()) + "\n\n"
                    + Constants.SOURCE_URL + '\n');
    intent.setType("x-bitcoin/private-keys");
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    startActivity(Intent.createChooser(intent, getString(R.string.export_keys_dialog_mail_intent_chooser)));

    log.info("invoked archive private keys chooser");
}

From source file:de.baumann.browser.Browser.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from   w  w  w.  j a  v  a  2 s .  c om
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_search) {

        mWebView.stopLoading();
        String text = editText.getText().toString();
        String searchEngine = sharedPref.getString("searchEngine", "https://startpage.com/do/search?query=");
        String wikiLang = sharedPref.getString("wikiLang", "en");

        if (text.length() > 3) {
            subStr = text.substring(3);
        }

        if (text.equals(mWebView.getTitle()) || text.isEmpty()) {
            helper_editText.showKeyboard(Browser.this, editText, 3, "", getString(R.string.app_search_hint));

        } else {
            helper_editText.hideKeyboard(Browser.this, editText, 0, text, getString(R.string.app_search_hint));
            helper_editText.editText_EditorAction(editText, Browser.this, mWebView);

            if (text.startsWith("www")) {
                mWebView.loadUrl("http://" + text);
            } else if (text.contains("http")) {
                mWebView.loadUrl(text);
            } else if (text.contains(".w ")) {
                mWebView.loadUrl("https://" + wikiLang + ".wikipedia.org/wiki/Spezial:Suche?search=" + subStr);
            } else if (text.startsWith(".f ")) {
                mWebView.loadUrl("https://www.flickr.com/search/?advanced=1&license=2%2C3%2C4%2C5%2C6%2C9&text="
                        + subStr);
            } else if (text.startsWith(".m ")) {
                mWebView.loadUrl("https://metager.de/meta/meta.ger3?focus=web&eingabe=" + subStr);
            } else if (text.startsWith(".g ")) {
                mWebView.loadUrl("https://github.com/search?utf8=&q=" + subStr);
            } else if (text.startsWith(".s ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl(
                            "https://startpage.com/do/search?query=" + subStr + "&lui=deutsch&l=deutsch");
                } else {
                    mWebView.loadUrl("https://startpage.com/do/search?query=" + subStr);
                }
            } else if (text.startsWith(".G ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl("https://www.google.de/search?&q=" + subStr);
                } else {
                    mWebView.loadUrl("https://www.google.com/search?&q=" + subStr);
                }
            } else if (text.startsWith(".y ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl("https://www.youtube.com/results?hl=de&gl=DE&search_query=" + subStr);
                } else {
                    mWebView.loadUrl("https://www.youtube.com/results?search_query=" + subStr);
                }
            } else if (text.startsWith(".d ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl("https://duckduckgo.com/?q=" + subStr
                            + "&kl=de-de&kad=de_DE&k1=-1&kaj=m&kam=osm&kp=-1&kak=-1&kd=1&t=h_&ia=web");
                } else {
                    mWebView.loadUrl("https://duckduckgo.com/?q=" + subStr);
                }
            } else {
                if (searchEngine.contains("https://duckduckgo.com/?q=")) {
                    if (Locale.getDefault().getLanguage().contentEquals("de")) {
                        mWebView.loadUrl("https://duckduckgo.com/?q=" + text
                                + "&kl=de-de&kad=de_DE&k1=-1&kaj=m&kam=osm&kp=-1&kak=-1&kd=1&t=h_&ia=web");
                    } else {
                        mWebView.loadUrl("https://duckduckgo.com/?q=" + text);
                    }
                } else if (searchEngine.contains("https://metager.de/meta/meta.ger3?focus=web&eingabe=")) {
                    if (Locale.getDefault().getLanguage().contentEquals("de")) {
                        mWebView.loadUrl("https://metager.de/meta/meta.ger3?focus=web&eingabe=" + text);
                    } else {
                        mWebView.loadUrl("https://metager.de/meta/meta.ger3?focus=web&eingabe=" + text
                                + "&focus=web&encoding=utf8&lang=eng");
                    }
                } else if (searchEngine.contains("https://startpage.com/do/search?query=")) {
                    if (Locale.getDefault().getLanguage().contentEquals("de")) {
                        mWebView.loadUrl(
                                "https://startpage.com/do/search?query=" + text + "&lui=deutsch&l=deutsch");
                    } else {
                        mWebView.loadUrl("https://startpage.com/do/search?query=" + text);
                    }
                } else {
                    mWebView.loadUrl(searchEngine + text);
                }
            }
        }
    }

    if (id == R.id.action_history) {
        helper_main.switchToActivity(Browser.this, Popup_history.class, "", false);
    }

    if (id == R.id.action_search3) {
        helper_editText.editText_searchWeb(editText, Browser.this);
    }

    if (id == R.id.action_pass) {
        helper_main.switchToActivity(Browser.this, Popup_pass.class, "", false);
        sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
        sharedPref.edit().putString("pass_copy_title", mWebView.getTitle()).apply();
    }

    if (id == R.id.action_toggle) {

        sharedPref.edit().putString("started", "yes").apply();
        String link = mWebView.getUrl();
        int domainInt = link.indexOf("//") + 2;
        final String domain = link.substring(domainInt, link.indexOf('/', domainInt));
        final String whiteList = sharedPref.getString("whiteList", "");

        AlertDialog.Builder builder = new AlertDialog.Builder(Browser.this);
        View dialogView = View.inflate(Browser.this, R.layout.dialog_toggle, null);

        Switch sw_java = (Switch) dialogView.findViewById(R.id.switch1);
        Switch sw_pictures = (Switch) dialogView.findViewById(R.id.switch2);
        Switch sw_location = (Switch) dialogView.findViewById(R.id.switch3);
        Switch sw_cookies = (Switch) dialogView.findViewById(R.id.switch4);
        final ImageButton whiteList_js = (ImageButton) dialogView.findViewById(R.id.imageButton_js);

        if (whiteList.contains(domain)) {
            whiteList_js.setImageResource(R.drawable.check_green);
        } else {
            whiteList_js.setImageResource(R.drawable.close_red);
        }
        if (sharedPref.getString("java_string", "True").equals(getString(R.string.app_yes))) {
            sw_java.setChecked(true);
        } else {
            sw_java.setChecked(false);
        }
        if (sharedPref.getString("pictures_string", "True").equals(getString(R.string.app_yes))) {
            sw_pictures.setChecked(true);
        } else {
            sw_pictures.setChecked(false);
        }
        if (sharedPref.getString("loc_string", "True").equals(getString(R.string.app_yes))) {
            sw_location.setChecked(true);
        } else {
            sw_location.setChecked(false);
        }
        if (sharedPref.getString("cookie_string", "True").equals(getString(R.string.app_yes))) {
            sw_cookies.setChecked(true);
        } else {
            sw_cookies.setChecked(false);
        }

        whiteList_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (whiteList.contains(domain)) {
                    whiteList_js.setImageResource(R.drawable.close_red);
                    String removed = whiteList.replaceAll(domain, "");
                    sharedPref.edit().putString("whiteList", removed).apply();
                } else {
                    whiteList_js.setImageResource(R.drawable.check_green);
                    sharedPref.edit().putString("whiteList", whiteList + " " + domain).apply();
                }
            }
        });
        sw_java.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("java_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(true);
                } else {
                    sharedPref.edit().putString("java_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(false);
                }

            }
        });
        sw_pictures.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                } else {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(false);
                }

            }
        });
        sw_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setGeolocationEnabled(true);
                    helper_main.grantPermissionsLoc(Browser.this);
                } else {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setGeolocationEnabled(false);
                }

            }
        });
        sw_cookies.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_yes)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                } else {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_no)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(false);
                }

            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.menu_toggle_title);
        builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                mWebView.reload();
            }
        });
        builder.setNegativeButton(R.string.menu_settings, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
                sharedPref.edit().putString("lastActivity", "browser").apply();
                helper_main.switchToActivity(Browser.this, Activity_settings.class, "", true);
            }
        });

        final AlertDialog dialog = builder.create();
        // Display the custom alert dialog on interface
        dialog.show();

    }

    if (id == R.id.action_save) {
        final CharSequence[] options = { getString(R.string.menu_save_screenshot),
                getString(R.string.menu_save_bookmark), getString(R.string.menu_save_readLater),
                getString(R.string.menu_save_pass), getString(R.string.menu_createShortcut) };
        new AlertDialog.Builder(Browser.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.menu_save_bookmark))) {
                            helper_editText.editText_saveBookmark(editText, Browser.this, mWebView);
                        }
                        if (options[item].equals(getString(R.string.menu_save_pass))) {
                            helper_editText.editText_savePass(Browser.this, mWebView, mWebView.getTitle(),
                                    mWebView.getUrl());
                        }
                        if (options[item].equals(getString(R.string.menu_save_readLater))) {
                            try {
                                final Database_ReadLater db = new Database_ReadLater(Browser.this);
                                db.addBookmark(mWebView.getTitle(), mWebView.getUrl());
                                db.close();
                                Snackbar.make(mWebView, R.string.readLater_added, Snackbar.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (options[item].equals(getString(R.string.menu_save_screenshot))) {
                            screenshot();
                        }
                        if (options[item].equals(getString(R.string.menu_createShortcut))) {
                            Intent i = new Intent();
                            i.setAction(Intent.ACTION_VIEW);
                            i.setClassName(Browser.this, "de.baumann.browser.Browser");
                            i.setData(Uri.parse(mWebView.getUrl()));

                            Intent shortcut = new Intent();
                            shortcut.putExtra("android.intent.extra.shortcut.INTENT", i);
                            shortcut.putExtra("android.intent.extra.shortcut.NAME",
                                    "THE NAME OF SHORTCUT TO BE SHOWN");
                            shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, mWebView.getTitle());
                            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                                    .fromContext(Browser.this.getApplicationContext(), R.mipmap.ic_launcher));
                            shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
                            Browser.this.sendBroadcast(shortcut);
                            Snackbar.make(mWebView, R.string.menu_createShortcut_success, Snackbar.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }).show();
    }

    if (id == R.id.action_share) {
        final CharSequence[] options = { getString(R.string.menu_share_screenshot),
                getString(R.string.menu_share_link), getString(R.string.menu_share_link_copy) };
        new AlertDialog.Builder(Browser.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.menu_share_link))) {
                            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                            sharingIntent.setType("text/plain");
                            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
                            sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
                            startActivity(
                                    Intent.createChooser(sharingIntent, (getString(R.string.app_share_link))));
                        }
                        if (options[item].equals(getString(R.string.menu_share_screenshot))) {
                            screenshot();

                            if (shareFile.exists()) {
                                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                sharingIntent.setType("image/png");
                                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
                                sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
                                Uri bmpUri = Uri.fromFile(shareFile);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                                startActivity(Intent.createChooser(sharingIntent,
                                        (getString(R.string.app_share_screenshot))));
                            }
                        }
                        if (options[item].equals(getString(R.string.menu_share_link_copy))) {
                            String url = mWebView.getUrl();
                            ClipboardManager clipboard = (ClipboardManager) Browser.this
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                            Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }).show();
    }

    if (id == R.id.action_downloads) {
        String startDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getPath();
        helper_main.openFilePicker(Browser.this, mWebView, startDir);
    }

    if (id == R.id.action_searchSite) {
        mWebView.stopLoading();
        helper_editText.editText_FocusChange_searchSite(editText, Browser.this);
        helper_editText.editText_searchSite(editText, Browser.this, mWebView);
    }

    if (id == R.id.action_search2) {

        String text = editText.getText().toString();

        if (text.startsWith(getString(R.string.app_search))) {
            helper_editText.editText_searchSite(editText, Browser.this, mWebView);
        } else {
            mWebView.findAllAsync(text);
            helper_editText.hideKeyboard(Browser.this, editText, 1, getString(R.string.app_search) + " " + text,
                    getString(R.string.app_search_hint_site));
        }

    }

    if (id == R.id.action_prev) {
        mWebView.findNext(false);
    }

    if (id == R.id.action_next) {
        mWebView.findNext(true);
    }

    if (id == R.id.action_cancel) {
        helper_editText.editText_FocusChange(editText, Browser.this);
        helper_editText.editText_EditorAction(editText, Browser.this, mWebView);
        helper_editText.hideKeyboard(Browser.this, editText, 0, mWebView.getTitle(),
                getString(R.string.app_search_hint));
    }

    if (id == R.id.action_save_bookmark) {
        helper_editText.editText_saveBookmark_save(editText, Browser.this, mWebView);
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.android.contacts.activities.PeopleActivity.java

/**
 * Share all contacts that are currently selected in mAllFragment. This method is pretty
 * inefficient for handling large numbers of contacts. I don't expect this to be a problem.
 *//* w w  w .  java  2s  .c o m*/
private void shareSelectedContacts() {
    final StringBuilder uriListBuilder = new StringBuilder();
    for (Long contactId : mAllFragment.getSelectedContactIds()) {
        final Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
        final Uri lookupUri = Contacts.getLookupUri(getContentResolver(), contactUri);
        if (lookupUri == null) {
            continue;
        }
        final List<String> pathSegments = lookupUri.getPathSegments();
        if (pathSegments.size() < 2) {
            continue;
        }
        final String lookupKey = pathSegments.get(pathSegments.size() - 2);
        if (uriListBuilder.length() > 0) {
            uriListBuilder.append(':');
        }
        uriListBuilder.append(Uri.encode(lookupKey));
    }
    if (uriListBuilder.length() == 0) {
        return;
    }
    final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI,
            Uri.encode(uriListBuilder.toString()));
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType(Contacts.CONTENT_VCARD_TYPE);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    ImplicitIntentsUtil.startActivityOutsideApp(this, intent);
}

From source file:activities.PaintActivity.java

private void invokeApplication(String packageName, Resources resources) {

    int requestCode = 0;
    Log.d("DialogShare", "Seleccionado ... " + packageName);
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.setType("image/*");

    shareIntent.setPackage(packageName);

    //Image/*from   ww  w.  j  a v a  2s . c o  m*/
    Bitmap bitmap = painter.getImageBitmap();

    if ((uriTempImage = PaintUtility.saveTempPhoto(this, bitmap)) == null)
        Toast.makeText(this, "Error al crear imagonen ", Toast.LENGTH_SHORT).show();

    shareIntent.putExtra(Intent.EXTRA_STREAM, uriTempImage);

    if (packageName.contains("twitter")) {
        shareIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(string.sharecontent_twitter_text));
        requestCode = RS_CODE_SHARE_TWITTER;

    } else if (packageName.contains("facebook")) {
        // Warning: Facebook IGNORES our text. They say "These fields are intended for users to express themselves. Pre-filling these fields erodes the authenticity of the user voice."
        // One workaround is to use the Facebook SDK to post, but that doesn't allow the user to choose how they want to share. We can also make a custom landing page, and the link
        // will show the <meta content ="..."> text from that page with our link in Facebook.
        shareIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(string.sharecontent_fb_text));
        requestCode = RS_CODE_SHARE_FB;
    } else if (packageName.contains("gm")) {

        shareIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(string.sharecontent_email_text));
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(string.sharecontent_subject));
        shareIntent.setType("message/rfc822");
        requestCode = RS_CODE_SHARE_GMAIL;
    }

    startActivityForResult(shareIntent, requestCode);
}

From source file:com.irccloud.android.activity.MainActivity.java

private void setFromIntent(Intent intent) {
    launchBid = -1;//from   www. j  ava 2  s. co m
    launchURI = null;

    if (NetworkConnection.getInstance().ready)
        setIntent(new Intent(this, MainActivity.class));

    if (intent.hasExtra("bid")) {
        int new_bid = intent.getIntExtra("bid", 0);
        if (NetworkConnection.getInstance().ready
                && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                && BuffersDataSource.getInstance().getBuffer(new_bid) == null) {
            Crashlytics.log(Log.WARN, "IRCCloud", "Invalid bid requested by launch intent: " + new_bid);
            Notifications.getInstance().deleteNotificationsForBid(new_bid);
            if (excludeBIDTask != null)
                excludeBIDTask.cancel(true);
            excludeBIDTask = new ExcludeBIDTask();
            excludeBIDTask.execute(new_bid);
            return;
        } else if (BuffersDataSource.getInstance().getBuffer(new_bid) != null) {
            Crashlytics.log(Log.DEBUG, "IRCCloud", "Found BID, switching buffers");
            if (buffer != null && buffer.bid != new_bid)
                backStack.add(0, buffer.bid);
            buffer = BuffersDataSource.getInstance().getBuffer(new_bid);
            server = ServersDataSource.getInstance().getServer(buffer.cid);
        } else {
            Crashlytics.log(Log.DEBUG, "IRCCloud", "BID not found, will try after reconnecting");
            launchBid = new_bid;
        }
    }

    if (intent.getData() != null && intent.getData().getScheme() != null
            && intent.getData().getScheme().startsWith("irc")) {
        if (open_uri(intent.getData())) {
            return;
        } else {
            launchURI = intent.getData();
            buffer = null;
            server = null;
        }
    } else if (intent.hasExtra("cid")) {
        if (buffer == null) {
            buffer = BuffersDataSource.getInstance().getBufferByName(intent.getIntExtra("cid", 0),
                    intent.getStringExtra("name"));
            if (buffer != null) {
                server = ServersDataSource.getInstance().getServer(intent.getIntExtra("cid", 0));
            }
        }
    }

    if (buffer == null) {
        server = null;
    } else {
        if (intent.hasExtra(Intent.EXTRA_STREAM)) {
            String type = getContentResolver().getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
            if (type != null && type.startsWith("image/")
                    && (!NetworkConnection.getInstance().uploadsAvailable()
                            || PreferenceManager.getDefaultSharedPreferences(this)
                                    .getString("image_service", "IRCCloud").equals("imgur"))) {
                new ImgurRefreshTask((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM)).execute((Void) null);
            } else {
                fileUploadTask = new FileUploadTask((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM), this);
                fileUploadTask.execute((Void) null);
            }
        }

        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            if (intent.hasExtra(Intent.EXTRA_SUBJECT))
                buffer.draft = intent.getStringExtra(Intent.EXTRA_SUBJECT) + " ("
                        + intent.getStringExtra(Intent.EXTRA_TEXT) + ")";
            else
                buffer.draft = intent.getStringExtra(Intent.EXTRA_TEXT);
        }
    }

    if (buffer == null) {
        launchBid = intent.getIntExtra("bid", -1);
    } else {
        onBufferSelected(buffer.bid);
    }
}

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 ww .  j  a  v  a  2s .com
 */
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:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java

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

    try {// w ww .j a  v  a 2  s  .  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();
    }
}