您的位置:首页 > 移动开发 > Android开发

Android中的Intent(意图)的使用

2016-09-20 09:10 260 查看

概述:

Intent(意图)主要是解决Android应用的各项组件之间的通讯。Intent负责对应用中一次操作的动作、动作涉及数据、附加数据进行描述,Android则根据此Intent的描述,负责找到对应的组件,将
Intent传递给调用的组件,并完成组件的调用。因此,Intent在这里起着一个媒体中介的作用,专门提供组件互相调用的相关信息,实现调用者与被调用者之间的解耦。

分类:

隐式意图   

        不用指定要打开的activity, 通过动作和数据的组合去查找系统中, 能处理指定动作和数据的界面,因此该方法效率较低。

   应用场景:

        一个应用想被另一个应用打开。

        一个应用想打开另一个应用程序。

        开启方法: 

[java]
view plain
copy

// 开启代码  
Intent intent = new Intent();  
intent.setAction("com.test.rpcalc.CALC_RP");  
intent.setData(Uri.parse("calc://张三"));  
intent.addCategory("android.intent.category.DEFAULT");  
startActivity(intent);  
  
// 被打开界面清单文件的配置  
<intent-filter >  
    <action android:name="com.test.rpcalc.CALC_RP"/>  
    <data android:scheme="calc" />  
    <!-- 额外类别参数 -->  
    <category android:name="android.intent.category.DEFAULT"/>  
</intent-filter>  

显式意图

   指定(包名, 类名), 直接进行跳转。 效率高。

   应用场景:

       应用内部的界面之间进行跳转(安全)

       应用之间跳转可以给Activity配置android:exported="true", 默认false

   开启方法

[java]
view plain
copy

方式一:  
Intent intent = new Intent(this, SelectNumberActivity.class);  
startActivity(intent);  
方式二:  
Intent intent = new Intent();  
intent.setClassName("com.test.smssenderapp", "com.test.smssenderapp.SelectNumberActivity");  
startActivity(intent);  

Intent的数据传递 

   1.intent.setData(uri)  --  intent.getData();

     - 传递字符串数据, 比较局限.

   2.intent.putExtra(name, value)

     - 8 大基本数据类型(byte,short,int,long;float,double;char;boolean), 及其数组。

     - String字符串传CharSequence

     - Serializable 序列化对象 (序列化到文件) 接口

     - Parcelable 序列化对象 (邮包化到内存) 接口

     - Bundle 类似于map的数据集合。使用 putExtras()。

    Intent中传递对象的方法:

    一种是Bundle.putSerializable(Key,Object);

    另一种是Bundle.putParcelable(Key, Object);

    选择序列化方法的原则:

    1)在使用内存的时候,Parcelable比Serializable性能高,所以推荐使用Parcelable。

    2)Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC。

    3)Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable不能很好的保证数据的持续性在外界有变化的情况下。尽管Serializable效率低点,但此时还是建议使用Serializable 。

 

参考博文链接:

   《Android中Intent中传递对象的方法》  http://www.oschina.net/code/snippet_1408868_39329

   《Android中Parcelable接口用法》http://www.cnblogs.com/renqingping/archive/2012/10/25/Parcelable.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: