Intent类:激活组件
在安卓系统中占有十分重要的位置,负责连接两个组件。
例如:应用程序的多个Activity之间的跳转时通过Intent来进行跳转的
2,Intent还可以启动一个Service服务,也可以发起一个Broadcast
=====
Intent由Action(动作)、Data(数据)、Category(分类)、Type(类型)、Component(组件)和Extra扩展信息)
通过这些便可以启动其他组件并传递信息。
setComponent方法
设置组件名称,设置intent对象要查询的组件名称
输入参数为ComponentName。
//
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
ComponentName componentname=new
ComponentName(firstActivity.this,"iflab.test.secondActivity");
Intent intent=new Intent();
intent.setComponent(componentname);
startActivity(intent);
}
======
setClass方法:设置查找的类
public Intent setClass(Context packageContext,Class<?> cls)
//........
与上一个例子很类似,
{
public void onCreate(View v){
。。。
Intent intent=new Intent();
intent.setClass(getApplicationContext(),secondActivity.class);
startActivity(intent);
}
//
=============
setClassName设置查找的类名称
public Intent setClassName(Context packageContext,String className)
//例如
intent.setClassName(getApplicationContext(),"iflab.test.secondActivity");
======
getIntent方法:获取Intent对象
===============
getComponent()方法获取组件名称
setAction设置Action
getAction获取Action
===================
addCategory添加附加信息
intent.addCategory(Intent.CATEGORY_HOME)
=========
putExtra方法,扩展信息设置
public Intent putExtra(String name,String value)
===================
getStringExtra()方法,获取扩展信息
//example
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(sevedInstanceState);
TextView tv=new TextView(this);
Intent intent =this.getIntent();
String name=intent.getStringExtra("name");
String key=intent.getStringExtra("key");
tv.setText("your information:");
tv.append(name);
tv.append(key);
}
=====================
setData()设置数据
//example
public void onClick(View v)
{
Intent intent=new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri data=Url.parse("http://www.baidu.com");
intent.setData(data);
startActivity(intent);
}
广播接收器BroadcastReceiver
安卓系统中的广播接收器,运行机制类似于事件处理。
系统级事件
1,可以通过sendBroadcast方法来发送系统广播
2,通过onReceive方法来接受系统广播
1,)sendBroadcast发送传递的是intent对象
public void sendBroadcast(Intent intent)
======
public Class myReceiver extends BroadcastReceiver{
public void onClick(View v)
{
Intent intent=new Intent();
intent.setAction(MY_ACTION);
intent.putExtra(“message",”from broadcast");
sendBroadcastReceiver(intent);
}
//
public void onReceiver(Context arg,Intent arg1)
{
String str;
str="收到的消息"+arg1.getStringExtra("message");
Toast.makeText(arg0,str,Toast.LENGTH_SHORT).show();
}
}
为了能使用myReceiver类:
在AndroidManifest.xml文件中声明myReceiver类为receiver
<receiver android:name="myReceiver">
<intent-filter>
<action android:name="iflab.test.MY_ACTION"> //iflab.test是package名,MY_ACTION是firstActivity类中自定义的ACTION:public static final String //MY_ACTION=”iflab.text.MY_ACTION"
</intent-filter>
</receiver>
====注册:
registerReceiver方法
unregisterReceiver方法。
。。。。后面继续补充,自己也是初学者,要是有什么不对的还希望大家补充!纠正