一、Intent对象及其属性
1.1 Intent的ComponentName属性
Intent查找组件策略,显示方式直接通过组件名称Component name来查找。Intent的组件名称对象由ComponentName类来封装,组件名称包含包名称和类名称,被声明在AndroidManifest.xml文件中
组件名称通过setComponent(),setClass(),setClassName()设置,通过getComponent()获得。
实例DEMO重要代码:
①在Button单击方法中创建组件名称对象,指向一个Activity,实例化Intent,并为其设置组件名称属性,启动Acticity
public void onClick(View v) {
//实例化组件名称
ComponentName cn = new ComponentName(MainActivity.this, MyActivity.class);
//实例化Intent
Intent intent = new Intent();
//为Intent设置组件名称属性
intent.setComponent(cn);
//启动Activity
startActivity(intent);
}
②在另外一个Acticity的onCreate()方法实例化文本框,获得Intent从而获得组件名称对象,从组件名称对象中获取包名称和类名称
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
//获得intent对象
Intent intent=getIntent();
//获得组件名称对象
ComponentName cn = intent.getComponent();
//获得包名
String packageName = cn.getPackageName();
// 获得类名称
String className = cn.getClassName();
//实例化TextView
textView = (TextView)findViewById(R.id.textView1);
textView.setText(" 组件包名称:"+packageName+",类名称:"+className);
}
1.2 Intent的Action属性
Action是指Intent要完成的动作,是一个字符串常量。Intent类里面定义了大量的Action常量属性,例如ACTION_CALL、ACTION_EDIT、ACTION_BATTEAY_LOW。我们可以自己定义Action来使用。
通过setAction()来设置Intent的Action属性,使用getAction来获得Intent的Action属性。
①自定义Action属性
为Intent定义一个Action属性来访问,Action属性是一个字符串。我们在程序中定义,并在要访问最贱的IntentFilter中声明就可以。
/定义Action属性常量
private static final String MY_ACTION = "com.hanfeng.intent_action.MY_ACTION";
public void onClick(View v) {
//实例化Intent
Intent intent = new Intent();
//为Intent设置Action属性
intent.setAction(MY_ACTION);
//启动Activity
startActivity(intent);
}
在另外一个Acticity的onCreate()方法实例化文本框,获得Intent实例,从而获得属性并显示在textView里面
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
//获得intent对象
Intent intent=getIntent();
//获得Action
String action= intent.getAction();
//实例化TextView
textView = (TextView)findViewById(R.id.textView1);
textView.setText(action);
}
在AndroidManifest.xml配置文件中添加一个Acticity的声明,在IntentFilter元素中指定Action属性
<activity android:name=".MyActivity" >
<intent-filter>
<action android:name="com.hanfeng.acticity。.MY_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
尚未完结笔记