有些时候我们需要我们的程序在系统开机后能自动运行,这个时候我们可以使用Android中的广播机制,编写一个继承BroadcastReceiver的类,接受系统启动关闭广播。代码如下:
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系统在启动完毕后会发送广播,在系统关闭时是否也有对应的广播呢?通过查询帮助文档,找到了系统关闭的广播:
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>
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN"/>
</intent-filter>
</receiver>