Example usage for android.content Context CLIPBOARD_SERVICE

List of usage examples for android.content Context CLIPBOARD_SERVICE

Introduction

In this page you can find the example usage for android.content Context CLIPBOARD_SERVICE.

Prototype

String CLIPBOARD_SERVICE

To view the source code for android.content Context CLIPBOARD_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.content.ClipboardManager for accessing and modifying the contents of the global clipboard.

Usage

From source file:org.kontalk.ui.AbstractComposeFragment.java

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_delete: {
        // using clone because listview returns its original copy
        deleteSelectedMessages(SystemUtils.cloneSparseBooleanArray(getListView().getCheckedItemPositions()));
        mode.finish();//from w  ww.ja va2 s  .  c  o m
        return true;
    }

    case R.id.menu_retry: {
        CompositeMessage msg = getCheckedItem();
        retryMessage(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_share: {
        CompositeMessage msg = getCheckedItem();
        shareMessage(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_copy_text: {
        CompositeMessage msg = getCheckedItem();

        TextComponent txt = msg.getComponent(TextComponent.class);

        String text = (txt != null) ? txt.getContent() : "";

        ClipboardManager cpm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        cpm.setText(text);

        Toast.makeText(getActivity(), R.string.message_text_copied, Toast.LENGTH_SHORT).show();
        mode.finish();
        return true;
    }

    case R.id.menu_open: {
        CompositeMessage msg = getCheckedItem();
        openFile(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_download: {
        CompositeMessage msg = getCheckedItem();
        startDownload(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_cancel_download: {
        CompositeMessage msg = getCheckedItem();
        stopDownload(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_details: {
        CompositeMessage msg = getCheckedItem();
        showMessageDetails(msg);
        mode.finish();
        return true;
    }
    }
    return false;
}

From source file:org.telegram.ui.Components.ShareAlert.java

private void copyLink(Context context) {
    if (exportedMessageLink == null && linkToCopy == null) {
        return;//from   www.ja v a 2 s  .  co m
    }
    try {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext
                .getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData.newPlainText("label",
                linkToCopy != null ? linkToCopy : exportedMessageLink.link);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(context, LocaleController.getString("LinkCopied", R.string.LinkCopied),
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.ieeton.agency.activity.ChatActivity.java

private void setUpView() {
    activityInstance = this;
    Intent intent = getIntent();/* w w  w  .  j a  va2 s . co  m*/
    if (intent == null) {
        return;
    }
    mChatUser = (ChatUser) intent.getExtras().getSerializable(EXTRA_USERINFO);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // ???
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = intent.getStringExtra(EXTRA_USERID);
        String nick = "";
        if (mChatUser != null) {
            nick = mChatUser.getName();
        } else if (!TextUtils.isEmpty(Utils.getNickCache(this, toChatUsername))) {
            nick = Utils.getNickCache(this, toChatUsername);
        } else {
            nick = getString(R.string.default_nick);
        }
        if (toChatUsername.equals(NetEngine.getFeedbackId())) {
            mTitleName.setText(getString(R.string.xiaomishu));
        } else {
            mTitleName.setText(nick);
        }
    } else {
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        findViewById(R.id.container_remove).setVisibility(View.GONE);
        findViewById(R.id.container_voice_call).setVisibility(View.GONE);
        toChatUsername = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(toChatUsername);
        mTitleName.setText(group.getGroupName());
    }
    if (mChatUser == null) {
        new FetchInfoTask().execute(MODE_HUANXIN);
    } else {
        if (ChatUser.USER_DOCTOR.equals(mChatUser.getType())) {
            new FetchInfoTask().execute(MODE_DOCTOR);
        } else if (ChatUser.USER_PATIENT.equals(mChatUser.getType())) {
            new FetchInfoTask().execute(MODE_PATIENT);
        }
    }
    if (toChatUsername.equals(NetEngine.getFeedbackId())) {
        mBtnCall.setVisibility(View.VISIBLE);
    }
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnsetMsgCount();
    adapter = new MessageAdapter(this, toChatUsername, chatType, new MessageAdapter.HeaderClickListener() {
        @Override
        public void click(int id) {
            if (id == CLICK_LEFT) {
                if (mUser == null) {
                    return;
                }
                //?
                if (mUser.getUserType() == UserInfo.ACCOUNT_DOCTOR) {
                    return;
                }
                Intent intent = new Intent(ChatActivity.this, PatientProfileActivity.class);
                intent.putExtra(PatientProfileActivity.EXTRA_USERID, toChatUsername);
                startActivity(intent);

            } else {
                Intent intent = new Intent(ChatActivity.this, MainActivity.class);
                intent.putExtra(MainActivity.INPUT_INDEX, MainActivity.INPUT_SETTING);
                startActivity(intent);
            }
        }
    });
    // ?
    listView.setAdapter(adapter);
    listView.setOnScrollListener(new ListScrollListener());
    int count = listView.getCount();
    if (count > 0) {
        listView.setSelection(count - 1);
    }

    listView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            hideKeyboard();
            more.setVisibility(View.GONE);
            //iv_emoticons_normal.setVisibility(View.VISIBLE);
            //iv_emoticons_checked.setVisibility(View.INVISIBLE);
            expressionContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
            return false;
        }
    });

    if (toChatUsername.equals(NetEngine.getFeedbackId()) && conversation.getMsgCount() <= 0) {
        //???
        boolean notificationOn = EMChatManager.getInstance().getChatOptions().getNotificationEnable();
        boolean soundOn = EMChatManager.getInstance().getChatOptions().getNoticedBySound();
        boolean vibrateOn = EMChatManager.getInstance().getChatOptions().getNoticedByVibrate();
        if (notificationOn && soundOn) {
            mSoundID = initSoundPool();
            mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    playSound();
                }
            });
        }
        if (notificationOn && vibrateOn) {
            mVibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
            playVibrator();
        }

        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
        String msgID = message.getMsgId();
        message.setMsgId("ieeton" + msgID);

        String content = getString(R.string.mishu_begin_conversation);
        TextMessageBody txtBody = new TextMessageBody(content);
        message.addBody(txtBody);

        message.setFrom(toChatUsername);
        message.setTo(DemoApplication.getInstance().getUserName());
        message.direct = EMMessage.Direct.RECEIVE;

        conversation.addMessage(message);
        EMChatManager.getInstance().saveMessage(message);
        adapter.refresh();

    }

    // ?
    receiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    // Mainacitivity,??chat??????
    intentFilter.setPriority(5);
    registerReceiver(receiver, intentFilter);

    // ack?BroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(5);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // ??BroadcastReceiver
    IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
    deliveryAckMessageIntentFilter.setPriority(5);
    registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

    // ????T
    groupListener = new GroupListener();
    EMGroupManager.getInstance().addGroupChangeListener(groupListener);

    // show forward message if the message is not null
    String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
    if (forward_msg_id != null) {
        // ?????
        forwardMessage(forward_msg_id);
    }

}

From source file:de.electricdynamite.pasty.ClipboardFragment.java

@SuppressLint("NewApi")
public boolean onContextItemSelected(android.view.MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int menuItemIndex = item.getItemId();
    ClipboardItem Item = mItems.get(info.position);
    switch (menuItemIndex) {
    case PastySharedStatics.ITEM_CONTEXTMENU_COPY_ID:
        // Copy without exit selected
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSherlockActivity()
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            Item.copyToClipboard(clipboard);
            clipboard = null;//from w w  w  .j a  v a 2  s .c o m
        } else {
            ClipboardManager clipboard = (ClipboardManager) getSherlockActivity()
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            Item.copyToClipboard(clipboard);
            clipboard = null;
        }
        Toast.makeText(getSherlockActivity().getApplicationContext(), getString(R.string.item_copied),
                Toast.LENGTH_LONG).show();

        break;
    case PastySharedStatics.ITEM_CONTEXTMENU_SHARE_ID:
        // Share to another app
        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, Item.getText());
        startActivity(Intent.createChooser(shareIntent, getString(R.string.app_share_from_pasty)));
        break;
    case PastySharedStatics.ITEM_CONTEXTMENU_DELETE_ID:
        // Delete selected
        mAdapter.delete(info.position);
        break;
    case PastySharedStatics.ITEM_CONTEXTMENU_OPEN_ID:
        /* If the clicked item was originally linkified, we
        * fire an ACTION_VIEW intent.
        */
        String url = Item.getText();
        if (!URLUtil.isValidUrl(url))
            url = "http://" + url;
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
        break;
    }
    return true;
}

From source file:com.android.browser.BookmarksPageCallbacks.java

private void copy(CharSequence text) {
    ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
    cm.setPrimaryClip(ClipData.newRawUri(null, Uri.parse(text.toString())));
}

From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity,
        final Action action) {

    switch (action) {

    case UPVOTE:/*  w w w . j a  v a  2 s . c  om*/
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case DELETE:
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.DELETE);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl()
                : post.url;
        intent.setData(Uri.parse(url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        LinkHandler.getImageInfo(activity, post.url, Constants.Priority.IMAGE_VIEW, 0,
                new GetImageInfoListener() {

                    @Override
                    public void onFailure(final RequestFailureType type, final Throwable t,
                            final StatusLine status, final String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(activity, type, t, status,
                                post.url);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    public void onSuccess(final ImgurAPI.ImageInfo info) {

                        CacheManager.getInstance(activity)
                                .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon,
                                        null, Constants.Priority.IMAGE_VIEW, 0,
                                        CacheRequest.DownloadType.IF_NECESSARY, Constants.FileType.IMAGE, false,
                                        false, false, activity) {

                                    @Override
                                    protected void onCallbackException(Throwable t) {
                                        BugReportActivity.handleGlobalError(context, t);
                                    }

                                    @Override
                                    protected void onDownloadNecessary() {
                                        General.quickToast(context, R.string.download_downloading);
                                    }

                                    @Override
                                    protected void onDownloadStarted() {
                                    }

                                    @Override
                                    protected void onFailure(RequestFailureType type, Throwable t,
                                            StatusLine status, String readableMessage) {
                                        final RRError error = General.getGeneralErrorForFailure(context, type,
                                                t, status, url.toString());
                                        General.showResultDialog(activity, error);
                                    }

                                    @Override
                                    protected void onProgress(boolean authorizationInProgress, long bytesRead,
                                            long totalBytes) {
                                    }

                                    @Override
                                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile,
                                            long timestamp, UUID session, boolean fromCache, String mimetype) {

                                        File dst = new File(
                                                Environment.getExternalStoragePublicDirectory(
                                                        Environment.DIRECTORY_PICTURES),
                                                General.uriFromString(info.urlOriginal).getPath());

                                        if (dst.exists()) {
                                            int count = 0;

                                            while (dst.exists()) {
                                                count++;
                                                dst = new File(
                                                        Environment.getExternalStoragePublicDirectory(
                                                                Environment.DIRECTORY_PICTURES),
                                                        count + "_" + General.uriFromString(info.urlOriginal)
                                                                .getPath().substring(1));
                                            }
                                        }

                                        try {
                                            final InputStream cacheFileInputStream = cacheFile.getInputStream();

                                            if (cacheFileInputStream == null) {
                                                notifyFailure(RequestFailureType.CACHE_MISS, null, null,
                                                        "Could not find cached image");
                                                return;
                                            }

                                            General.copyFile(cacheFileInputStream, dst);

                                        } catch (IOException e) {
                                            notifyFailure(RequestFailureType.STORAGE, e, null,
                                                    "Could not copy file");
                                            return;
                                        }

                                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                                Uri.parse("file://" + dst.getAbsolutePath())));

                                        General.quickToast(context,
                                                context.getString(R.string.action_save_image_success) + " "
                                                        + dst.getAbsolutePath());
                                    }
                                });

                    }

                    @Override
                    public void onNotAnImage() {
                        General.quickToast(activity, R.string.selected_link_is_not_image);
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        try {
            final Intent intent = new Intent(activity, PostListingActivity.class);
            intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).generateJsonUri());
            activity.startActivityForResult(intent, 1);

        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show();
        }

        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.author).toString());
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity.getFragmentManager(), null);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_delete: {
        // using clone because listview returns its original copy
        deleteSelectedMessages(SystemUtils.cloneSparseBooleanArray(getListView().getCheckedItemPositions()));
        mode.finish();//from  w w  w.j  av a  2 s.c  o m
        return true;
    }

    case R.id.menu_retry: {
        CompositeMessage msg = getCheckedItem();
        retryMessage(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_share: {
        CompositeMessage msg = getCheckedItem();
        shareMessage(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_copy_text: {
        CompositeMessage msg = getCheckedItem();

        TextComponent txt = (TextComponent) msg.getComponent(TextComponent.class);

        String text = (txt != null) ? txt.getContent() : "";

        ClipboardManager cpm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        cpm.setText(text);

        Toast.makeText(getActivity(), R.string.message_text_copied, Toast.LENGTH_SHORT).show();
        mode.finish();
        return true;
    }

    case R.id.menu_decrypt: {
        CompositeMessage msg = getCheckedItem();
        decryptMessage(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_open: {
        CompositeMessage msg = getCheckedItem();
        openFile(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_download: {
        CompositeMessage msg = getCheckedItem();
        startDownload(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_cancel_download: {
        CompositeMessage msg = getCheckedItem();
        stopDownload(msg);
        mode.finish();
        return true;
    }

    case R.id.menu_details: {
        CompositeMessage msg = getCheckedItem();
        showMessageDetails(msg);
        mode.finish();
        return true;
    }
    }
    return false;
}

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

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    final WebView.HitTestResult result = mWebView.getHitTestResult();

    final MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            final String url = result.getExtra();

            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                try {
                    if (url != null) {

                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                        request.allowScanningByMediaScanner();
                        request.setNotificationVisibility(
                                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                helper_main.newFileName());
                        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                        dm.enqueue(request);

                        Snackbar.make(mWebView,
                                getString(R.string.context_saveImage_toast) + " " + helper_main.newFileName(),
                                Snackbar.LENGTH_SHORT).show();
                    }//ww  w . ja  va 2 s . c  o m
                } catch (Exception e) {
                    e.printStackTrace();
                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {

                    shareString = helper_main.newFileName();
                    shareFile = helper_main.newFile();

                    try {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                        request.allowScanningByMediaScanner();
                        request.setNotificationVisibility(
                                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, shareString);
                        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                        dm.enqueue(request);

                        Snackbar.make(mWebView,
                                getString(R.string.context_saveImage_toast) + " " + helper_main.newFileName(),
                                Snackbar.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                    }
                    registerReceiver(onComplete2, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                }
                break;

            case ID_READ_LATER:
                if (url != null) {
                    int domainInt = url.indexOf("//") + 2;
                    final String domain = url.substring(domainInt, url.indexOf('/', domainInt));

                    try {
                        final Database_ReadLater db = new Database_ReadLater(Browser.this);
                        db.addBookmark(domain, url);
                        db.close();
                        Snackbar.make(mWebView, R.string.readLater_added, Snackbar.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;

            case ID_COPY_LINK:
                if (url != null) {
                    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();
                }
                break;

            case ID_SHARE_LINK:
                if (url != null) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                    sendIntent.setType("text/plain");
                    Browser.this.startActivity(Intent.createChooser(sendIntent,
                            getResources().getString(R.string.app_share_link)));
                }
                break;
            }
            return true;
        }
    };

    if (result.getType() == WebView.HitTestResult.IMAGE_TYPE) {
        menu.add(0, ID_SAVE_IMAGE, 0, getString(R.string.context_saveImage))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, getString(R.string.context_shareImage))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_READ_LATER, 0, getString(R.string.context_readLater))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
        menu.add(0, ID_COPY_LINK, 0, getString(R.string.menu_share_link_copy))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, getString(R.string.menu_share_link)).setOnMenuItemClickListener(handler);
        menu.add(0, ID_READ_LATER, 0, getString(R.string.context_readLater))
                .setOnMenuItemClickListener(handler);
    }
}

From source file:ac.robinson.ticqr.TicQRActivity.java

private void sendOrder() {
    try {/*from  w w w. java2 s  . co  m*/
        Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
                Uri.fromParts("mailto", TextUtils.isEmpty(mDestinationEmail) ? "" : mDestinationEmail, null));
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject));
        emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.email_body, mEmailContents));
        startActivity(Intent.createChooser(emailIntent, getString(R.string.email_prompt)));
    } catch (ActivityNotFoundException e) {
        // copy to clipboard instead if no email client found
        String clipboardText = getString(R.string.email_backup_sender,
                TextUtils.isEmpty(mDestinationEmail) ? "" : mDestinationEmail,
                getString(R.string.email_body, mEmailContents));

        // see: http://stackoverflow.com/a/11012443
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            @SuppressLint("ServiceCast")
            @SuppressWarnings("deprecation")
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                    Context.CLIPBOARD_SERVICE);
            clipboard.setText(clipboardText);
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                    Context.CLIPBOARD_SERVICE);
            android.content.ClipData clip = android.content.ClipData
                    .newPlainText(getString(R.string.email_subject), clipboardText);
            clipboard.setPrimaryClip(clip);
        }

        Toast.makeText(TicQRActivity.this, getString(R.string.hint_no_email_client), Toast.LENGTH_LONG).show();
    }
}

From source file:com.xicheng.trid.hx.activity.ChatActivity.java

private void setUpView() {
    iv_emoticons_normal.setOnClickListener(this);
    iv_emoticons_checked.setOnClickListener(this);
    // position = getIntent().getIntExtra("position", -1);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // ???/* ww w .j ava 2s .c o  m*/
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        User user = UserUtils.getUserInfor(toChatUsername);
        //?
        if (user.getChatTitle() != null) {
            ((TextView) findViewById(R.id.name)).setText(user.getChatTitle());

        } else {
            ((TextView) findViewById(R.id.name)).setText(toChatUsername);

        }
        //?
        UserUtils.setDefaultBarColor(user.getType());
    }

    // for chatroom type, we only init conversation and create view adapter on success
    if (chatType != CHATTYPE_CHATROOM) {
        onConversationInit();

        onListViewCreation();

        // show forward message if the message is not null
        String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
        if (forward_msg_id != null) {
            // ?????
            forwardMessage(forward_msg_id);
        }
    }
}