Intent代表了Android应用的启动“意图”,Android应用汇根据Intent来启动指定组件,至于到底启动哪个组件,取决于Intent的各个属性,Intent对象大致包含Component、Action、Category、Data、Type、Extra和Flag这7种属性
Intent的Component属性需要接受一个ComponentName对象,ComponentName对象包含如下几个构造器
- ComponentName(String pkg,String cls): 创建pkg所在包下的cls类所对应的组件
- ComponentName(Context pkg,String cls): 创建pkg所对应的包下的cls类所对应的组件
- ComponentName(Context pkg,Class<?> cls): 创建pkg所对应的包下的cls类所对应的组件
- setClass(Context packageContext,Class<?> cls):设置Intent将要启动的组件对应的类。
- setClassName(Context packageContext,String className):设置该Intent将要启动的组件对应的类名
- setClassName(String packageName,String className):设置该Intent将要启动的组件对应的类名
实例
点击跳转按钮,跳转到下个页面,同时在下个页面获取component,所在包名和类名
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button android:id="@+id/jump"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="跳转"/>
</LinearLayout>
MainActivity.java
package com.example.compontenttest;
import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but=(Button) super.findViewById(R.id.jump);
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
ComponentName component=new ComponentName(MainActivity.this,SeconActivitiy.class);
Intent intent=new Intent();
intent.setComponent(component);
startActivity(intent);
}
});
}
}
second_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
SecondActivity.java
package com.example.compontenttest;
import android.app.Activity;
import android.content.ComponentName;
import android.os.Bundle;
import android.widget.TextView;
public class SeconActivitiy extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView=(TextView) super.findViewById(R.id.result);
//获取该Activity对应的Intent的Component属性
ComponentName component=getIntent().getComponent();
//显示该component对象的包名,类名
textView.setText("组件包名为"+component.getPackageName()+"\n组件类名为"+component.getClassName());
}
}