您的位置:首页 > 其它

Service两种不同的调用方式以及BroadcastReceiver两种不同的注册方式

2011-12-29 17:10 706 查看
一、Service
如果把Activity比喻为前台程序,那么Service就是后台程序,Service的整个生命周期都只会在后台执行。Service跟Activity一样也由Intent调用。在工程里想要添加一个Service,先新建继承Service的类,然后到AndroidManifest.xml -> Application ->Application
Nodes中的Service标签中添加。
Service要由Activity通过startService 或者 bindService来启动,Intent负责传递参数

1、startService中,service的生命周期为onCreate-->onStart-->onDestroy(由startService开始的service必须调用stopService才能终止service的运作,不调用stopService,那么即使Activity.finish()了Service还是在运作)

2、bindService中,service的生命周期为onCreate-->onBind-->【Activity.finish()】-->onUnbind-->onDestroy(由bindService开始的service可以用onunbindService停止service运作,也可以在一个Activity finish以后自动unbindService停止运作)

二、BroadcastReceiver
1、BroadcastReceiver接受并处理自定义Action广播通知,Receiver的注册一般分为动态注册和静态注册,动态注册就是通过API registerReceiver来注册,静态的一般就是写在AndroidManifest.xml
2、步骤
A、动态注册:
【1】 registerReceiver(BroadcastReceiver, new IntentFilter(String
actionAddress)); //我自己设定的actionAddress的值为com.woody.testCase.Internal_1,IntentFilter为结构化描述intent匹配的信息,必须包含action,可包含data与category
【2】创建BroadcastReceiver类(BroadcastReceiver receiver = new BroadcastReceiver()),并实现它的onReceive(Context context,Intent intent)方法 //context值为之前的actionAddress,也就是com.woody.testCase.Internal_1,得到传过来的值可通过调用intent.getAction()来获取
【3】基本工作都做好了,接下来就应该通知receiver了
Intent intent = new Intent(actionAddress); //值为刚才的com.woody.testCase.Internal_1
sendBroadcast(intent);

B、静态注册:
【1】AndroidManifest.xml中add Receiver节点,如下:

<receiver android:name="clsReceiver2">
<intent-filter>
<action
android:name="com.woody.testCase.Internal_2"/>
</intent-filter>
</receiver>
【2】在外新建个Receiver类,并继承BroadcastReceiver类,实现onReceive,具体代码与之前动态的雷同
【3】通知receiver
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: