当前位置: 移动技术网 > IT编程>移动开发>Android > Android编程使用Intent传递对象的方法分析

Android编程使用Intent传递对象的方法分析

2019年07月24日  | 移动技术网IT编程  | 我要评论

路虎中国,日曜转生txt,优酷会员共享一人一号

本文实例分析了android编程使用intent传递对象的方法。分享给大家供大家参考,具体如下:

之前的文章中,介绍过intent的用法,比如启动活动,发送广播,启发服务等,并且可以使用intent时传递一些数据。如下代码所示:

intent intent = new intent(this,secondactivity.class);
intent.putextra("info", "i am fine");
startactivity(intent);

在传递数据时,使用的方法是putextra,支持的数据类型有限,如何传递对象呢??

在android中,使用intent传递对象有两种方式:serializable序列化方式以及parcelable串行化方式。

1、serializable方式

此种方式表示将一个对象转换成可存储或者可传输的状态,序列化后的对象可以在网络上进行传输,可以存储到本地。

对象序列化,只需要实现serializable类。

package com.example.testapplication;
import java.io.serializable;
/**
 * 对象序列化
 * @author yy
 *
 */
public class emp implements serializable {
  private string name;
  private int 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;
  }
}

那么intent如何传递对象参数呢,查看api发现如下方法:

复制代码 代码如下:
intent.putextra(string name, serializable value);

因此,使用该方法传递,如下:

intent intent = new intent(this,secondactivity.class);
intent.putextra("obj", new emp());
startactivity(intent);

那么如何获取呢?使用如下方法:

复制代码 代码如下:
emp emp = (emp) getintent().getserializableextra("obj");

这样就获得了emp对象了。

2、parcelable方式

该种方式的实现原理是将一个完整的对象进行分解,使分解的每一部分都是intent所支持的数据类型。示例如下:

package com.example.testapplication;
import android.os.parcel;
import android.os.parcelable;
/**
 * parcelable方式
 * @author yy
 *
 */
public class emp2 implements parcelable{
  private string name;
  private int 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;
  }
  @override
  public int describecontents() {
    return 0;
  }
  @override
  public void writetoparcel(parcel dest, int flag) {
    //写出name
    dest.writestring(name);
    //写出age
    dest.writeint(age);
  }
  public static final parcelable.creator<emp2> creator = new creator<emp2>() {
    @override
    public emp2[] newarray(int size) {
      return new emp2[size];
    }
    @override
    public emp2 createfromparcel(parcel source) {
      emp2 emp2 = new emp2();
      //读取的顺序要和上面写出的顺序一致
      //读取name
      emp2.name = source.readstring();
      emp2.age = source.readint();
      return emp2;
    }
  };
}

传递对象:方式和序列化相同:

intent intent = new intent(this,secondactivity.class);
intent.putextra("obj", new emp2());
startactivity(intent);

获取对象:

复制代码 代码如下:
emp2 emp2 = getintent().getparcelableextra("obj");

3、区别

serializable在序列化的时候会产生大量的临时变量,从而引起频繁的gc。因此,在使用内存的时候,parcelable 类比serializable性能高,所以推荐使用parcelable类。

parcelable不能使用在要将数据存储在磁盘上的情况,因为parcelable不能很好的保证数据的持续性在外界有变化的情况下。尽管serializable效率低点, 也不提倡用,但在这种情况下,还是建议你用serializable 。

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网