1、在Activity之间传递数据还可以利用一些技巧,无论是Windows还是Linux操作系统,都支持一种叫做剪切板的技术(某一程序将数据复制到剪切板上,其它的任何程序都可以从剪切板中获取数据);
2、新建一个名为“android_intent3”的Android工程;
3、在main.xml文件中添加Button:
<Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Android使用剪切板传递数据" />4、新建布局文件”other.xml“,添加”TextView“,代码:
<?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、声明一个Activity,”OtherActivity“,并继承Activity,在此类中创建”onCreate“方法;
6、回到“Main.java”中,添加成员Button,并向Android系统调用剪切板,构造意图并启动,代码:
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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // 从Android系统中调用剪切板的服务 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); String name = "Jack"; clipboardManager.setText(name);// 向剪切板添加数据 Intent intent = new Intent(Main.this, OtherActivity.class); startActivity(intent); } }); } @Override public 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、点击“OtherActivity.java”,添加获取剪切板方法,获取剪切板数据,设置到“textView”上,代码:
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; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.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();//从剪切板中获取数据 textView.setText(msgString); } public OtherActivity() { // TODO Auto-generated constructor stub } }10、在“AndroidManifest.xml”上添加“Activity”:
<activity android:name=".OtherActivity" > </activity>11、运行:
12、未完待续~