今天挑出一节专门来说一下使用intent和intentfilter进行通信。
场景:一个Activity启动另一个Activity。
前面已经讲了Fragment的切换,Fragment顾名思义是基于碎片切换的,假如我们要切换屏幕,或者是service组件等等,这就要用到Intent。
此外还想说明一下,Intent还具有很好的设计思想在里面的。它将各种“启动意图”封装成一个一致编程模型,利于高层次的解耦。
1、Intent属性
- Component属性
先来看一段代码:
<span style="white-space:pre"> </span>Intent intent = new Intent();
ComponentName componentName = new ComponentName(this, EventsActivity.class);
intent.setComponent(componentName);
startActivity(intent);
这段代码的功能是用作从当前的activity启动到EventsActivity。
针对ComponentName这个类:(intent.setComponent(componentName);)
构造方法:
public ComponentName(String pkg, String cls)
public ComponentName(Context pkg, String cls)
public ComponentName(Context pkg, Class<?> cls)<span style="white-space:pre"> </span>//上面代码中使用到的构造,一般也是常用方法
再来看Intent类里面的一段源码:
public Intent setClass(Context packageContext, Class<?> cls) {
mComponent = new ComponentName(packageContext, cls);
return this;
}
public Intent setClassName(String packageName, String className) {
mComponent = new ComponentName(packageName, className);
return this;
}
public Intent setClassName(Context packageContext, String className) {
mComponent = new ComponentName(packageContext, className);
return this;
}
我想我不用多说了的,懂java的人都知道的。。。
- Action、Category属性与intent-filter的配置
首先,先来看一下intent-filter配置:这个配置一般写在AndroidManifest.xml:
<activity
android:name="com.xmind.activity.TestActivity"
android:label="@string/title_activity_test" >
<intent-filter >
<span style="white-space:pre"> </span><action android:name="com.xmind.intent.action.TEST_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
intent-filter里面包含了action和category,这两个标签与Intent里面action和category属性是一一对应的。
来看下一段代码:
Intent intent = new Intent();
intent.setAction("com.xmind.intent.action.TEST_ACTION");
intent.addCategory("android.intent.category.DEFAULT");
startActivity(intent);
此外,看一下下面的标准Action和Category表:
2、Intent为Activity之间传值
前面是已经说了启动切换的问题,那现在如果有从当前的activity携带值进行跳转到另一个Activity,这个应该怎么操作呢?
这里我们需要使用到Intent的Extra属性:
下面先看一段代码:
<span style="white-space:pre"> </span>Intent intent = new Intent();
intent.setAction("com.xmind.intent.action.TEST_ACTION");
intent.putExtra("test1", 1);
Bundle bundle = new Bundle();
bundle.putBoolean("test2", false);
bundle.putSerializable("test3", new Person("Mr.稻帅",25));
intent.putExtras(bundle);
startActivity(intent);
从上面可以看出,通过Bundle这个类,我们可以构造任意类型的参数,而且这种方式 极力推荐的。
具体操作方法,请查阅其API。
那怎么样接收参数呢?
看下面代码:
<span style="white-space:pre"> </span>Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Person person = (Person) bundle.getSerializable("test3");
textView = (TextView) findViewById(R.id.person_name);
textView.setText(person.getName());
textView = (TextView) findViewById(R.id.person_age);
textView.setText(person.getAge()+"");
System.out.println(bundle.getInt("test1"));
System.out.println(bundle.getBoolean("test2"));
System.out.println(bundle.getSerializable("test3"));
从上面代码可以看到,还是使用Bundle这个类。