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:net.oremland.rss.reader.fragments.BrowserFragment.java

private void copyUrlToClipboard() {
    ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("Feed Item Url", getFeedItem().getUrl());
    clipboard.setPrimaryClip(clip);/*from w w  w.  j  a v  a  2s . c  om*/
    Toast.makeText(getContext(), "Url Copied To Clipboard", Toast.LENGTH_SHORT).show();
}

From source file:de.dknapps.pswgendroid.ServiceDetailFragment.java

/**
 * Kopiert die Login-Informationen in die Zwischenablage.
 * /*  ww  w  . j  ava  2  s . c  o  m*/
 * FIXME dkn Die callingActivity kann durch getActivity() ersetzt werden.
 */
private void copyLoginInfo(final Activity callingActivity) {
    ClipboardManager clipboard = (ClipboardManager) callingActivity.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setPrimaryClip(ClipData.newPlainText(null, currentServiceInfo.getLoginInfo()));
}

From source file:com.microsoft.graph.snippets.SnippetDetailFragment.java

private void clipboard(TextView tv) {
    // which view are we copying to the clipboard?
    int which;//  www . j av a 2  s.c o m

    switch (tv.getId()) {
    case txt_request_url: // the url field
        which = code_snippet;
        break;

    case txt_response_body: // the response body
        which = raw_object;
        break;

    default:
        which = UNSET; // don't assign a prefix
    }

    // if we know which view we're copying, prefix it with useful info
    String what = which == UNSET ? "" : getString(which) + " ";

    // concat the clipboard data to this String
    what += getString(clippy);

    // inform the user that data was added to the clipboard
    Toast.makeText(getActivity(), what, Toast.LENGTH_SHORT).show();

    // depending on our API, do it one way or another...
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        // old way
        ClipboardManager clipboardManager = (ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setText(tv.getText());
    } else {
        clipboard11(tv);
    }
}

From source file:de.kodejak.hashr.fragmentHashFromFile.java

public void OnButtonToClipboardClick() {
    TextView txtOutput = (TextView) getView().findViewById(R.id.edOutput);
    String strOutput = txtOutput.getText().toString();

    ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(strOutput);/*  w  w w  .j  ava  2 s  . co  m*/

    Toast.makeText(mContext, fragJobStr + " copied to clipboard", Toast.LENGTH_SHORT).show();
}

From source file:de.enlightened.peris.SocialFragment.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void storePostInClipboard() {

    //Copy text support for all Android versions
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        final ClipboardManager clipboard = (ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        final ClipData cd = ClipData.newHtmlText(this.selectedPost.author + "'s Social Post",
                this.selectedPost.body, this.selectedPost.body);
        clipboard.setPrimaryClip(cd);//from  w w  w.jav a  2s  . c  o m
    } else {
        final android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(this.selectedPost.body);
    }

    final Toast toast = Toast.makeText(this.getActivity(), "Text copied!", Toast.LENGTH_SHORT);
    toast.show();
}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetDetailFragment.java

private void clipboard(TextView tv) {
    // which view are we copying to the clipboard?
    int which;//from   w  w w  . jav  a 2s.  c o  m

    switch (tv.getId()) {
    case txt_request_url: // the url field
        which = req_url;
        break;

    case txt_response_headers: // the display headers
        which = response_headers;
        break;

    case txt_response_body: // the response body
        which = response_body;
        break;

    default:
        which = UNSET; // don't assign a prefix
    }

    // if we know which view we're copying, prefix it with useful info
    String what = which == UNSET ? "" : getString(which) + " ";

    // concat the clipboard data to this String
    what += getString(clippy);

    // inform the user that data was added to the clipboard
    Toast.makeText(getActivity(), what, Toast.LENGTH_SHORT).show();

    // depending on our API, do it one way or another...
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        // old way
        ClipboardManager clipboardManager = (ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setText(tv.getText());
    } else {
        clipboard11(tv);
    }
}

From source file:com.parttime.activity.ChatActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.chat);/*w w w . j a  va  2 s  .  c o m*/

    mContext = this;
    toChatUsername = getIntent().getStringExtra("userid");
    //       if(toChatUsername==null)
    //       {
    //          toChatUsername="";
    //       }
    flag = getIntent().getStringExtra("flag");
    if (flag != null && flag.equals("commnuication")) {
        Utils.CommitPageFlagToShared(this, Constant.FINISH_ACTIVITY_FLAG_COMMUNICATION);
    }

    Utils.HxUserNames.add(toChatUsername);
    initView();
    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");
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnreadMsgCount();
    adapter = new MessageAdapter(this, toChatUsername, chatType);
    // ?
    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);
            emojiIconContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
            return false;
        }
    });
    // ?
    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);

    // 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);
    }

    // setUpView();
}

From source file:de.kodejak.hashr.fragmentHashFromFile.java

public void OnButtonFromClipboardClick() {
    EditText txtOutput = (EditText) getView().findViewById(R.id.edCompare);
    ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
    CharSequence hash = clipboard.getText();
    String out = (String) hash;

    if (trimHash)
        out = out.trim();//from   w w w. j  a  v a 2s  .  com

    if (uppercaseHash)
        out = out.toUpperCase();

    txtOutput.setText(out);
}

From source file:com.krayzk9s.imgurholo.ui.ImagesFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle item selection
    final Activity activity = getActivity();
    switch (item.getItemId()) {
    case R.id.action_download:
        Toast.makeText(activity,//from   w  ww  . j  a va2 s  .c om
                String.format(getActivity().getResources().getString(R.string.toast_downloading), urls.size()),
                Toast.LENGTH_SHORT).show();
        Intent serviceIntent = new Intent(activity, DownloadService.class);
        serviceIntent.putParcelableArrayListExtra("ids", ids);
        if (albumId != null)
            serviceIntent.putExtra("albumName", albumId);
        else
            serviceIntent.putExtra("albumName", imageCall);
        activity.startService(serviceIntent);
        return true;
    case R.id.action_refresh:
        urls = new ArrayList<String>();
        ids = new ArrayList<JSONParcelable>();
        page = 0;
        makeGallery();
        return true;
    case R.id.action_copy:
        ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("imgur Link", "http://imgur.com/a/" + albumId);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(activity, R.string.toast_copied, Toast.LENGTH_SHORT).show();
        return true;
    case R.id.action_share:
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.putExtra(Intent.EXTRA_TEXT, "http://imgur.com/a/" + albumId);
        startActivity(intent);
        return true;
    case R.id.action_new:
        Intent i = new Intent(this.getActivity().getApplicationContext(), ImageSelectActivity.class);
        startActivityForResult(i, 1);
        //select image
        return true;
    case R.id.action_comments:
        if (galleryAlbumData != null) {
            CommentsAsync commentsAsync = new CommentsAsync(((ImgurHoloActivity) getActivity()),
                    galleryAlbumData);
            commentsAsync.execute();
            return true;
        } else
            return super.onOptionsItemSelected(item);
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.willhauck.linconnectclient.SettingsActivity.java

@SuppressLint("SimpleDateFormat")
private void setupSimplePreferencesScreen() {
    // Load preferences
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);

    // Add preferences from XML
    addPreferencesFromResource(R.xml.pref_general);
    bindPreferenceSummaryToValue(findPreference("pref_ip"));

    // Preference Categories
    serverCategory = ((PreferenceCategory) findPreference("cat_servers"));

    // Preferences
    refreshPreference = ((Preference) findPreference("pref_refresh"));
    serverCategory.removePreference(refreshPreference);

    loadingPreference = ((Preference) findPreference("pref_loading"));
    serverCategory.removePreference(loadingPreference);

    Preference prefEnable = findPreference("pref_enable");
    prefEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override//  ww  w .java 2s .c  om
        public boolean onPreferenceClick(Preference arg0) {
            // If Android 4.3+, open Notification Listener settings,
            // otherwise open accessibility settings
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                startActivityForResult(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS), 0);
            } else {
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
            }
            return true;
        }
    });

    ((Preference) findPreference("pref_ip")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference arg0, Object arg1) {
            // Update Custom IP address summary
            arg0.setSummary((String) arg1);

            refreshServerList();

            // Create and send test notification
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            Object[] notif = new Object[3];
            notif[0] = "Hello from Android!";
            notif[1] = "Test succesful @ " + sf.format(new Date());
            notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
            new TestTask().execute(notif);

            return true;
        }
    });

    Preference prefDownload = findPreference("pref_download");
    prefDownload.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Create share dialog with server download URL
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT,
                    "Download LinConnect server @ https://github.com/hauckwill/linconnect-server");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
            return true;
        }
    });

    Preference prefApplication = findPreference("pref_application");
    prefApplication.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open application settings screen
            Intent intent = new Intent(getApplicationContext(), ApplicationSettingsActivity.class);

            startActivity(intent);
            return true;
        }
    });

    Preference prefDonateBitcoin = findPreference("pref_donate_btc");
    prefDonateBitcoin.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            try {
                // Open installed Bitcoin wallet if possible
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(
                        "bitcoin:1125MguyS1feaop99bCDPQG6ukUcMuvVBo?label=Will%20Hauck&message=Donation%20for%20LinConnect"));
                startActivity(intent);
            } catch (Exception e) {
                // Otherwise, show dialog with Bitcoin address
                EditText input = new EditText(SettingsActivity.this);
                input.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                input.setEnabled(false);

                new AlertDialog.Builder(SettingsActivity.this).setTitle("Bitcoin Address")
                        .setMessage(
                                "Please donate to the following Bitcoin address. Thank you for the support.")
                        .setView(input)
                        .setPositiveButton("Copy Address", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                        Context.CLIPBOARD_SERVICE);
                                clipboard.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                            }
                        }).setNegativeButton("Okay", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
            }
            return true;
        }
    });

    Preference prefGooglePlus = findPreference("pref_google_plus");
    prefGooglePlus.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Google Plus page
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://plus.google.com/114633032648182423928/posts"));
            startActivity(intent);
            return true;
        }
    });

    Preference prefDonatePlay = findPreference("pref_donate_play");
    prefDonatePlay.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Donation Key app on Play Store
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.willhauck.donation"));
            startActivity(intent);
            return true;
        }
    });

    // Create handler to process a detected server
    serverFoundHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj != null) {

                javax.jmdns.ServiceInfo serviceInfo = mJmDNS.getServiceInfo(jmDnsServiceType, (String) msg.obj);

                // Get info about server
                String name = serviceInfo.getName();
                String port = String.valueOf(serviceInfo.getPort());
                String ip = serviceInfo.getHostAddresses()[0];

                // Create a preference representing the server
                Preference p = new Preference(SettingsActivity.this);
                p.setTitle(name);
                p.setSummary(ip + ":" + port);

                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference arg0) {
                        refreshServerList();

                        // Save IP address in preferences
                        Editor e = sharedPreferences.edit();
                        e.putString("pref_ip", arg0.getSummary().toString());
                        e.apply();

                        // Create and send test notification
                        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");

                        Object[] notif = new Object[3];
                        notif[0] = "Hello from Android!";
                        notif[1] = "Test succesful @ " + sf.format(new Date());
                        notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);

                        new TestTask().execute(notif);

                        return true;
                    }

                });

                // Add preference to server list if it doesn't already exist
                boolean found = false;
                for (int i = 0; i < serverCategory.getPreferenceCount(); i++) {
                    if (serverCategory.getPreference(i) != null
                            && serverCategory.getPreference(i).getTitle() != null
                            && serverCategory.getPreference(i).getTitle().equals(p.getTitle())) {
                        found = true;
                    }
                }
                if (!found) {
                    serverCategory.addPreference(p);
                }

                refreshServerList();

                // Remove loading indicator, add refresh indicator if it
                // isn't already there
                if (findPreference("pref_loading") != null)
                    serverCategory.removePreference(findPreference("pref_loading"));
                if (findPreference("pref_refresh") == null)
                    serverCategory.addPreference(refreshPreference);

            }
            return true;
        }
    });

    // Create task to scan for servers
    class ServerScanTask extends AsyncTask<String, ServiceEvent, Boolean> {

        @Override
        protected void onPreExecute() {
            // Remove refresh preference, add loading preference
            if (findPreference("pref_refresh") != null)
                serverCategory.removePreference(refreshPreference);
            serverCategory.addPreference(loadingPreference);

            try {
                mJmDNS.removeServiceListener(jmDnsServiceType, ServerListener);
            } catch (Exception e) {
            }

            refreshServerList();

        }

        @Override
        protected Boolean doInBackground(String... notif) {
            WifiInfo wifiinfo = mWifiManager.getConnectionInfo();
            int intaddr = wifiinfo.getIpAddress();

            // Ensure there is an active Wifi connection
            if (intaddr != 0) {
                byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
                        (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
                InetAddress addr = null;
                try {
                    addr = InetAddress.getByAddress(byteaddr);
                } catch (UnknownHostException e1) {
                }

                // Create Multicast lock (required for JmDNS)
                mMulticastLock = mWifiManager.createMulticastLock("LinConnect");
                mMulticastLock.setReferenceCounted(true);
                mMulticastLock.acquire();

                try {
                    mJmDNS = JmDNS.create(addr, "LinConnect");
                } catch (IOException e) {
                }

                // Create listener for detected servers
                ServerListener = new ServiceListener() {

                    @Override
                    public void serviceAdded(ServiceEvent arg0) {
                        final String name = arg0.getName();
                        // Send the server data to the handler, delayed by
                        // 500ms to ensure all information is read
                        serverFoundHandler.sendMessageDelayed(Message.obtain(serverFoundHandler, -1, name),
                                500);
                    }

                    @Override
                    public void serviceRemoved(ServiceEvent arg0) {
                    }

                    @Override
                    public void serviceResolved(ServiceEvent arg0) {
                        mJmDNS.requestServiceInfo(arg0.getType(), arg0.getName(), 1);
                    }
                };
                mJmDNS.addServiceListener(jmDnsServiceType, ServerListener);

                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                // Notify user if there is no connection
                if (findPreference("pref_loading") != null) {
                    serverCategory.removePreference(findPreference("pref_loading"));
                    serverCategory.addPreference(refreshPreference);

                }
                Toast.makeText(getApplicationContext(), "Error: no connection.", Toast.LENGTH_LONG).show();
            }
        }
    }

    refreshPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference arg0) {
            new ServerScanTask().execute();
            return true;
        }

    });

    // Start scanning for servers
    new ServerScanTask().execute();
}