当前位置: 代码迷 >> Android >> Android Service 服务(2)—— BroadcastReceiver
  详细解决方案

Android Service 服务(2)—— BroadcastReceiver

热度:142   发布时间:2016-05-01 10:48:01.0
Android Service 服务(二)—— BroadcastReceiver

一、 BroadcastReceiver简介

BroadcastReceiver,用于异步接收广播Intent,广播Intent是通过调用Context.sendBroadcast()发送、BroadcastReceiver()接收。

广播Intent的发送是通过调用Context.sendBroadcast()、Context.sendOrderedBroadcast()、Context.sendStickyBroadcast()来实现的。通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收,广播接收者和JMS中的Topic消息接收者很相似。
广播接收器只能接收广播,对广播的通知做出反应,很多广播都产生于系统代码,如:时区改变的通知、电池电量不足、用户改变了语言偏好,或者开机启动等
广播接收器没有用户界面,但是它可以为它们接收到信息启动一个Activity或者使用NotificationManager来通知用户.

?

BroadcastReceiver 接收广播方式:
1. Normal broadcasts(正常广播),用 Context.sendBroadcast()发送是完全异步的,它们都运行在一个未定义的顺序,通常是在同一时间。这样会更有效,但意味着receiver不能包含所要使用的结果或中止的API。 ?
2. Ordered broadcasts(有序广播),用 Context.sendOrderedBroadcast()发送每次被发送到一个receiver。所谓有序,就是每个receiver执行后可以传播到下一个receiver,也可以完全中止传播——不传播给其他receiver。 而receiver运行的顺序可以通过matched intent-filter 里面的android:priority来控制,当priority优先级相同的时候,Receiver以任意的顺序运行。

?

二、 BroadcastReceiver注册方式

?

1 静态注册
AndroidManifest.xml中,application里面,定义receiver并设置要接收的action

[java]?view plaincopyprint?
?
  1. <receiver?android:name=".receiver.MusicReceiver"?>??
  2. ????<intent-filter>??
  3. ????????<action?android:name="com.homer.receiver.musicReceiver"?/>??
  4. ????</intent-filter>??
  5. </receiver>??


2 动态注册
Activity中,需在onStart()中调用registerReceiver()进行注册和在onStop中调用unregisterReceiver()释放服务

[java]?view plaincopyprint?
?
  1. private?MusicReceiver?receiver;??
  2. ??
  3. @Override??
  4. protected?void?onStart(){??
  5. ????super.onStart();??
  6. ??????
  7. ????receiver?=?new?MusicReceiver();??
  8. ????IntentFilter?filter?=?new?IntentFilter();??
  9. ????filter.addAction("com.homer.receiver.musicReceiver");??
  10. ????this.registerReceiver(receiver,?filter);??
  11. }??
  12. ??
  13. @Override??
  14. protected?void?onStop(){??
  15. ????this.unregisterReceiver(receiver);??
  16. ??????
  17. ????super.onStop();??
  18. }??


3 两种注册方式的比较
静态注册方式,由系统来管理receiver,而且程序里的所有receiver,可以在xml里面一目了然
动态注册方式,隐藏在代码中,比较难发现;需要特别注意的是,在退出程序前要记得调用Context.unregisterReceiver()方法。一般在activity的onStart()里面进行注册, onStop()里面进行注销。官方提醒,如果在Activity.onResume()里面注册了,就必须在Activity.onPause()注销。

?

三、 BroadcastReceiver生命周期

一个BroadcastReceiver 对象只有在被调用onReceive(Context, Intent)的才有效,当从该函数返回后,该对象就无效的了,结束生命周期。
因此从这个特征可以看出,在所调用的onReceive(Context, Intent)函数里,不能有过于耗时的操作,不能使用线程来执行。对于耗时的操作,应该在startService中来完成。因为当得到其他异步操作所返回的结果时,BroadcastReceiver 可能已经无效了。

?

四、 BroadcastReceiver示例

Activity

?

[java]?view plaincopyprint?
?
  1. public?class?PlayMusicRecevicer?extends?Activity?implements?OnClickListener?{??
  2. ??????
  3. ????private?Button?playBtn;??
  4. ????private?Button?stopBtn;??
  5. ????private?Button?pauseBtn;??
  6. ????private?Button?exitBtn;??
  7. ????private?Button?closeBtn;??
  8. ??????
  9. ????private?Intent?intent;??
  10. ??????
  11. ????@Override??
  12. ????public?void?onCreate(Bundle?savedInstanceState)?{??
  13. ????????super.onCreate(savedInstanceState);??
  14. ????????setContentView(R.layout.music_receiver);??
  15. ??
  16. ????????playBtn?=?(Button)?findViewById(R.id.play);??
  17. ????????stopBtn?=?(Button)?findViewById(R.id.stop);??
  18. ????????pauseBtn?=?(Button)?findViewById(R.id.pause);??
  19. ????????exitBtn?=?(Button)?findViewById(R.id.exit);??
  20. ????????closeBtn?=?(Button)?findViewById(R.id.close);??
  21. ??????????
  22. ????????playBtn.setOnClickListener(this);??
  23. ????????stopBtn.setOnClickListener(this);??
  24. ????????pauseBtn.setOnClickListener(this);??
  25. ????????exitBtn.setOnClickListener(this);??
  26. ????????closeBtn.setOnClickListener(this);??
  27. ??
  28. ????}??
  29. ??
  30. ????@Override??
  31. ????public?void?onClick(View?v)?{??
  32. ????????int?op?=?-1;??
  33. ?????????intent?=?new?Intent("com.homer.receiver.musicReceiver");??
  34. ??
  35. ????????switch?(v.getId())?{??
  36. ????????case?R.id.play:?????????????????????????????//?play?music??
  37. ????????????op?=?1;??
  38. ????????????break;??
  39. ????????case?R.id.stop:?????????????????????????????//?stop?music??
  40. ????????????op?=?2;??
  41. ????????????break;??
  42. ????????case?R.id.pause:????????????????????????????//?pause?music??
  43. ????????????op?=?3;??
  44. ????????????break;??
  45. ????????case?R.id.close:????????????????????????????//?close?activity??
  46. ????????????this.finish();??
  47. ????????????break;??
  48. ????????case?R.id.exit:?????????????????????????????//?process?by?MusicReceiver??
  49. ????????????op?=?4;??
  50. ????????????this.finish();??
  51. ????????????break;??
  52. ????????}??
  53. ??
  54. ????????Bundle?bundle?=?new?Bundle();??
  55. ????????bundle.putInt("op",?op);??
  56. ????????intent.putExtras(bundle);??
  57. ??
  58. ?????????sendBroadcast(intent);?????????????????????//?sendBroadcast??
  59. ????}??
  60. ??
  61. //??private?MusicReceiver?receiver;??
  62. //????
  63. [email protected]??
  64. //??protected?void?onStart(){??
  65. //??????super.onStart();??
  66. //????????
  67. //??????receiver?=?new?MusicReceiver();??
  68. //??????IntentFilter?filter?=?new?IntentFilter();??
  69. //??????filter.addAction("com.homer.receiver.musicReceiver");??
  70. //??????this.registerReceiver(receiver,?filter);??
  71. //??}??
  72. //????
  73. [email protected]??
  74. //??protected?void?onStop(){??
  75. //??????this.unregisterReceiver(receiver);??
  76. //????????
  77. //??????super.onStop();??
  78. //??}??
  79. ??????
  80. ????@Override??
  81. ????public?void?onDestroy(){??
  82. ????????super.onDestroy();??
  83. ??????????
  84. ????????if(intent?!=?null){??
  85. ????????????stopService(intent);??
  86. ????????}??
  87. ????}??
  88. }??

?

?

BroadcastReceiver

?

[java]?view plaincopyprint?
?
  1. public?class?MusicReceiver?extends?BroadcastReceiver?{??????//?receive?Broadcast??
  2. ??????
  3. ????@Override??
  4. ????public?void?onReceive(Context?context,?Intent?intent)?{??
  5. ??????????
  6. ????????if(intent?!=?null){??
  7. ????????????Bundle?bundle?=?intent.getExtras();??
  8. ????????????Intent?it?=?new?Intent(context,?MusicReceiverService.class);????//?call?service?for?MusicReceiverService.class??
  9. ????????????it.putExtras(bundle);??
  10. ????????????if(bundle?!=?null){??
  11. ????????????????int?op?=?bundle.getInt("op");??
  12. ????????????????if(op?==?4){??
  13. ????????????????????context.stopService(it);????????//?stopService??
  14. ????????????????}else{??
  15. ????????????????????context.startService(it);???????//?startService??
  16. ????????????????}??
  17. ????????????}??
  18. ????????}??
  19. ????}??
  20. }??

?

?

Service(BroadcastReceiver调用的后台服务)

?

[java]?view plaincopyprint?
?
  1. public?class?MusicReceiverService?extends?Service?{??
  2. ??????
  3. ????private?MediaPlayer?mediaPlayer;??
  4. ??
  5. ????@Override??
  6. ????public?IBinder?onBind(Intent?arg0)?{??
  7. ????????return?null;??
  8. ????}??
  9. ??
  10. ????@Override??
  11. ????public?void?onCreate()?{??
  12. ????????Toast.makeText(this,?"show?media?player",?Toast.LENGTH_SHORT).show();??
  13. ??
  14. ????????if?(mediaPlayer?==?null)?{??
  15. ????????????mediaPlayer?=?MediaPlayer.create(this,?R.raw.tmp);??
  16. ????????????mediaPlayer.setLooping(false);??
  17. ????????}??
  18. ????}??
  19. ??
  20. ????@Override??
  21. ????public?void?onDestroy()?{??
  22. ????????Toast.makeText(this,?"stop?media?player",?Toast.LENGTH_SHORT);??
  23. ????????if?(mediaPlayer?!=?null)?{??
  24. ????????????mediaPlayer.stop();??
  25. ????????????mediaPlayer.release();??
  26. ????????}??
  27. ????}??
  28. ??
  29. ????@Override??
  30. ????public?void?onStart(Intent?intent,?int?startId)?{??
  31. ????????if?(intent?!=?null)?{??
  32. ????????????Bundle?bundle?=?intent.getExtras();??
  33. ????????????if?(bundle?!=?null)?{??
  34. ????????????????int?op?=?bundle.getInt("op");??
  35. ????????????????switch?(op)?{??
  36. ????????????????case?1:??
  37. ????????????????????play();??
  38. ????????????????????break;??
  39. ????????????????case?2:??
  40. ????????????????????stop();??
  41. ????????????????????break;??
  42. ????????????????case?3:??
  43. ????????????????????pause();??
  44. ????????????????????break;??
  45. ????????????????}??
  46. ????????????}??
  47. ????????}??
  48. ????}??
  49. ??
  50. ????public?void?play()?{??
  51. ????????if?(!mediaPlayer.isPlaying())?{??
  52. ????????????mediaPlayer.start();??
  53. ????????}??
  54. ????}??
  55. ??
  56. ????public?void?pause()?{??
  57. ????????if?(mediaPlayer?!=?null?&&?mediaPlayer.isPlaying())?{??
  58. ????????????mediaPlayer.pause();??
  59. ????????}??
  60. ????}??
  61. ??
  62. ????public?void?stop()?{??
  63. ????????if?(mediaPlayer?!=?null)?{??
  64. ????????????mediaPlayer.stop();??
  65. ????????????try?{??
  66. ????????????????mediaPlayer.prepare();??//?在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数??
  67. ????????????}?catch?(IOException?ex)?{??
  68. ????????????????ex.printStackTrace();??
  69. ????????????}??
  70. ????????}??
  71. ????}??
  72. }??

?

?

AndroidManifest.xml

?

[css]?view plaincopyprint?
?
  1. <service??
  2. ????android:name=".receiver.MusicReceiverService"??
  3. ????android:enabled="true"?>??
  4. ????<intent-filter>??
  5. ????????<action?android:name="com.homer.service.musicReceiverService"?/>??
  6. ????</intent-filter>??
  7. </service>???
  8. <receiver?android:name=".receiver.MusicReceiver"?>??
  9. ????<intent-filter>??
  10. ????????<action?android:name="com.homer.receiver.musicReceiver"?/>??
  11. ????</intent-filter>??
  12. </receiver>??



?

五、代码解析

?

1、Activity中,PlayMusicService中通过重写OnClickListener 接口onClick()方法实现对播放音乐的控制,把音乐各种操作用数字通过Intent传递给service

然后通过构造一个Intent , intent = new Intent("com.homer.receiver.musicReceiver");?

其中,com.homer.receiver.musicReceiver是?AndroidManifest.xml?对receiver的定义(或动态注册addAction为filter.addAction("com.homer.receiver.musicReceiver");)

2、Activity中,音乐播放的控制,利用Bundle绑定数字op后,通过?sendBroadcast(intent);?广播出去
Bundle bundle = new Bundle();
bundle.putInt("op", op);
intent.putExtras(bundle);

startService(intent);

3、 BroadcastReceiver中,会处理Activity启动的?sendBroadcast(intent); 广播,通过实现onReceive()方法,解析Activity中Intent的Bundle数据。

然后通过Intent it = new Intent(context, MusicReceiverService.class); 初始化一个启动Service服务的Intent

最后根据解析bundle的op数值决定启动context.startService(it); 服务 或 关闭context.stopService(it);?服务

4、Service中,处理BroadcastReceiver广播启动的MusicReceiverService服务,即依次调用service的启动过程:onCreate --> onStart(可多次调用) --> onDestroy

onCreate(), ?创建mediaPlayer

onStart(), ? ? ?通过获取Bundle bundle = intent.getExtras();,提取int op = bundle.getInt("op");,然后执行响应的音乐播放操作

onDestroy(),停止并释放mediaPlayer音乐资源,如果当执行context.stopService()时调用此方法

5、Activity中,onClick()函数中close与exit是执行含义是不同的:

close : 只是执行了this.finish(); 关闭了本Activity窗体,service并没有被关掉,音乐依然会继续在后台播放

exit?: 先调用了stopService(intent); 关闭了service服务,在Service中会调用3中的onDestroy()停止并释放音乐资源,后才执行this.finish(); 关闭了本Activity窗体

?

六、BroadcastReceiver总结

BroadcastReceiver需要先注册receriver(静态或动态)—> 发送广播sendBroadcast(intent)?—>?处理广播onReceive(Context context, Intent intent)?—> 启动服务startService(it)?—> 关闭服务stopService(it)?

其中,receriver两种注册方式,静态注册在AndroidManifest.xml中的receiver和动态注册在PlayMusicRecevicer注释的代码部分,两者选择一种即可

?

代码下载

?

?

参考推荐:

Android Service生命周期及用法

Android之BroadcastReceiver的使用(静态和动态两种注册方式)

?

  相关解决方案