intent

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 copy
import 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 copy
import 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中。如下图:
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值