您的位置:首页 > 其它

安卓开发手记 之 intent 传递数据的另外几种方式

2013-08-06 16:29 399 查看
这里有一篇关于intent 的基本使用/article/10398897.html

当然除了这些基本的使用之外,还有其他经常使用的 传递数据的方式 ;

一,使用静态变量传递数据

1,新建一个android 工程,我们做一个简单demo,在原有 mianActivity 的基础上添加一个 OtherActivity ,然后在 mainActivity.xml 添加一个button

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="98dp"
android:text="Button" />


新建 布局文件 other.xml 添加一个 textview

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.20"
/>
</LinearLayout>


2,在 otherActivity .java onCreate() 里添加如下代码 ,

public class OtherActivity extends Activity{
public static String name;
private TextView tx;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
tx = (TextView) this.findViewById(R.id.textView1);

//name="mr_miaomiao";

tx.setText("name  :"+name);
}
}


3, 在mainActivity.java oncreate 里添加如下代码

public class MainActivity 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.button1);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
//跳转到下一个activity
Intent intent = new Intent();
intent.setClass(MainActivity.this, OtherActivity.class);
//修改其静态变量的值
OtherActivity.name="@夏苗苗长见识了";
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.activity_main, menu);
return true;
}

}


4.,最后我们来改下清单文件 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xiamiaomiao.testintent001"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.xiamiaomiao.testintent001.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>


部署在模拟器上试试。

小结:其实使用静态变量传数据 就是在activity 里声明一个静态变量在 系统为它初始化前 赋值 。

二,android 中Application

有过javaee 开发经验的童鞋们都知道 有个 jsp 内置对象 application ,它的生命周期和 服务器 一起,应用启动时创建服务器挂了 ,就没了,在android 里也有个极其相似的 东西 android.application

下面我们来看看它的使用方式:

为了方便我们接着上面的例子,新建一个java类--------MyApp 继承自 Application ,我们需要重写onCreate()方法,该方法表示该对象的创建,我们可以在这个方法里初始化我们需要的数据。

package com.xiamiaomiao.application;

import android.app.Application;

public class MyApp extends Application {
private String name;
private String weibo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWeibo() {
return weibo;
}
public void setWeibo(String weibo) {
this.weibo = weibo;
}
@Override
public void onCreate() {
super.onCreate();

this.name ="mr_miaomiao";
this.weibo = "@夏苗苗长见识了";
}
}


1,,我们修改一下mainActivity 的代码,来从MyApp 里获取数据展示到 other 的 textview 里 。(ps:真是不错的想法。。。。)

public class MainActivity extends Activity {
private MyApp myapp;

private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
//跳转到下一个activity
Intent intent = new Intent();
intent.setClass(MainActivity.this, OtherActivity.class);
myapp = (MyApp) getApplication();
intent.putExtra("name", myapp.getName());
intent.putExtra("weibo", myapp.getWeibo());

//修改其静态变量的值
//OtherActivity.name="@夏苗苗长见识了";
startActivity(intent);
}
});

}


2.,修改 otherActivity .java 中的代码

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);

tx = (TextView) this.findViewById(R.id.textView1);

Intent intent = getIntent();
String name  =intent.getStringExtra("name");
String weibo = intent.getStringExtra("weibo");

tx.setText("name  :"+name +"\n"+"weibo  : "+weibo);
}


只是从 intent 里取了一些数据 ,

3,其实这些已经差不多了,但是还有一个地方不要忘记了,那就是你的清单文件 ,对application 节点 修改如下

<application
android:name="com.xiamiaomiao.testintent001"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.xiamiaomiao.application.MyApp"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


运行一下试试看。

小结:myapp 对象 在任何一个activity 里 都可以被调用,可以存储一些app 的全局变量;

三,android 中的剪切板

事实上在android 里使用剪切板来传递数据 也是一种不错的选择,特别是我们要传递一些自定义对象的时候 ;下面我们来看看

如何使用;

1,现在我们新建一个android application ---------TestClipboard (不知道拼错没有。。。)

和上面一样新建一个 otherActiviy.java ,顺带也建好 布局文件 ,在里面加入一个 textview ,

2,下面我们在 mainActivity 里 启动剪切板服务 在里面储存 我们要放的数据

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {

@SuppressLint("NewApi") @Override
public void onClick(View arg0) {
//启动剪切板服务
ClipboardManager cm =  (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData cd= ClipData.newPlainText("name", "xiamiaomiao");
cm.setPrimaryClip(cd);
Intent intent  = new Intent();
intent.setClass(MainActivity.this, NewActivity.class);
startActivity(intent);
}
});

}

3,接下来看看如何在otherActivity 里获取这个 内容

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
tx = (TextView) this.findViewById(R.id.textView1);
ClipboardManager cm  = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if(cm.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
ClipData cd =
cm.getPrimaryClip();
Item it = cd.getItemAt(0);
System.out.println(cd.getItemCount());
tx.setText(it.getText());

}
}


4,配置好你的清单文件后试试看 ,是不是同样可以获取到数据

5,,紧接着 我们试试用剪切板来传递一个复杂的对象,新建一个java 类 emp .java

package com.xiamiaomiao.model;

import java.io.Serializable;

public class Emp implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String dept;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Emp(int id, String name, String dept, int age) {
super();
this.id = id;
this.name = name;
this.dept = dept;
this.age = age;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + ", dept=" + dept + ", age="
+ age + "]";
}

}


6,修改mainActivity 中部分代码如下

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {

@SuppressLint("NewApi") @Override
public void onClick(View arg0) {
ObjectOutputStream oos  = null;
ByteArrayOutputStream bos = null;
ClipboardManager cm =  (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
String empStr ="";
ArrayList<Emp> emps = new ArrayList<Emp>();
emps.add(new Emp(1, "001", "a", 20));
emps.add(new Emp(2, "002", "b", 20));
emps.add(new Emp(3, "003", "c", 20));
emps.add(new Emp(4, "004", "d", 20));
try {
bos = new ByteArrayOutputStream();
oos  = new ObjectOutputStream(bos);
oos.writeObject(emps);
//转码成字符串
empStr = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
System.out.println(empStr);

} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ClipData cd= ClipData.newPlainText("emps",empStr);
cm.setPrimaryClip(cd);
Intent intent  = new Intent();
intent.setClass(MainActivity.this, NewActivity.class);
startActivity(intent);
}
});

}


7,修改OtherActivity 中代码 如下,(同样都是传递的字符串,只不过这里传递一个对象时,需要序列化)

protected void onCreate(Bundle savedInstanceState)  {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
tx = (TextView) this.findViewById(R.id.textView1);
ClipboardManager cm  = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if(cm.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
ClipData cd =
cm.getPrimaryClip();
Item it = cd.getItemAt(0);
byte[] buf = Base64.decode(it.getText().toString(), Base64.DEFAULT);
ByteArrayInputStream bis  = new ByteArrayInputStream(buf);

ObjectInputStream ois = null;

try {
ois = new ObjectInputStream(bis);

ArrayList<Emp> emps  =  (ArrayList<Emp>) ois.readObject();

tx.setText(emps.toString());

} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{

try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}


小结:使用剪切板传递复杂对象时 ,需要借助 base64 自带工具,进行压缩,解压缩,用到了java 对象流;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: