betacode

Руководство Android Clipboard

  1. Android Clipboard
  2. Пример: Clipboard (Plain Text)
  3. Пример: Clipboard (Intent)
  4. Пример: Clipboard (URI)

1. Android Clipboard

В Android, Clipboard это очень полезный фреймворк (framework) для компирования (copy) и вставки (paste) разных видов данных, например: текст, изображение (image), данные двоичного потока (binary stream data), и другие виды сложных данных.
Точнее, если данные являются простым видом текста, при компировании, он будет сохранен напрямую в Clipboard.
Сложные данные при копировании будут сохранены как ссылка (reference). И приложение которое вставляет (pasting application) возможно должно использовать ContentProvider для анализа содержания.
Чтобы использовать Android Clipboard Framework, ваше приложение должно расположить данные в объект ClipData, потом положить данный объект в системе Clipboard. Все приложения следуют правилам выше, чтобы скопировать и вставить данные один на другой.
Объект ClipData создан с помощью следующих статических методов:
* Copy & Paste *
private void doCopy()  {
    this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

    String txtCopy = "Hello World";
    
    // ClipData (Plain Text)
    ClipData clipData = ClipData.newPlainText("Some label", txtCopy);
    
    // Copy ClipData to Clipboard.
    this.clipboardManager.setPrimaryClip(clipData);
}

private void doPaste()  {
    ClipData primaryClipData = this.clipboardManager.getPrimaryClip();

    ClipData.Item item = primaryClipData.getItemAt(0);

    // Text in the Clipboard.
    String txtPaste = item.getText().toString();
}

2. Пример: Clipboard (Plain Text)

Скопировать и вставить "чистый текст" (Plain Text) это самое простое и распространенное в приложении Android. Ниже является такой пример:
Интерфейс приложения:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="18dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Enter text to copy"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText_copy"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="text"
        android:text="Hello Everybody!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_copy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Copy to Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_copy" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Show Clipboard data"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_copy" />

    <EditText
        android:id="@+id/editText_paste"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/button_paste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Paste from Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_paste" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.clipboardplaintextexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText editTextCopy;
    private EditText editTextPaste;

    private Button buttonCopy;
    private Button buttonPaste;

    private ClipboardManager clipboardManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

        this.editTextCopy = (EditText) findViewById(R.id.editText_copy);
        this.editTextPaste = (EditText) findViewById(R.id.editText_paste);

        this.buttonCopy = (Button) findViewById(R.id.button_copy);
        this.buttonPaste = (Button) findViewById(R.id.button_paste);

        this.buttonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCopy();
            }
        });
        this.buttonPaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPaste();
            }
        });
    }

    // User click on "Copy" button.
    private void doCopy()  {
        String txtCopy = this.editTextCopy.getText().toString();
        ClipData clipData = ClipData.newPlainText("text", txtCopy);

        // Copy ClipData to Clipboard.
        this.clipboardManager.setPrimaryClip(clipData);

        Toast.makeText(getApplicationContext(),"Data Copied to Clipboard", Toast.LENGTH_SHORT).show();
    }

    // User click on "Poste" button.
    private void doPaste()  {
        // Get ClipData from Clipboard.
        ClipData primaryClipData = this.clipboardManager.getPrimaryClip();
        ClipData.Item item = primaryClipData.getItemAt(0);

        String txtPaste = item.getText().toString();

        this.editTextPaste.setText(txtPaste);

        Toast.makeText(getApplicationContext(),"Data Pasted from Clipboard",Toast.LENGTH_SHORT).show();
    }

}

3. Пример: Clipboard (Intent)

Intent так же могут быть скопированы в Clipbooard. В данном примере я создам простой Intent чтобы открыть URL в браузере. Мы можем скопировать данный Intent в Clipboard.
Интерфейс приложения:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Intention to open a URL in the browser:"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText_url"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="text"
        android:text="https://google.com"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_copy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Copy Intent to Clipboard"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_url" />

    <EditText
        android:id="@+id/editText_paste"
        android:layout_width="0dp"
        android:layout_height="120dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:background="#B2B5A4"
        android:ems="10"
        android:inputType="textMultiLine|text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_copy" />

    <Button
        android:id="@+id/button_paste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Paste Intent from Clipboard and start It!"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_paste" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.clipboarditentexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private ClipboardManager clipboardManager;
    private Button buttonCopy;
    private Button buttonPaste;

    private EditText editTextUrl;
    private EditText editTextPaste;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ClipboardManager:
        this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

        this.editTextPaste = (EditText) this.findViewById(R.id.editText_paste);
        this.editTextUrl = (EditText) this.findViewById(R.id.editText_url);

        this.buttonCopy = (Button) this.findViewById(R.id.button_copy);
        this.buttonPaste = (Button) this.findViewById(R.id.button_paste);


        this.buttonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCopy();
            }
        });

        this.buttonPaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPaste();
            }
        });
    }

    // Some Intent need to Copy to Clipboard.
    private Intent getOpenUrlIntent(String url)  {

        // Intent to open a URL.
        Intent openUrlIntent = new Intent(Intent.ACTION_VIEW);
        openUrlIntent.setData(Uri.parse(url));

        openUrlIntent.putExtra("copyTimeInMillis", new Date().getTime());
        openUrlIntent.putExtra("description", "Intent to open a URL");

        return openUrlIntent;
    }

    private void doCopy()  {
        String url = this.editTextUrl.getText().toString();
        Intent openUrlIntent = this.getOpenUrlIntent(url);

        ClipData clipData = ClipData.newIntent("Open URL Intent", openUrlIntent);

        // Copy ClipData to Clipboard.
        this.clipboardManager.setPrimaryClip(clipData);

        Toast.makeText(getApplicationContext(),"Data Copied to Clipboard", Toast.LENGTH_SHORT).show();
    }

    private void doPaste()  {
        // Get ClipData from Clipboard.
        ClipData primaryClipData = this.clipboardManager.getPrimaryClip();
        ClipData.Item item = primaryClipData.getItemAt(0);

        // Get Intent from Clipboard.
        Intent intentPaste = item.getIntent();

        this.editTextPaste.setText("");

        if(intentPaste == null)  {
            this.editTextPaste.setText("No Intent data in Clipboard!");
            return;
        }

        this.editTextPaste.append("description: " + intentPaste.getStringExtra( "description" ));
        this.editTextPaste.append("\n");
        this.editTextPaste.append("copyTimeInMillis: " + intentPaste.getLongExtra("copyTimeInMillis" ,0L));

        this.editTextPaste.append("\n");
        this.editTextPaste.append("Action: " + intentPaste.getAction());
        Uri uri = intentPaste.getData();

        this.editTextPaste.append("Uri: " + uri);

        // Start Activity (If you want).
        startActivity(intentPaste);

        Toast.makeText(getApplicationContext(),"Data Pasted from Clipboard",Toast.LENGTH_SHORT).show();
    }
}

4. Пример: Clipboard (URI)

Чтобы скопировать изображение, вам нужно конвертировать его в Uri, и скопировать данный Uri в Clipboard. В данном примере я скопирую изображение в папке "drawable" в Clipboard.
Копировать несколько файлов изображения в папку "drawable":
icon_cry.png
icon_feel_good.png
На Android Studio, мы создадим новый Activity с названием ImageActivity для отображения скопированного изображения в Clipboard.
  • File > New > Activity > Empty Activity
Android Studio создает 2 файла: ImageActivity.java и activity_image.xml, одновременно ImageActivity будет зарегистрировано с AndroidManifest.xml:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.o7planning.clipboarduriexample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- ImageActivity -->
        <activity android:name=".ImageActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Интерфейс ImageActivity:
activity_image.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Show  Image In Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@drawable/icon_cry" />

    <Button
        android:id="@+id/button_paste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Paste"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Button
        android:id="@+id/button_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Back"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_paste" />

</androidx.constraintlayout.widget.ConstraintLayout>
ImageActivity.java
package org.o7planning.clipboarduriexample;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

public class ImageActivity  extends AppCompatActivity {

    private static final String LOG_TAG = "AndroidExample";

    private ClipboardManager clipboardManager;

    private ImageView imageView;
    private Button buttonBack;
    private Button buttonPaste;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);

        //
        this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

        //
        this.imageView = (ImageView) this.findViewById(R.id.imageView);

        this.buttonPaste = (Button) this.findViewById(R.id.button_paste);
        this.buttonPaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPaste();
            }
        });


        this.buttonBack = (Button) this.findViewById(R.id.button_back);
        this.buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doBack();
            }
        });
    }



    private void doPaste()  {
        Intent intent= this.getIntent();

        ClipData primaryClipData = this.clipboardManager.getPrimaryClip();

        if(primaryClipData == null)  {
            this.imageView.setImageURI(null);
            return;
        }

        ClipData.Item item = primaryClipData.getItemAt(0);

        Uri uri = item.getUri();

        this.imageView.setImageURI(uri);
    }

    // Back to MainActivity.
    private void doBack()  {
        this.finish();
    }

}
Интерфейс MainActivity:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Select Image (In drawable folder):"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView">

        <RadioButton
            android:id="@+id/radioButton_cry"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="icon_cry.png" />

        <RadioButton
            android:id="@+id/radioButton_feel_good"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="icon_feel_good.png" />
    </RadioGroup>

    <Button
        android:id="@+id/button_copy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Copy Image to Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radioGroup" />

    <Button
        android:id="@+id/button_go"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Go to ImageActivity"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_copy" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.xml
package org.o7planning.clipboarduriexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;

import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = "AndroidExample";

    private ClipboardManager clipboardManager;

    private Button buttonCopy;
    private Button buttonGo;

    private RadioButton radioButtonCry;
    private RadioButton radioButtonFeelGood;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //
        this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

        this.radioButtonCry = (RadioButton) this.findViewById(R.id.radioButton_cry);
        this.radioButtonFeelGood = (RadioButton) this.findViewById(R.id.radioButton_feel_good);

        this.buttonCopy = (Button) this.findViewById(R.id.button_copy);
        this.buttonGo = (Button) this.findViewById(R.id.button_go);

        this.buttonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCopy();
            }
        });

        this.buttonGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToImageActivity();
            }
        });
    }


    private void doCopy()  {
        int resId = R.drawable.icon_cry;

        if(this.radioButtonCry.isChecked()) {
            resId = R.drawable.icon_cry;
        } else if(this.radioButtonFeelGood.isChecked()) {
            resId = R.drawable.icon_feel_good;
        }

        Resources resources = this.getResources();

        // android.resource://org.o7planning.clipboarduriexample/drawable/icon_cry
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE //  android.resource
                + "://" + resources.getResourcePackageName(resId) // org.o7planning.clipboarduriexample
                + '/' + resources.getResourceTypeName(resId)  // drawable
                + '/' + resources.getResourceEntryName(resId); // icon_cry

        Log.i(LOG_TAG, path);

        Uri uriCopy = Uri.parse(path);

        // ClipData (Uri)
        ClipData clipData = ClipData.newRawUri("Some label", uriCopy);

        // Copy ClipData to Clipboard.
        this.clipboardManager.setPrimaryClip(clipData);
    }

    private void goToImageActivity() {
         // Create an Intent:
        Intent myIntent = new Intent(this, ImageActivity.class);

        // Extra data:
        myIntent.putExtra("text1", "This is text1 sent from MainActivity at " + new Date());
        myIntent.putExtra("text2", "This is text2 sent from MainActivity at " + new Date());

        // Start ImageActivity
        this.startActivity(myIntent);
    }
}

Pуководства Android

Show More