Master the powerful functions of ClipboardManager in Android development and efficiently manage clipboard data

Master the powerful functions of ClipboardManager in Android development and efficiently manage clipboard data

ClipboardManager

ClipboardManager is a system service provided by Android, responsible for managing the system's global clipboard object. It allows you to copy and paste text, links, images and other data between applications. In Android development, you can get an instance of ClipboardManager through context.getSystemService(Context.CLIPBOARD_SERVICE). The main functions of ClipboardManager include copying, pasting, monitoring changes in clipboard data, and clearing clipboard content.

Get the ClipboardManager instance
 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipboardManager Common Methods
  1. "setPrimaryClip(ClipData clip)"

「Description」: Used to set the specified ClipData object as the main clipboard content. ClipData can contain data such as text, links, images, etc.

「Use Example」: Create a ClipData object containing text and set it as the content of the clipboard.

 ClipData clipData = ClipData.newPlainText("label", "复制的文本"); clipboardManager.setPrimaryClip(clipData);
  1. 「getPrimaryClip()」

「Description」: Used to get the main content of the current clipboard. Returns a ClipData object containing the data in the clipboard.

「Use Example」: Get the contents on the clipboard by calling this method and checking the returned ClipData object.

 ClipData clipData = clipboardManager.getPrimaryClip(); if (clipData != null && clipData.getItemCount() > 0) { // 处理剪贴板内容}
  1. "addPrimaryClipChangedListener(ClipData.OnPrimaryClipChangedListener listener)"

「Description」: Used to add a listener to the main content of the clipboard. When the content of the clipboard changes, the registered listener will be triggered.

「Use Example」: If you need to perform certain actions (such as updating the UI) when the clipboard content changes, you can use this method to add a listener.

 clipboardManager.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() { @Override public void onPrimaryClipChanged() { // 剪贴板内容发生变化时执行相关操作} });
  1. 「removePrimaryClipChangedListener(ClipData.OnPrimaryClipChangedListener listener)」

「Description」: Used to remove the clipboard content change listener that was previously added.

「Usage example」: When you do not need to monitor clipboard content changes, use this method to remove the listener to avoid unnecessary resource consumption.

 private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() { @Override public void onPrimaryClipChanged() { // 剪贴板内容发生变化时执行相关操作} } clipboardManager.removePrimaryClipChangedListener(mOnPrimaryClipChangedListener);
  1. 「hasPrimaryClip()」

「Description」: Used to check whether there is content on the clipboard.

「Use Example」: You can use this method to check whether the clipboard is empty before trying to get the clipboard contents.

 if (clipboardManager.hasPrimaryClip()) { ClipData clipData = clipboardManager.getPrimaryClip(); if (clipData != null && clipData.getItemCount() > 0) { CharSequence text = clipData.getItemAt(0).getText(); // 使用获取到的文本进行操作} }
  1. 「clearPrimaryClip()」

「Description」: Used to clear the contents of the clipboard.

「Usage example」: Used when you need to clear the contents on the clipboard.

 clipboardManager.clearPrimaryClip();

ClipData

ClipData is used to represent clipboard data, allowing text, links, images and other data to be copied and pasted between applications. The ClipData object is an immutable data container that usually contains one or more ClipData.Item objects. Each Item object represents an item of data in the clipboard, which can be text, Uri or Intent.

ClipData Features
  1. 「Data type diversity」: ClipData can contain multiple types of data, such as text, pictures, audio, etc. Each ClipData.Item object can specify its data type, such as text, URI, or Intent.
  2. 「Clipboard Management」: ClipData works with the ClipboardManager class to manage the contents of the clipboard. Through ClipboardManager, you can set ClipData objects as the contents of the clipboard, or you can get ClipData objects from the clipboard.
  3. 「Flexibility and scalability」: ClipData is designed to allow developers to customize the format and type of data as needed. Developers can create custom ClipData.Item objects and specify their MIME types and data contents.
Creating ClipData

Creating a ClipData object involves specifying the type of data to copy and setting the appropriate tags and MIME type.

  1. To create a plain text ClipData object, you need to provide a label (label) and the text content (text) to be copied to the clipboard.
 ClipData clip = ClipData.newPlainText("label", "这里是文本内容");

The newPlainText(CharSequence label, CharSequence text) method is used to create a ClipData object containing only plain text. The first parameter is the label used to describe the data in the clipboard, and the second parameter is the text content to be copied.

  1. Create a ClipData object containing a URI. You need to provide a label, a content resolver, and the URI to copy to the clipboard.
 Uri imageUri = Uri.parse("content://media/external/images/media/123456"); // URI ClipData clip = ClipData.newUri(getContentResolver(), "label", imageUri);

The newUri(ContentResolver resolver, CharSequence label, Uri uri) method is used to create a ClipData object containing a URI. It is used to copy the URI of an image or other file type. The first parameter is the ContentResolver object used to access the data in the content provider, the second parameter is the label, and the third parameter is the URI to be copied.

  1. Create a ClipData object containing multiple items
 ClipData.Item item1 = new ClipData.Item("文本1"); ClipData.Item item2 = new ClipData.Item("文本2"); ClipData clip = new ClipData("label", new String[]{"text/plain"}, item1, item2);

Manually create a ClipData.Item object and construct a ClipData object containing multiple items. Save multiple types of data or multiple items of data in the clipboard.

  1. Use the Intent's ClipData object to pass the Intent as part of the clipboard data. Not common, but can be achieved with:
 Intent intent = new Intent(); // 设置Intent的数据和动作等... ClipData.Item item = new ClipData.Item(intent); ClipData clip = new ClipData("label", new String[]{intent.getType()}, item);

Create a ClipData.Item containing an Intent to construct a ClipData object. Often used to pass complex data or actions in the clipboard that can be parsed in another application or component.

Get ClipData data

Get the current content on the clipboard from ClipboardManager and parse the data in it. Use the getPrimaryClip method to get the current ClipData object on the clipboard.

 ClipData clipData = clipboardManager.getPrimaryClip();

If clipData is not empty, call the corresponding method to get the data. The specific method depends on the type of data contained in the ClipData object.

  1. Get plain text data If the ClipData object contains plain text, use getItemAt(0) to get the first ClipData.Item object and call the getText() method to get the text data.
 if (clipData != null && clipData.getItemCount() > 0) { ClipData.Item item = clipData.getItemAt(0); if (item.getText() != null) { CharSequence text = item.getText().toString(); // 使用text变量,包含剪贴板上的文本内容} }
  1. Get URI data If the ClipData object contains URI data, get the ClipData.Item object and call the getUri() method to get the URI data.
 if (clipData != null && clipData.getItemCount() > 0) { ClipData.Item item = clipData.getItemAt(0); Uri uri = item.getUri(); // 使用uri变量,包含剪贴板上的文件或资源的URI }
  1. Getting Intent data is not common. If the ClipData object contains Intent data, get the ClipData.Item object and call the getIntent() method to get the Intent data.
 if (clipData != null && clipData.getItemCount() > 0) { ClipData.Item item = clipData.getItemAt(0); Intent intent = item.getIntent(); // 使用intent变量,包含剪贴板上的Intent数据}
  1. If a ClipData object contains multiple items, you can iterate over each item to get the data:
 if (clipData != null) { for (int i = 0; i < clipData.getItemCount(); i++) { ClipData.Item item = clipData.getItemAt(i); // 根据item的类型调用相应的方法来获取数据} }

Code Sample

 package com.reathin.sample; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; public class ClipboardHelper { /** * 将文本复制到剪贴板* * @param text 要复制的文本*/ public void copyText(Context context, String text) { ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clipData = ClipData.newPlainText("text", text); clipboardManager.setPrimaryClip(clipData); } /** * 从剪贴板获取文本* * @return 剪贴板中的文本*/ public String getCopiedText(Context context) { ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); if (clipboardManager.hasPrimaryClip()) { ClipData clipData = clipboardManager.getPrimaryClip(); if (clipData != null && clipData.getItemCount() > 0) { CharSequence text = clipData.getItemAt(0).getText(); return text.toString(); } } return null; } }

<<:  What are the Android emulator detection methods?

>>:  WebView core usage and best practices, avoid common pitfalls and optimization techniques

Recommend

Why do you find it increasingly difficult to understand what users like?

What do users really want? What should I give to ...

Why are konjac shreds white and konjac cubes black?

In summer, all the fat people know one thing: &qu...

Master the core rules of Tik Tok and create explosive short videos!

What exactly is the structure of a short video? H...

Surface mini was killed by Microsoft at the last minute

Microsoft held a new product launch conference in ...

If a child doesn’t grow tall, can a shot of injection fix it?

Mixed Knowledge Specially designed to cure confus...

Testing experience of Swift framework on Xcode 6

[[121714]] I spent most of the summer figuring ou...

What will Apple TV look like in China? Not worth looking forward to

At Apple's Spring Festival new product launch...