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

Android开机广播跟关机广播

热度:28   发布时间:2016-05-01 10:48:07.0
Android开机广播和关机广播
http://blog.csdn.net/coolszy/article/details/6544598

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

/**  [email protected] coolszy  [email protected] 2011-6-14  [email protected] http://blog.csdn.net/coolszy  */    public class BootCompletedReceiver extends BroadcastReceiver  {        @Override      public void onReceive(Context context, Intent intent)      {          Log.i("MainActivity", "系统启动完毕");      }  }   

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

<receiver android:name=".BootCompletedReceiver">                <intent-filter>                    <action android:name="android.intent.action.BOOT_COMPLETED"/>                </intent-filter>            </receiver>   


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

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 


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

/**  [email protected] coolszy  [email protected] 2011-6-14  [email protected] http://blog.csdn.net/coolszy  */    public class ShutdownReceiver extends BroadcastReceiver  {        @Override      public void onReceive(Context context, Intent intent)      {          Log.i("MainActivity", "启动关闭中...");      }  }  

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

<receiver android:name=".ShutdownReceiver">                <intent-filter>                    <action android:name="android.intent.action.ACTION_SHUTDOWN"/>                </intent-filter>            </receiver>   


是否还需要相应的权限呢?通过查询帮助文档,并没有找到相关的权限,在模拟器中进行测试,当系统关闭后能正常输出信息。
  相关解决方案