Example usage for android.content Intent EXTRA_SUBJECT

List of usage examples for android.content Intent EXTRA_SUBJECT

Introduction

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

Prototype

String EXTRA_SUBJECT

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

Click Source Link

Document

A constant string holding the desired subject line of a message.

Usage

From source file:com.github.dfa.diaspora_android.activity.ShareActivity2.java

@SuppressLint("SetJavaScriptEnabled")
@Override// w  w  w. j a  v a 2s . c  om
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (Helpers.isOnline(ShareActivity2.this)) {
                Intent intent = new Intent(ShareActivity2.this, MainActivity.class);
                startActivityForResult(intent, 100);
                overridePendingTransition(0, 0);
            } else {
                Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
            }
        }
    });

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    fab = (com.getbase.floatingactionbutton.FloatingActionsMenu) findViewById(R.id.fab_expand_menu_button);
    fab.setVisibility(View.GONE);

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.hideTopBar(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.drawer_layout), "Unable to get image",
                            Snackbar.LENGTH_SHORT).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    Intent intent = getIntent();
    final Bundle extras = intent.getExtras();
    String action = intent.getAction();

    if (Intent.ACTION_SEND.equals(action)) {
        webView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {

                if (extras.containsKey(Intent.EXTRA_TEXT) && extras.containsKey(Intent.EXTRA_SUBJECT)) {
                    final String extraText = (String) extras.get(Intent.EXTRA_TEXT);
                    final String extraSubject = (String) extras.get(Intent.EXTRA_SUBJECT);

                    webView.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {

                            finish();

                            Intent i = new Intent(ShareActivity2.this, MainActivity.class);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(i);
                            overridePendingTransition(0, 0);

                            return false;
                        }
                    });

                    webView.loadUrl("javascript:(function() { "
                            + "document.getElementsByTagName('textarea')[0].style.height='110px'; "
                            + "document.getElementsByTagName('textarea')[0].innerHTML = '**[" + extraSubject
                            + "]** " + extraText + " *[shared with #DiasporaWebApp]*'; "
                            + "    if(document.getElementById(\"main_nav\")) {"
                            + "        document.getElementById(\"main_nav\").parentNode.removeChild("
                            + "        document.getElementById(\"main_nav\"));"
                            + "    } else if (document.getElementById(\"main-nav\")) {"
                            + "        document.getElementById(\"main-nav\").parentNode.removeChild("
                            + "        document.getElementById(\"main-nav\"));" + "    }" + "})();");

                }
            }
        });
    }

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity2.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.drawer_layout), R.string.no_internet,
                    Snackbar.LENGTH_SHORT).show();
        }
    }

}

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

private byte[] encodeSubjectAndText(String subject, String text) {
    JSONObject o = new JSONObject();
    try {/*from   w  w  w. ja  v a2s  .  co  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:com.microsoft.azure.engagement.engagement.AzmeNotifier.java

@Override
protected boolean onNotificationPrepared(Notification notification, EngagementReachInteractiveContent content)
        throws RuntimeException {

    if (content.isSystemNotification() == true) {
        // Read http://developer.android.com/guide/topics/ui/notifiers/notifications.html
        final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext);

        // "Large Icon" : the left icon
        if (content.getNotificationImage() != null) {
            notificationBuilder.setLargeIcon(content.getNotificationImage());
        }//from  ww w  .j  a  va2  s .  c  o m
        // "Small Icon": the small icon on the bottom right
        notificationBuilder.setSmallIcon(R.drawable.ic_notification_default);

        // "Content Title": the legacy notification title, i.e. the text on the top
        notificationBuilder.setContentTitle(content.getNotificationTitle());
        // "Content Text": the legacy notification text, i.e. the text on the bottom
        notificationBuilder.setContentText(content.getNotificationMessage());

        // The ticker text
        notificationBuilder.setTicker(notification.tickerText);

        // The notification settings
        notificationBuilder.setDefaults(notification.defaults);
        if (content.isNotificationCloseable() == false) {
            notificationBuilder.setAutoCancel(false);
        }
        notificationBuilder.setContent(notification.contentView);
        notificationBuilder.setContentIntent(notification.contentIntent);
        notificationBuilder.setDeleteIntent(notification.deleteIntent);
        notificationBuilder.setWhen(notification.when);

        if (content.getNotificationBigText() != null) {
            final BigTextStyle bigTextStyle = new BigTextStyle();
            bigTextStyle.setBigContentTitle(content.getNotificationTitle());
            bigTextStyle.setSummaryText(content.getNotificationMessage());
            bigTextStyle.bigText(content.getNotificationBigText());
            notificationBuilder.setStyle(bigTextStyle);
        } else if (content.getNotificationBigPicture() != null) {
            final BigPictureStyle bigPictureStyle = new BigPictureStyle();
            final Bitmap bitmap = EngagementNotificationUtilsV11.getBigPicture(this.mContext,
                    content.getDownloadId().longValue());
            bigPictureStyle.bigPicture(bitmap);
            bigPictureStyle.setSummaryText(content.getNotificationMessage());
            notificationBuilder.setStyle(bigPictureStyle);
        }

        // Retrieves the actionURL from the content
        final String actionURL;
        if (content instanceof EngagementAbstractAnnouncement == true) {
            actionURL = ((EngagementAbstractAnnouncement) content).getActionURL();
        } else {
            // We are receiving a poll notification
            actionURL = null;
        }

        if (actionURL != null) {
            final Uri actionUri = Uri.parse(actionURL);

            // Retrieves the specify parameters from the actionURL
            final boolean displayShareButton = actionUri.getBooleanQueryParameter("displayShareButton", false);
            final boolean displayFeedbackButton = actionUri.getBooleanQueryParameter("displayFeedbackButton",
                    false);

            if (displayFeedbackButton == true) {
                final Intent feedbackIntent = new Intent();
                feedbackIntent.setAction(Intent.ACTION_VIEW);
                final Uri data = Uri.parse("mailto:");
                feedbackIntent.putExtra(Intent.EXTRA_SUBJECT,
                        mContext.getString(R.string.notification_feedback_email_subject));
                feedbackIntent.setData(data);
                final PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, feedbackIntent, 0);

                notificationBuilder.addAction(R.drawable.ic_out_of_app_send_feedback,
                        mContext.getString(R.string.notification_feedback_button_title), pendingIntent);
            }

            if (displayShareButton == true) {
                final Intent sharingIntent = new Intent();
                sharingIntent.setAction(Intent.ACTION_SEND);
                sharingIntent.putExtra(Intent.EXTRA_TEXT,
                        mContext.getString(R.string.notification_share_message));
                sharingIntent.setType("text/plain");
                final PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, sharingIntent, 0);

                notificationBuilder.addAction(R.drawable.ic_out_of_app_share,
                        mContext.getString(R.string.notification_share_button_title), pendingIntent);
            }

        }

        /* Dismiss option can be managed only after build */
        final Notification finalNotification = notificationBuilder.build();
        if (content.isNotificationCloseable() == false) {
            finalNotification.flags |= Notification.FLAG_NO_CLEAR;
        }

        /* Notify here instead of super class */
        final NotificationManager manager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(getNotificationId(content), finalNotification); // notice the call to get the right identifier

        /* Return false, we notify ourselves */
        return false;
    } else {
        return super.onNotificationPrepared(notification, content);
    }
}

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/*ww w  . j  av  a  2s.  c  o 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:com.github.dfa.diaspora_android.activity.ShareActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*from   ww w.  j  a va  2 s.  c o m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main__activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (toolbar != null) {
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Helpers.isOnline(ShareActivity.this)) {
                    Intent intent = new Intent(ShareActivity.this, MainActivity.class);
                    startActivityForResult(intent, 100);
                    overridePendingTransition(0, 0);
                    finish();
                } else {
                    Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }
    setTitle(R.string.new_post);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.applyDiasporaMobileSiteChanges(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.main__layout), "Unable to get image",
                            Snackbar.LENGTH_LONG).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.main__layout), R.string.no_internet,
                    Snackbar.LENGTH_LONG).show();
        }
    }

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
                handleSendSubject(intent);
            } else {
                handleSendText(intent);
            }
        } else if (type.startsWith("image/")) {
            // TODO Handle single image being sent -> see manifest
            handleSendImage(intent);
        }
        //} else {
        // Handle other intents, such as being started from the home screen
    }

}

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

/**
 *
 * @param resource/*w ww.j av  a2 s . 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:com.shareyourproxy.IntentLauncher.java

/**
 * View Invite friends/*from  w  w  w. j  a  v  a  2  s.  c o m*/
 *
 * @param activity context
 */
public static void launchInviteFriendIntent(Activity activity) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.share_your_proxy));
    intent.putExtra(Intent.EXTRA_TEXT, activity.getString(R.string.invite_friend_content));
    if (intent.resolveActivity(activity.getPackageManager()) != null) {
        activity.startActivity(createChooser(intent, activity.getString(R.string.invite_a_friend)));
    }
}

From source file:com.codeskraps.sbrowser.home.SBrowserActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.itemQuit) {

        try {/*  w  ww. j  a  va  2s . c  o  m*/
            dataBaseData.deleteTable(DataBaseData.DB_TABLE_TABS);
        } catch (Exception e) {
            Log.e(TAG, "deleteTable: " + e.getMessage());
        }
        this.finish();
        overridePendingTransition(R.anim.fadein, R.anim.fadeout);

    } else if (item.getItemId() == R.id.itemFeedback) {

        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

        String aEmailList[] = { "codeskraps@gmail.com" };

        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "sBrowser - Feedback");
        emailIntent.setType("plain/text");

        startActivity(Intent.createChooser(emailIntent, "Send your feedback in:"));

        /*-
        } else if (item.getItemId() == R.id.itemBuyMeAPint) {
                
           try {
              Intent marketIntent = new Intent(Intent.ACTION_VIEW);
              marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
             | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
              startActivity(marketIntent.setData(Uri.parse("market://developer?id=Codeskraps")));
           } catch (Exception e) {
              Intent browserIntent = new Intent(Intent.ACTION_VIEW,
             Uri.parse("http://play.google.com/store/apps/developer?id=Codeskraps"));
              browserIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
             | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
              startActivity(browserIntent);
              Log.e(TAG, e.getMessage());
           }
         */
    } else {

        try {
            Picture picture = webView.capturePicture();
            PictureDrawable pictureDrawable = new PictureDrawable(picture);
            Bitmap bitmap = Bitmap.createBitmap(300, 300, Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawPicture(pictureDrawable.getPicture());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, (OutputStream) bos);
            bitmap.isRecycled();

            BookmarkItem bookmarkItem = new BookmarkItem(webView.getTitle(), webView.getUrl());
            bookmarkItem.setImage(bos.toByteArray());
            sBrowserData.setBookmarkItem(bookmarkItem);
            bos.close();

        } catch (Exception e) {
            Log.e(TAG, "Picture:" + e.getMessage());
            BookmarkItem bookmarkItem = new BookmarkItem("Set title", "Set url");
            bookmarkItem.setImage(null);
            sBrowserData.setBookmarkItem(bookmarkItem);
        }

        SBrowserApplication sBrwoserApp = (SBrowserApplication) getApplication();
        SBrowserActivity.this.startActivity(sBrwoserApp.getMenuIntent(item, SBrowserActivity.this));
        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.architjn.materialicons.ui.MainActivity.java

@Override
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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_sendemail) {
        StringBuilder emailBuilder = new StringBuilder();

        Intent intent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("mailto:" + getResources().getString(R.string.email_id)));
        intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.email_subject));

        emailBuilder.append("\n \n \nOS Version: ").append(System.getProperty("os.version")).append("(")
                .append(Build.VERSION.INCREMENTAL).append(")");
        emailBuilder.append("\nOS API Level: ").append(Build.VERSION.SDK_INT);
        emailBuilder.append("\nDevice: ").append(Build.DEVICE);
        emailBuilder.append("\nManufacturer: ").append(Build.MANUFACTURER);
        emailBuilder.append("\nModel (and Product): ").append(Build.MODEL).append(" (").append(Build.PRODUCT)
                .append(")");
        PackageInfo appInfo = null;// w  w  w  .j  a v a  2s . c o m
        try {
            appInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        assert appInfo != null;
        emailBuilder.append("\nApp Version Name: ").append(appInfo.versionName);
        emailBuilder.append("\nApp Version Code: ").append(appInfo.versionCode);

        intent.putExtra(Intent.EXTRA_TEXT, emailBuilder.toString());
        startActivity(Intent.createChooser(intent, (getResources().getString(R.string.send_title))));
        return true;
    } else if (id == R.id.action_share) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = getResources().getString(R.string.share_one)
                + getResources().getString(R.string.developer_name)
                + getResources().getString(R.string.share_two) + MARKET_URL + getPackageName();
        sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, (getResources().getString(R.string.share_title))));
    } else if (id == R.id.action_changelog) {
        showChangelog();
    }

    return super.onOptionsItemSelected(item);
}

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

/**
 * Handle export in the provided background thread
 */// ww w.j  a  v a  2  s .  c  o  m
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();
    }

}