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

/**
*
@author coolszy
*@date 2011-6-14
*@blog
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系统在启动完毕后会发送广播,在系统关闭时是否也有对应的广播呢?通过查询帮助文档,找到了系统关闭的广播:

/**
*
@author coolszy
*@date 2011-6-14
*@blog
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>

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

相关文章:

  • 2021-06-18
  • 2021-06-02
  • 2022-12-23
  • 2022-12-23
  • 2021-07-04
  • 2022-01-08
猜你喜欢
  • 2021-11-25
  • 2022-12-23
  • 2021-11-25
  • 2021-06-27
相关资源
相似解决方案