Android Study Notes (4)-transfer data through clipboard

Source: Internet
Author: User

1. Some skills can also be used to transmit data between activities. Both Windows and Linux operating systems support a technology called clipboard (a program copies data to the clipboard, any other program can obtain data from the clipboard );

2. Create an Android project named "android_intent3;

3. Add the Button in the main. xml file:

<Button android: id = "@ + id/button" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "Android uses clipboard to transmit data"/>
4. Create the layout file "other. xml" and add "TextView". Code:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextVeiw        android:id="@+id/msg"        android:layout_width="fill_parent"        android:layout_height="fill_parent" >    </TextVeiw></LinearLayout>
5. Declare an Activity, "OtherActivity", inherit the Activity, and create the "onCreate" method in this class;

6. Return to "Main. java", add the member Button, call the clipboard to the Android system, construct the intent, and start the clipboard. Code:

Package com. android. myintent; import android. OS. bundle; import android. app. activity; import android. content. clipboardManager; import android. content. context; import android. content. intent; import android. view. menu; import android. view. view; import android. widget. button; import android. widget. textView; public class Main extends Activity {private Button button; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub // call the clipboard service ClipboardManager clipboardManager = (ClipboardManager) from the Android system) getSystemService (Context. CLIPBOARD_SERVICE); String name = "Jack"; clipboardManager. setText (name); // Add data Intent intent = new Intent (Main. this, OtherActivity. class); startActivity (intent) ;}}@overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
9. Click "OtherActivity. java" to add a method to obtain the Clipboard data and set it to "textView". The Code is as follows:

Package com. android. myintent; import android. app. activity; import android. content. clipboardManager; import android. content. context; import android. OS. bundle; import android. widget. textView; public class OtherActivity extends Activity {private TextView textView; @ Overrideprotected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stubsuper. onCreate (savedInstanceState); setContentView (R. layout. other); textView = (TextView) this. findViewById (R. id. msg); ClipboardManager clipboardManager = (ClipboardManager) getSystemService (Context. CLIPBOARD_SERVICE); String msgString = clipboardManager. getText (). toString (); // obtain the data textView from the clipboard. setText (msgString);} public OtherActivity () {// TODO Auto-generated constructor stub }}
10. Add "Activity" to "AndroidManifest. xml ":

        <activity android:name=".OtherActivity" >        </activity>
11. Run:



12. After clicking the button, the system prompts that the task could not be run. After searching, it was found that the setText () and getText () Methods used to transmit data through the clipboard were discarded after Android11, only ClipData objects can be used to replace ~ Next, let's make some changes to the above program ~

In step 2, replace the orange program:

ClipData clipData = ClipData.newPlainText("Label", "Jack");clipboardManager.setPrimaryClip(clipData);

In step 2, replace the orange program:

ClipData clipData = clipboardManager. getPrimaryClip (); // obtain the data Item = clipData from the clipboard. getItemAt (0); textView. setText (item. getText (). toString ());
13. If we want to transmit complex data in the clipboard, for example, an object: first create a class "MyData" and implement the "serializable" interface (in the Superclass option ):

14. Add "name" and "age" members to the new class and provide the constructor. The Code is as follows:

import java.io.Serializable;public class MyData implements Serializable {private String name;private int age;@Overridepublic String toString() {return "MyData [name=" + name + ", age=" + age + "]";}public MyData(String name, int age) {super();this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
15. Enter "Main. java", comment out the previously added code, and instantiate a MyData object. The Code is as follows (using the Base64 tool class ):

Package com. android. myintent; import java. io. byteArrayOutputStream; import java. io. objectInputStream; import java. io. objectOutputStream; import android. OS. bundle; import android. app. activity; import android. content. clipData; import android. content. clipData. item; import android. content. clipboardManager; import android. content. context; import android. content. intent; import android. util. base64; import android. view. menu; import android. view. view; import android. widget. button; import android. widget. textView; public class Main extends Activity {private Button button; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub // call the clipboard service from the Android system // ClipboardManager clipboardManager = (ClipboardManager) // getSystemService (Context. CLIPBOARD_SERVICE); // Add data to the clipboard // ClipData clipData = ClipData. newPlainText ("label", "Jack"); // clipboardManager. setPrimaryClip (clipData); // Intent intent = new Intent (Main. this, OtherActivity. class); // startActivity (intent); MyData myData = new MyData ("Jack", 23); // converts an object to a string ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream (); string base64String = ""; try {// catch exceptions ObjectOutputStream objectOutputStream = new ObjectOutputStream (byteArrayOutputStream); objectOutputStream. writeObject (myData); base64String = Base64.encodeToString (byteArrayOutputStream. toByteArray (), Base64.DEFAULT); objectOutputStream. close ();} catch (Exception e) {// TODO: handle exception} ClipboardManager clipboardManager = (ClipboardManager) getSystemService (Context. CLIPBOARD_SERVICE); ClipData clipData = ClipData. newPlainText ("label", base64String); clipboardManager. setPrimaryClip (clipData); Intent intent = new Intent (Main. this, OtherActivity. class); startActivity (intent) ;}}@overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
16. Go to "OtherActivity. java" and modify the Code as follows:

Package com. android. myintent; import java. io. byteArrayInputStream; import java. io. byteArrayOutputStream; import java. io. objectInputStream; import java. io. objectOutputStream; import android. annotation. suppressLint; import android. app. activity; import android. content. clipData; import android. content. clipboardManager; import android. content. context; import android. content. clipData. item; import android. OS. bundle; import android. util. base64; import android. widget. textView; public class OtherActivity extends Activity {private TextView textView; @ SuppressLint ("NewApi") @ Overrideprotected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stubsuper. onCreate (savedInstanceState); setContentView (R. layout. other); textView = (TextView) this. findViewById (R. id. msg); ClipboardManager clipboardManager = (ClipboardManager) getSystemService (Context. CLIPBOARD_SERVICE); ClipData clipData = clipboardManager. getPrimaryClip (); // obtain the data Item = clipData from the clipboard. getItemAt (0); String msgString = item. getText (). toString (); byte [] base64_byte = Base64.decode (msgString, Base64.DEFAULT); ByteArrayInputStream encoding = new bytes (base64_byte); try {ObjectInputStream objectInputStream = new ObjectInputStream ); myData myData = (MyData) objectInputStream. readObject (); textView. setText (myData. toString ();} catch (Exception e) {// TODO: handle exception} public OtherActivity () {// TODO Auto-generated constructor stub }}
Ps: to be continued ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.