Example usage for android.content Intent EXTRA_TEXT

List of usage examples for android.content Intent EXTRA_TEXT

Introduction

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

Prototype

String EXTRA_TEXT

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

Click Source Link

Document

A constant CharSequence that is associated with the Intent, used with #ACTION_SEND to supply the literal data to be sent.

Usage

From source file:com.armtimes.activities.SingleArticlePreviewActivity.java

private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    // Get Description.
    String description = getIntent().getStringExtra(EXTRA_SHORT_DESC);
    if (description == null || description.isEmpty())
        return null;

    String url = getIntent().getStringExtra(EXTRA_URL);
    if (url == null || url.isEmpty())
        return null;

    description = Html.fromHtml(description).toString();

    final String textToShare = String.format("%s... <a href=\"%s\">%s</a>", description, url,
            getString(R.string.read_more));
    shareIntent.putExtra(Intent.EXTRA_TEXT, textToShare);
    return shareIntent;
}

From source file:gov.whitehouse.ui.fragments.app.ArticleViewerFragment.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    ActionBar actionBar = getSherlockActivity().getSupportActionBar();

    if (!((BaseActivity) getSherlockActivity()).isMultipaned()) {
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayUseLogoEnabled(false);
    }/*from  w  w  w  .ja  v  a 2 s .co  m*/

    MenuItem shareItem = menu.findItem(R.id.menu_share);
    shareItem.setVisible(true);
    Intent shareIntent;
    try {
        shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, mPageInfo.getString("url"));
        ShareActionProvider sap = (ShareActionProvider) shareItem.getActionProvider();
        sap.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
        sap.setShareIntent(shareIntent);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    MenuItem favoriteItem = menu.findItem(R.id.menu_favorite);
    favoriteItem.setVisible(true);
    if (mFavorited) {
        favoriteItem.setTitle(R.string.unfavorite);
        favoriteItem.setIcon(R.drawable.ic_favorite);
    } else {
        favoriteItem.setTitle(R.string.favorite);
        favoriteItem.setIcon(R.drawable.ic_unfavorite);
    }
}

From source file:com.cerema.cloud2.ui.activity.ShareActivity.java

/**
 * Updates the view associated to the activity after the finish of some operation over files
 * in the current account./*from w  w w  . j  av  a2  s . c o  m*/
 *
 * @param operation Removal operation performed.
 * @param result    Result of the removal.
 */
@Override
public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
    super.onRemoteOperationFinish(operation, result);

    if (result.isSuccess() || (operation instanceof GetSharesForFileOperation
            && result.getCode() == RemoteOperationResult.ResultCode.SHARE_NOT_FOUND)) {
        Log_OC.d(TAG, "Refreshing view on successful operation or finished refresh");
        refreshSharesFromStorageManager();
    }

    if (operation instanceof CreateShareViaLinkOperation && result.isSuccess()) {
        // Send link to the app
        String link = ((OCShare) (result.getData().get(0))).getShareLink();
        Log_OC.d(TAG, "Share link = " + link);

        Intent intentToShareLink = new Intent(Intent.ACTION_SEND);
        intentToShareLink.putExtra(Intent.EXTRA_TEXT, link);
        intentToShareLink.setType("text/plain");
        String[] packagesToExclude = new String[] { getPackageName() };
        DialogFragment chooserDialog = ShareLinkToDialog.newInstance(intentToShareLink, packagesToExclude);
        chooserDialog.show(getSupportFragmentManager(), FTAG_CHOOSER_DIALOG);
    }

    if (operation instanceof UnshareOperation && result.isSuccess() && getEditShareFragment() != null) {
        getSupportFragmentManager().popBackStack();
    }

    if (operation instanceof UpdateSharePermissionsOperation && getEditShareFragment() != null
            && getEditShareFragment().isAdded()) {
        getEditShareFragment().onUpdateSharePermissionsFinished(result);
    }

}

From source file:com.galois.qrstream.MainActivity.java

private byte[] encodeSubjectAndText(String subject, String text) {
    JSONObject o = new JSONObject();
    try {//w  ww.  j  av  a  2  s .c  o m
        o.put(Intent.EXTRA_SUBJECT, subject);
        o.put(Intent.EXTRA_TEXT, text);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return o.toString().getBytes();
}

From source file:co.carlosjimenez.android.currencyalerts.app.DetailActivityFragment.java

private Intent createShareForecastIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, mDisplayedRate + FOREX_SHARE_HASHTAG);
    return shareIntent;
}

From source file:bander.notepad.NoteListAppCompat.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info;
    try {/*from  w ww  . ja v a  2s.com*/
        info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    } catch (ClassCastException e) {
        return false;
    }
    switch (item.getItemId()) {
    case DELETE_ID:
        deleteNote(this, info.id);
        return true;
    case SEND_ID:
        Uri uri = ContentUris.withAppendedId(Note.CONTENT_URI, info.id);
        Cursor cursor = getContentResolver().query(uri, new String[] { Note._ID, Note.TITLE, Note.BODY }, null,
                null, null);
        Note note = Note.fromCursor(cursor);
        cursor.close();

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, note.getBody());
        startActivity(Intent.createChooser(intent, getString(R.string.menu_send)));
        return true;
    }
    return false;
}

From source file:com.zia.freshdocs.widget.CMISAdapter.java

/**
 * Send the content using a built-in Android activity which can handle the content type.
 * @param position// w ww. j  a  v  a  2s. co m
 */
public void shareContent(int position) {
    final NodeRef ref = getItem(position);
    downloadContent(ref, new Handler() {
        public void handleMessage(Message msg) {
            Context context = getContext();
            boolean done = msg.getData().getBoolean("done");

            if (done) {
                dismissProgressDlg();

                File file = (File) _dlThread.getResult();

                if (file != null) {
                    Resources res = context.getResources();
                    Uri uri = Uri.fromFile(file);
                    Intent emailIntent = new Intent(Intent.ACTION_SEND);
                    emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
                    emailIntent.putExtra(Intent.EXTRA_SUBJECT, ref.getName());
                    emailIntent.putExtra(Intent.EXTRA_TEXT, res.getString(R.string.email_text));
                    emailIntent.setType(ref.getContentType());

                    try {
                        context.startActivity(
                                Intent.createChooser(emailIntent, res.getString(R.string.email_title)));
                    } catch (ActivityNotFoundException e) {
                        String text = "No suitable applications registered to send " + ref.getContentType();
                        int duration = Toast.LENGTH_SHORT;
                        Toast toast = Toast.makeText(context, text, duration);
                        toast.show();
                    }
                }
            } else {
                int value = msg.getData().getInt("progress");
                if (value > 0) {
                    _progressDlg.setProgress(value);
                }
            }
        }
    });
}

From source file:net.niyonkuru.koodroid.service.SessionService.java

@Override
public void onHandleIntent(Intent intent) {
    if (DEBUG)/*from   ww  w . java 2s  . c om*/
        Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")");

    int request = intent.getIntExtra(EXTRA_REQUEST, REQUEST_LOGIN);
    if (request == REQUEST_LOGOUT) {
        logout();
        return;
    }

    final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);

    final String email = intent.getStringExtra(EXTRA_EMAIL);
    final String password = intent.getStringExtra(EXTRA_PASSWORD);
    boolean broadcast = intent.getBooleanExtra(EXTRA_BROADCAST, false);

    /* totally ignore this request until full credentials are provided */
    if (email == null || password == null)
        return;

    final long startLogin = System.currentTimeMillis();
    final long lastLogin = mSettings.lastLogin();

    /* if the last successful login is within the last 15 minutes */
    if (startLogin - lastLogin <= DateUtils.MINUTE_IN_MILLIS * 15) {

        /* do a credentials check again the local data store */
        if (email.equals(mSettings.email()) && password.equals(mSettings.password())) {
            if (broadcast)
                IntentUtils.callWidget(this, LOGIN_FINISHED);
            announce(receiver, STATUS_FINISHED);
            return;
        }
    }

    try {
        if (NetworkUtils.isConnected(this)) {
            /* announce to the caller that we are now running */
            announce(receiver, STATUS_RUNNING);

        } else
            throw new ServiceException(getString(R.string.error_network_down));

        if (mSettings.email() == null) {
            /* this is likely a new user */
            Crittercism.leaveBreadcrumb(TAG + ": first_time_login");
        }

        login(email, password);
        saveCookies();

        if (DEBUG)
            Log.d(TAG, "login took " + (System.currentTimeMillis() - startLogin) + "ms");

    } catch (IOException e) {
        if (DEBUG)
            Log.e(TAG, "Problem while logging in", e);

        /* if the exception was simply from an abort */
        if (mPostRequest != null && mPostRequest.isAborted())
            return;

        if (receiver != null) {
            // Pass back error to surface listener
            final Bundle bundle = new Bundle();
            bundle.putString(Intent.EXTRA_TEXT, e.toString());
            receiver.send(STATUS_ERROR, bundle);
        }
        return; /* do not announce success below */
    }

    if (broadcast)
        IntentUtils.callWidget(this, LOGIN_FINISHED);
    announce(receiver, STATUS_FINISHED);
}

From source file:com.todoroo.astrid.sync.SyncProviderPreferences.java

/**
 *
 * @param resource/*from  w w w .ja v  a 2s .  c  o  m*/
 *            if null, updates all resources
 */
@Override
public void updatePreferences(Preference preference, Object value) {
    final Resources r = getResources();

    // interval
    if (r.getString(getUtilities().getSyncIntervalKey()).equals(preference.getKey())) {
        int index = AndroidUtilities.indexOf(r.getStringArray(R.array.sync_SPr_interval_values),
                (String) value);
        if (index <= 0)
            preference.setSummary(R.string.sync_SPr_interval_desc_disabled);
        else
            preference.setSummary(r.getString(R.string.sync_SPr_interval_desc,
                    r.getStringArray(R.array.sync_SPr_interval_entries)[index]));
    }

    // status
    else if (r.getString(R.string.sync_SPr_status_key).equals(preference.getKey())) {
        boolean loggedIn = getUtilities().isLoggedIn();
        String status;
        //String subtitle = ""; //$NON-NLS-1$

        // ! logged in - display message, click -> sync
        if (!loggedIn) {
            status = r.getString(R.string.sync_status_loggedout);
            statusColor = Color.rgb(19, 132, 165);
        }
        // sync is occurring
        else if (getUtilities().isOngoing()) {
            status = r.getString(R.string.sync_status_ongoing);
            statusColor = Color.rgb(0, 0, 100);
        }
        // last sync had errors
        else if (getUtilities().getLastError() != null || getUtilities().getLastAttemptedSyncDate() != 0) {
            // last sync was failure
            if (getUtilities().getLastAttemptedSyncDate() != 0) {
                status = r.getString(R.string.sync_status_failed, DateUtilities.getDateStringWithTime(
                        SyncProviderPreferences.this, new Date(getUtilities().getLastAttemptedSyncDate())));
                statusColor = Color.rgb(100, 0, 0);

                if (getUtilities().getLastSyncDate() > 0) {
                    //                        subtitle = r.getString(R.string.sync_status_failed_subtitle,
                    //                                DateUtilities.getDateStringWithTime(SyncProviderPreferences.this,
                    //                                        new Date(getUtilities().getLastSyncDate())));
                }
            } else {
                long lastSyncDate = getUtilities().getLastSyncDate();
                String dateString = lastSyncDate > 0
                        ? DateUtilities.getDateStringWithTime(SyncProviderPreferences.this,
                                new Date(lastSyncDate))
                        : ""; //$NON-NLS-1$
                status = r.getString(R.string.sync_status_errors, dateString);
                statusColor = Color.rgb(100, 100, 0);
            }
        } else if (getUtilities().getLastSyncDate() > 0) {
            status = r.getString(R.string.sync_status_success, DateUtilities.getDateStringWithTime(
                    SyncProviderPreferences.this, new Date(getUtilities().getLastSyncDate())));
            statusColor = Color.rgb(0, 100, 0);
        } else {
            status = r.getString(R.string.sync_status_never);
            statusColor = Color.rgb(0, 0, 100);
        }
        preference.setTitle(R.string.sync_SPr_sync);
        preference.setSummary(r.getString(R.string.sync_SPr_status_subtitle, status));

        preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference p) {
                startSync();
                return true;
            }
        });

        View view = findViewById(R.id.status);
        if (view != null)
            view.setBackgroundColor(statusColor);
    } else if (r.getString(R.string.sync_SPr_key_last_error).equals(preference.getKey())) {
        if (getUtilities().getLastError() != null) {
            // Display error
            final String service = getTitle().toString();
            final String lastErrorFull = getUtilities().getLastError();
            final String lastErrorDisplay = adjustErrorForDisplay(r, lastErrorFull, service);
            preference.setTitle(R.string.sync_SPr_last_error);
            preference.setSummary(R.string.sync_SPr_last_error_subtitle);

            preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                @Override
                @SuppressWarnings("nls")
                public boolean onPreferenceClick(Preference pref) {
                    // Show last error
                    new AlertDialog.Builder(SyncProviderPreferences.this).setTitle(R.string.sync_SPr_last_error)
                            .setMessage(lastErrorDisplay)
                            .setPositiveButton(R.string.sync_SPr_send_report, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent emailIntent = new Intent(Intent.ACTION_SEND);
                                    emailIntent.setType("plain/text")
                                            .putExtra(Intent.EXTRA_EMAIL,
                                                    new String[] { "android-bugs@astrid.com" })
                                            .putExtra(Intent.EXTRA_SUBJECT, service + " Sync Error")
                                            .putExtra(Intent.EXTRA_TEXT, lastErrorFull);
                                    startActivity(Intent.createChooser(emailIntent,
                                            r.getString(R.string.sync_SPr_send_report)));
                                }
                            }).setNegativeButton(R.string.DLG_close, null).create().show();
                    return true;
                }
            });

        } else {
            PreferenceCategory statusCategory = (PreferenceCategory) findPreference(
                    r.getString(R.string.sync_SPr_group_status));
            statusCategory.removePreference(findPreference(r.getString(R.string.sync_SPr_key_last_error)));
        }
    }
    // log out button
    else if (r.getString(R.string.sync_SPr_forget_key).equals(preference.getKey())) {
        boolean loggedIn = getUtilities().isLoggedIn();
        preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference p) {
                DialogUtilities.okCancelDialog(SyncProviderPreferences.this,
                        r.getString(R.string.sync_forget_confirm), new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                logOut();
                                initializePreference(getPreferenceScreen());
                            }
                        }, null);
                return true;
            }
        });
        if (!loggedIn) {
            PreferenceCategory category = (PreferenceCategory) findPreference(
                    r.getString(R.string.sync_SPr_key_options));
            category.removePreference(preference);
        }

    }
}

From source file:org.jnegre.android.osmonthego.service.ExportService.java

/**
 * Handle export in the provided background thread
 *//*from  www  .jav  a 2 s.com*/
private void handleOsmExport(boolean includeAddress, boolean includeFixme) {
    //TODO handle empty survey
    //TODO handle bounds around +/-180

    if (!isExternalStorageWritable()) {
        notifyUserOfError();
        return;
    }

    int id = 0;
    double minLat = 200;
    double minLng = 200;
    double maxLat = -200;
    double maxLng = -200;
    StringBuilder builder = new StringBuilder();

    if (includeAddress) {
        Uri uri = AddressTableMetaData.CONTENT_URI;
        Cursor cursor = getContentResolver().query(uri, new String[] { //projection
                AddressTableMetaData.LATITUDE, AddressTableMetaData.LONGITUDE, AddressTableMetaData.NUMBER,
                AddressTableMetaData.STREET }, null, //selection string
                null, //selection args array of strings
                null); //sort order

        if (cursor == null) {
            notifyUserOfError();
            return;
        }

        try {
            int iLat = cursor.getColumnIndex(AddressTableMetaData.LATITUDE);
            int iLong = cursor.getColumnIndex(AddressTableMetaData.LONGITUDE);
            int iNumber = cursor.getColumnIndex(AddressTableMetaData.NUMBER);
            int iStreet = cursor.getColumnIndex(AddressTableMetaData.STREET);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                //Gather values
                double lat = cursor.getDouble(iLat);
                double lng = cursor.getDouble(iLong);
                String number = cursor.getString(iNumber);
                String street = cursor.getString(iStreet);

                minLat = Math.min(minLat, lat);
                maxLat = Math.max(maxLat, lat);
                minLng = Math.min(minLng, lng);
                maxLng = Math.max(maxLng, lng);
                builder.append("<node id=\"-").append(++id).append("\" lat=\"").append(lat).append("\" lon=\"")
                        .append(lng).append("\" version=\"1\" action=\"modify\">\n");
                addOsmTag(builder, "addr:housenumber", number);
                addOsmTag(builder, "addr:street", street);
                builder.append("</node>\n");
            }
        } finally {
            cursor.close();
        }
    }

    if (includeFixme) {
        Uri uri = FixmeTableMetaData.CONTENT_URI;
        Cursor cursor = getContentResolver().query(uri, new String[] { //projection
                FixmeTableMetaData.LATITUDE, FixmeTableMetaData.LONGITUDE, FixmeTableMetaData.COMMENT }, null, //selection string
                null, //selection args array of strings
                null); //sort order

        if (cursor == null) {
            notifyUserOfError();
            return;
        }

        try {
            int iLat = cursor.getColumnIndex(FixmeTableMetaData.LATITUDE);
            int iLong = cursor.getColumnIndex(FixmeTableMetaData.LONGITUDE);
            int iComment = cursor.getColumnIndex(FixmeTableMetaData.COMMENT);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                //Gather values
                double lat = cursor.getDouble(iLat);
                double lng = cursor.getDouble(iLong);
                String comment = cursor.getString(iComment);

                minLat = Math.min(minLat, lat);
                maxLat = Math.max(maxLat, lat);
                minLng = Math.min(minLng, lng);
                maxLng = Math.max(maxLng, lng);
                builder.append("<node id=\"-").append(++id).append("\" lat=\"").append(lat).append("\" lon=\"")
                        .append(lng).append("\" version=\"1\" action=\"modify\">\n");
                addOsmTag(builder, "fixme", comment);
                builder.append("</node>\n");
            }
        } finally {
            cursor.close();
        }
    }

    try {
        File destinationFile = getDestinationFile();
        destinationFile.getParentFile().mkdirs();
        PrintWriter writer = new PrintWriter(destinationFile, "UTF-8");

        writer.println("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>");
        writer.println("<osm version=\"0.6\" generator=\"OsmOnTheGo\">");
        writer.print("<bounds minlat=\"");
        writer.print(minLat - MARGIN);
        writer.print("\" minlon=\"");
        writer.print(minLng - MARGIN);
        writer.print("\" maxlat=\"");
        writer.print(maxLat + MARGIN);
        writer.print("\" maxlon=\"");
        writer.print(maxLng + MARGIN);
        writer.println("\" />");

        writer.println(builder);

        writer.print("</osm>");
        writer.close();

        if (writer.checkError()) {
            notifyUserOfError();
        } else {
            //FIXME i18n the subject and content
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            emailIntent.setType(HTTP.OCTET_STREAM_TYPE);
            //emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"johndoe@exemple.com"});
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "OSM On The Go");
            emailIntent.putExtra(Intent.EXTRA_TEXT, "Your last survey.");
            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(destinationFile));
            startActivity(emailIntent);
        }
    } catch (IOException e) {
        Log.e(TAG, "Could not write to file", e);
        notifyUserOfError();
    }

}