当前位置: 代码迷 >> Android >> Android开机播音和关机广播
  详细解决方案

Android开机播音和关机广播

热度:59   发布时间:2016-05-01 14:24:15.0
Android开机广播和关机广播

?


分类: Android 3971人阅读 评论(19) 收藏 举报

有些时候我们需要我们的程序在系统开机后能自动运行,这个时候我们可以使用Android中的广播机制,编写一个继承BroadcastReceiver的类,接受系统启动关闭广播。代码如下:

view plain
  1. /**?
  2. [email protected]?
  3. [email protected]?
  4. [email protected]://blog.csdn.net/coolszy?
  5. ?*/??
  6. ??
  7. public?class?BootCompletedReceiver?extends?BroadcastReceiver??
  8. {??
  9. ??
  10. ????@Override??
  11. ????public?void?onReceive(Context?context,?Intent?intent)??
  12. ????{??
  13. ????????Log.i("MainActivity",?"系统启动完毕");??
  14. ????}??
  15. }??
然后在AndroidManifest.xml文件中进行注册:
  
view plain
  1. <receiver?android:name=".BootCompletedReceiver">????
  2. ????????????<intent-filter>????
  3. ????????????????<action?android:name="android.intent.action.BOOT_COMPLETED"/>????
  4. ????????????</intent-filter>????
  5. ????????</receiver>???

同时应添加所需要的权限:

view plain
  1. <uses-permission?android:name="android.permission.RECEIVE_BOOT_COMPLETED"?/>??

既然Android系统在启动完毕后会发送广播,在系统关闭时是否也有对应的广播呢?通过查询帮助文档,找到了系统关闭的广播:

view plain
  1. /**?
  2. [email protected]?
  3. [email protected]?
  4. [email protected]://blog.csdn.net/coolszy?
  5. ?*/??
  6. ??
  7. public?class?ShutdownReceiver?extends?BroadcastReceiver??
  8. {??
  9. ??
  10. ????@Override??
  11. ????public?void?onReceive(Context?context,?Intent?intent)??
  12. ????{??
  13. ????????Log.i("MainActivity",?"启动关闭中...");??
  14. ????}??
  15. }??

在AndroidManifest.xml文件中进行注册:

  
view plain
  1. <receiver?android:name=".ShutdownReceiver">????
  2. ????????????<intent-filter>????
  3. ????????????????<action?android:name="android.intent.action.ACTION_SHUTDOWN"/>????
  4. ????????????</intent-filter>????
  5. ????????</receiver>???
是否还需要相应的权限呢?通过查询帮助文档,并没有找到相关的权限,在模拟器中进行测试,当系统关闭后能正常输出信息。
  相关解决方案