intent

来源:互联网 发布:绫濑水泥杀人案 知乎 编辑:程序博客网 时间:2024/06/18 06:28

Intent代表了Android应用的启动“意图”,android应用将会根据Internet来启动制定组件,至于到底启动了哪个组件,则取决于Intent的各属性。下面就讨论下Intent的各属性值,以及Android如何根据不同属性值来启动相应的组件的,
Intent的Component属性需要接受一个ComponentName对象,ComponentName对象包含如下几个构造器
ComponentName(String pkg,String cls):创建pkg所在包下的cls类对应的组件
ComponentName(Context pkg,String cls):创建pkg所对应包下的cls类所对应的组件
ComponentName(Context pkg,Class

[java] view plain copyimport android.app.Activity;  import android.content.ComponentName;  import android.content.Intent;  import android.os.Bundle;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  public class MainActivity extends Activity  {      @Override      public void onCreate(Bundle savedInstanceState)      {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);          Button bn = (Button) findViewById(R.id.bn);          // 为bn按钮绑定事件监听器          bn.setOnClickListener(new OnClickListener()          {              @Override              public void onClick(View arg0)              {                  // 创建一个ComponentName对象                  <strong>ComponentName comp = new ComponentName(MainActivity.this,                      SecondActivity.class);                  Intent intent = new Intent();</strong>                  // 为Intent设置Component属性                  <strong>intent.setComponent(comp);  </strong>               startActivity(intent);              }          });      }  }  

上面程序中的三行粗体代码用于创建ComponentName对象,并将该对象设置成Intent对象的Component属性,这样应用程序即可根据该Intent的意图去启动制定的组件。
实际上,上面三行粗体字代码完全可以简化为如下形式:

[java] view plain copy//根据制定组件类来创建Intent  Intent intent = new Intent(ComponentAttr.this,SecondActivity.class);  

从上面的代码可以看出,当需要为Intent设置Component属性时,实际上Intent已经提供了一个简化的构造器,这样方便程序直接启动其他组件。
当程序通过Intent的Component属性启动特定组件时,被启动组件几乎不需要使用《intent-filter》元素进行配置;
程序的SecondActivity也很简单,它的界面布局中只包含一个简单的文本狂,用于显示该Activity对应的Intent的Component属性的包名、类名。代码如下:

[java] view plain copyimport android.app.Activity;  import android.content.ComponentName;  import android.os.Bundle;  import android.widget.EditText;  public class SecondActivity extends Activity  {      @Override      public void onCreate(Bundle savedInstanceState)      {          super.onCreate(savedInstanceState);          setContentView(R.layout.second);          EditText show = (EditText) findViewById(R.id.show);          // 获取该Activity对应的Intent的Component属性          ComponentName comp = getIntent().getComponent();          // 显示该ComponentName对象的包名、类名          show.setText("组件包名为:" + comp.getPackageName()                  + "\n组件类名为:" + comp.getClassName());      }  }  

运行上面的代码,通过第一个Acrivity中的按钮进入第二个Acrivity中。如下图:
这里写图片描述
这里写图片描述

作者:王诗婷:原文地址

原创粉丝点击