网上也有很多文章讲解了intent的用法,自己感觉他的字面意义说到了他的精髓:“目的、意向”,也就是说通过它来告诉应用程序将要做什么,intent正是这样,android通过Intent机制来协助应用间的交互与通讯,网上的一句话来理解:Intent有两种基本用法:一种是显式的Intent,即在构造Intent对象时就指定接收者,这种方式与普通的函数调用类似,只是复用的粒度有所差别;另一种是隐式的Intent,即Intent的发送者在构造Intent对象时,并不知道也不关心接收者是谁,这种方式与函数调用差别比较大,有利于降低发送者和接收者之间的耦合。另外Intent除了发送外,还可用于广播。本文的例子正式介绍其中的显示intent,隐式的Intent将在下一篇中学习。
     实例要达到大致的效果:一个页面显示用户列表,其中有一个按钮来添加用户。
 用户列表界面:
 android学习之 intent 实例
添加用户界面:
android学习之 intent 实例


显示的intent需要明确他的目标Component 也就是intent必须包含具体Component的Name,什么是Component

大致看下ComponentName源代码:

 public ComponentName(Context pkg, Class<?> cls)



其中有这样的介绍:
@param pkg The name of the package that the component exists in.  Can
     * not be null.
     * @param cls The name of the class inside of <var>pkg</var> that
     * implements the component.  Can not be null.
这个成员变量分别为目标的包和class的name
因此可以有三种方法够造ComponentName 例如
new ComponentName(targetclass.class.getPackage().getName(),targetclass.class.getName()));
new ComponentName(this,targetclass.class.getName()));
new ComponentName(this,targetclass.class));
---------------------------------
这样就构建了我们的意图,
但是要通知目标组件实现这个意图:
 可以使用startActivity(intent)方法来启动,但是本文使用了startActivityForResult方法,因为我们需要新打开的activity返回数据(新添加的用户数据),

此方法的参数:startActivityForResult(Intent intent, int requestCode),
requestCode是干嘛的呢:文档是这样说的:

 

android学习之 intent 实例requestCode If >= 0, this code will be returned in
android学习之 intent 实例     *                    onActivityResult() when the activity exits.


也就是说如果requestCode>0 我们就可以在目标activity返回的时候执行父窗口(官方叫做originating activity)的onActivityResult方法来处理我们的数据,我们可以使用已经定义好的requestCode,也可以自己定义,在代码中我直接给赋值为1,正如文档所说的,我们在用户类表的activity里面重写onActivityResult方法来刷新界面,以显示新添加的用户。
  下面来看下我们的本实例的两个activity:
首先是用户列表activity:Test1.java:(使用到了simpleAdapter可以见于我的另外一篇文章http://www.blogjava.net/freeman1984/archive/2009/11/06/301475.html

}

注意的不能在startActivityForResult(addnew, 1);后面finish();要不originating实例(列表activity)就不在了。
 新建用户activity Test2.java

}


本文大致介绍了下显示的intent 将在下一篇中看看隐式的intent,也就是intent的其他成员变量的使用:intent主要的成员变量如下:
 

android学习之 intent 实例private String mAction;
android学习之 intent 实例    private Uri mData;
android学习之 intent 实例    private String mType;
android学习之 intent 实例    private ComponentName mComponent;
android学习之 intent 实例    private int mFlags;
android学习之 intent 实例    private HashSet<String> mCategories;
android学习之 intent 实例    private Bundle mExtras;


本文来源:http://www.blogjava.net/freeman1984/archive/2009/11/10/301823.html

相关文章:

  • 2022-12-23
  • 2021-09-06
  • 2021-06-17
  • 2021-07-27
  • 2022-12-23
  • 2021-12-22
  • 2021-10-24
  • 2021-07-07
猜你喜欢
  • 2022-12-23
  • 2021-12-06
  • 2021-09-12
  • 2021-06-23
  • 2021-12-28
  • 2021-04-07
  • 2021-09-27
相关资源
相似解决方案