Intent的用法实例:
1.无参数Activity跳转
Intent it=new Intent(Activity.Main.this,Activity2.class);
startActivity(it);
2.向下一个Activity传送数据(使用Bundle和Intent.putExtras)
Intent it=new Intent(Activity.Main.this,Activity2.class);
Bundle bundle=new Bundle();
bundle.putString(“name”,“This is from MainActivity !”);
it.putExtras(bundle);
startActivity(it);
对于数据的采取:
Bundle bundle=getIntent().getExtras();
String name=bundle.getString(“name”);
3.向上一个Activity返回结果(使用setResult,针对startAcyivity ForResult(it,REQUEST_CODE启动的Activity))
Intent intent=getIntent();
Bundle bundle2=new Bundle();
bundle2.putString(“name”,“This is from Show Msg !”);
intent.putExtras(bundle2);
setResult(RESULT_OK,intent);
4.回调上一个Actvity的结果处理函数(onActivityResult)
@Override
protected void onActivity Result(int requestCode,int result Code,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCodeREQUEST_CODE){
if(resultCodeRESULT_CANCELED){
setTitle(“cancle”);
}
else if(resultCode==RESULT_OK){
String temp=null;
Bundle bundle=data.getExtras();
if(bundle!=null)temp=bundle.getString(“name”);
setTitle(temp);
}
}
}
Intent的两种用法:
1.显式的Intent,即在构造Intent对象时就指定接受者,它一般用在知道目标组件名称的前提下,一般是在相同的应用程序内部实现的,如下所示:
Intent it=new Intent(Activity.Main.this,Activity2.class);
startActivity(it);
上面的intent中,直接指明了接受者:Activity2
2.隐式的Intent,即Intent的发送者在构造Intent对象时,并不知道也不关心接收者是谁,有利于降低发送者和接收者之间的耦合,它一般用在没有明确指出目标组件名称的前提下,一般用于在不同应用程序之间。
Intent it =new Intent();
it setAction(“com.google.test”);
startActivity(it);
上面intent,没有明确指明接受者,只是给了一个action作为接收者的过滤条件。
Android需要解析隐式Intent,将Intent映射给可以处理此Intent的Activity.IntentReceiver或Service。
Intent解析机制主要通过查找已注册在Android Manifest.xml中的所有Intent,最终找到匹配的Intent。在这个解析过程中,Android是通过Intent的action、type、category这三个属性来进行判断的,判断方法如下:
如果Intent指明定了action,则目标组件的IntentFilter的action列表中就必须包含有这个action,否则不能匹配;
如果Intent没有提供type,系统将