今天挑出一节专门来说一下使用intent和intentfilter进行通信。
场景:一个Activity启动另一个Activity。
前面已经讲了Fragment的切换,Fragment顾名思义是基于碎片切换的,假如我们要切换屏幕,或者是service组件等等,这就要用到Intent。
此外还想说明一下,Intent还具有很好的设计思想在里面的。它将各种“启动意图”封装成一个一致编程模型,利于高层次的解耦。
1、Intent属性
<span style="white-space:pre"> </span>Intent intent = new Intent(); ComponentName componentName = new ComponentName(this, EventsActivity.class); intent.setComponent(componentName); startActivity(intent);这段代码的功能是用作从当前的activity启动到EventsActivity。
public ComponentName(String pkg, String cls) public ComponentName(Context pkg, String cls) public ComponentName(Context pkg, Class<?> cls)<span style="white-space:pre"> </span>//上面代码中使用到的构造,一般也是常用方法
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;
}<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 intent = new Intent();
intent.setAction("com.xmind.intent.action.TEST_ACTION");intent.addCategory("android.intent.category.DEFAULT");
startActivity(intent);
<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);<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"));android笔记6——intent的使用,布布扣,bubuko.com
原文:http://blog.csdn.net/enson16855/article/details/28624781