`
Everyday都不同
  • 浏览: 713640 次
  • 性别: Icon_minigender_1
  • 来自: 宇宙
社区版块
存档分类
最新评论

Activity组件与Service组件通过BroadcastReceiver监听器通信

阅读更多

1.首先,Activity的onCreate方法中要有启动后台Service的Intent

Intent intent = new Intent(this, xxxService.class);
startService(intent);

 为了能在AndroidManifest.xml中注册Activity中的receiver(它是内部类形式),需要把其定义成static的

 

public static class MyServiceReceiver extends BroadcastReceiver { ...}

 注意,当把receiver定义成static时,就不能使用non-static的sendBroadcast(intent) 方法了,如果要在receiver中发送广播消息,只能在onCreate中通过代码的方式注册receiver

 

 

2.在清单文件中注册Activity以及其内部receiver

 <activity
            android:name=".activity.xxxActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
 </activity>

<receiver android:name=".activity.xxxActivity$MyServiceReceiver">
   <intent-filter>
       <action android:name="com.example.action.UPDATE_BROADCAST" />
   </intent-filter>            
</receiver>

 其中,使用xxxActivity$MyServiceReceiver即可注册被定义成内部类的receiver. 此receiver用于接收后台service的广播信息,并通知前台Activity对界面进行改变等操作(一般来说前台Activity会实现onClickListener接口,会在button的单击事件中就广播消息给后台Service)。

 

 

 3.在后台Serivce中定义一个内部类型的receiver,因为要在此receiver中使用Non-static的sendBroadcast方法,所以不能定义为static了,所以就只好在此service的onCreate方法里注册该receiver了

 

public  class MyActivityReceiver extends BroadcastReceiver {.....}

 

 

4.在sevice的onCreate方法中注册该receiver

receiver = new MyActivityReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.action.CTL_BROADCAST");
registerReceiver(receiver, filter);

 其中filter.addAction("com.example.action.CTL_BROADCAST");指定该后台SERVICE所能监听到的action为

 

com.example.action.CTL_BROADCAST的intent.

 

以及,在清单文件中注册该Service:

<service android:name=".service.MusicService" />

 

 

5.注意,一旦Activity和Service一通信,他们内部类BroadcastReceiver的onReceive方法里面的intent参数即为它本身能够监听到的intent

如Activity中内部类的onReceive方法中的intent, 即为action为com.example.action.UPDATE_BROADCAST的Intent,

<action android:name="com.example.action.UPDATE_BROADCAST" />指定前台Activity所能监听的Action,表明后台如果想要给前台广播信息,必须发送一个action为com.example.action.UPDATE_BROADCAST的Intent:

Intent intent = new Intent("com.example.action.UPDATE_BROADCAST");
intent.putExtras(String key, Object value);
sendBroadcast(intent);

 同理,后台Service也一样。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics