Intent详解

     Intent提供了一种通用的消息系统,它允许在你的应用程序与其它的应用程序间传递Intent来执行动作和产生事件。使用Intent可以激活Android应用的三个核心组件:活动、服务和广播接收器。

    Intent可以划分成显式意图和隐式意图。

    显式意图:调用Intent.setComponent()或Intent.setClass()方法明确指定了组件名的Intent为显式意图,显式意图明确指定了Intent应该传递给哪个组件。

    隐式意图:没有明确指定组件名的Intent为隐式意图。Android系统会根据隐式意图中设置的动作(action)、类别(category)、数据(URI和数据类型)找到最合适的组件来处理这个意图。对于隐式意图,Android是怎样寻找到这个最合适的组件呢?我们在定义活动时,指定了一个intent-filter,IntentFilter(意图过滤器)其实就是用来匹配隐式Intent的,当一个意图对象被一个意图过滤器进行匹配测试时,只有三个方面会被参考到:动作、数据(URI以及数据类型)和类别。

    下面来看一个显示意图的demo:

public class IntentDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button button=(Button) this.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            /*    Intent intent=new Intent();
                intent.setClass(IntentDemoActivity.this, OtherActivity.class);*/
                
            /*    Intent intent=new Intent();
                intent.setComponent(new ComponentName(IntentDemoActivity.this, OtherActivity.class));*/
                
                Intent intent=new Intent(IntentDemoActivity.this, OtherActivity.class);
                startActivity(intent);
                
            }
        });
    }
}

可以调用Intent.setComponent()或Intent.setClass()方法或new Intent(IntentDemoActivity.this,OtherActivity.class)方法,一样的哦!下面看一下效果吧:

 

   点击button按钮后:

    跳转到了另一个activity。   

    下面我们看一下隐式意图的demo:

public class IntentDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);  
                Intent intent=new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:123"));   
                startActivity(intent);
setContentView(R.layout.main); Button button=(Button) this.findViewById(R.id.button1);
button.setOnClickListener(
new View.OnClickListener()
{

@Override
public void onClick(View v)
{
Intent intent=new Intent();
intent.setAction("cn.com.karl.intent.OtherActivity");
startActivity(intent);
}
});

}}

 

posted @ 2013-06-28 11:20  Wolves  阅读(196)  评论(0)    收藏  举报