5

intent的使用

 2 years ago
source link: http://www.androidchina.net/8818.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
intent的使用 – Android开发中文站

什么是Intent

Intent是一种运行时绑定(run-time binding)机制,它能在程序运行过程中连接两个不同的组件。通过Intent,你的程序可以向Android表达某种请求或者意愿,Android会根据意愿的内容选择适当的组件来完成请求。比如,有一个Activity希望打开网页浏览器查看某一网页的内容,那么这个Activity只需要发出WEB_SEARCH_ACTION给Android,Android就会根据Intent的请求内容,查询各组件注册时声明的IntentFilter,找到网页浏览器的Activity来浏览网页。

Android的三个基本组件——Activity,Service和Broadcast Receiver——都是通过Intent机制激活的,不同类型的组件有不同的传递Intent方式:

  • 要激活一个新的Activity,或者让一个现有的Activity做新的操作,可以通过调用Context.startActivity()或者Activity.startActivityForResult()方法。
  • 要启动一个新的Service,或者向一个已有的Service传递新的指令,调用Context.startService()方法或者调用Context.bindService()方法将调用此方法的上下文对象与Service绑定。
  • Context.sendBroadcast()、Context.sendOrderBroadcast()、Context.sendStickBroadcast()这三个方法可以发送Broadcast Intent。发送之后,所有已注册的并且拥有与之相匹配IntentFilter的BroadcastReceiver就会被激活。

下面我讲一下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);       // it.putExtra(“test”, "shuju”);
startActivity(it);          // startActivityForResult(it,REQUEST_CODE);

对于数据的获取可以采用:

Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");

3.向上一个Activity返回结果(使用setResult,针对startActivityForResult(it,REQUEST_CODE)启动的Activity)

Intent intent=getIntent();
Bundle bundle2=new Bundle();
bundle2.putString("name""This is from ShowMsg!");
intent.putExtras(bundle2);
setResult(RESULT_OK, intent);

4.回调上一个Activity的结果处理函数(onActivityResult)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE){
if(resultCode==RESULT_CANCELED)
setTitle("cancle");
else if (resultCode==RESULT_OK) {
String temp=null;
Bundle bundle=data.getExtras();
if(bundle!=null)   temp=bundle.getString("name");
setTitle(temp);
}
}
}

转载请注明:Android开发中文站 » intent的使用


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK