需求描述:有些时候,我们需要我们的程序在开机后能自动运行,在系统即将关闭时,能写入一些记录到指定的文件里。
一、开机广播监听:
Android系统启动完成后会发出启动完成广播(android.intent.action.BOOT_COMPLETED),所有注册了接收启动完成广播的接收器(BroadcastReceiver)都会收到此广播。
1、在AndroidManifest.xml文件里添加授予应用程序访问系统开机事件的权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2、编写系统发出的开机启动完成广播的接收器。自定类继承BroadcastReceiver类,代码如下:
package com.android.test; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * 类名:BootBroadcastReceiver * 功能描述:启动时系统发出的广播的接收器 * #<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> * @author android_ls */ public class BootBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "BootBroadcastReceiver"; private static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Boot this system , BootBroadcastReceiver onReceive()"); if (intent.getAction().equals(ACTION_BOOT)) { Log.i(TAG, "BootBroadcastReceiver onReceive(), Do thing!"); } } }
3、在AndroidManifest.xml文件里注册广播接收器
<receiver android:name="com.android.test.BootBroadcastReceiver" > <intent-filter > <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.HOME" /> </intent-filter> </receiver>
二、关机广播监听:
Android系统提供了与开机广播对应的关机广播,在系统即将关闭时发出此广播。
1、编写在系统即将关闭时发出的广播的接收器。自定类继承BroadcastReceiver类,代码如下:
package com.android.test; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * 类名:ShutdownBroadcastReceiver * 功能描述:在系统即将关闭时发出的广播的接收器 * @author android_ls */ public class ShutdownBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "ShutdownBroadcastReceiver"; private static final String ACTION_SHUTDOWN = "android.intent.action.ACTION_SHUTDOWN"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Shut down this system, ShutdownBroadcastReceiver onReceive()"); if (intent.getAction().equals(ACTION_SHUTDOWN)) { Log.i(TAG, "ShutdownBroadcastReceiver onReceive(), Do thing!"); } } }
2、在AndroidManifest.xml文件里注册广播接收器
<receiver android:name="com.android.test.ShutdownBroadcastReceiver" > <intent-filter > <action android:name="android.intent.action.ACTION_SHUTDOWN" /> <category android:name="android.intent.category.HOME" /> </intent-filter> </receiver>
注:开机关机操作有两种方式:1、重新启动,关闭后立刻又开机。这种情况下,开机启动完成和在系统即将关闭时发出的广播,都可以接收到。2、关机,这时的在系统即将关闭时发出的广播接收不到(我测试时遇到的情况)。开机,开机启动完成发出的广播时可以接收到的。
http://blog.csdn.net/android_ls/article/details/8605915
时间: 2024-10-16 12:45:20