Android开机启动程序

本文详细介绍了如何在Android系统开机时启动服务,包括配置文件的添加、服务类的实现以及如何通过定时器延迟启动服务。同时,解释了<category android:name=android.intent.category.HOME/>这一标签的意义及其在系统启动过程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面把我刚写好的 代码贴上

下面这个类 是接收系统开机时候发送广播的

public class MyReceiver extends BroadcastReceiver{ static final String ACTION ="android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(final Context context, Intent intent) { if(intent.getAction().equals(ACTION)) { // TODO Auto-generated method stub context.startService(new Intent(context,MyService.class)); Toast.makeText(context, "MyService has started!", 1).show(); } } }


下面这个类 是开启一个服务的 ,只要服务能启动到后台 起一个程序也是没问题的

public class MyService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub System.out.println("My Service create!"); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub System.out.println("My Service start!"); super.onStart(intent, startId); } }


配置文件需要添加的信息

<receiver android:name="MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.HOME"/> </intent-filter> </receiver> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

这里需要提示一点 android系统开机后 就会发出广播,这时候启动服务是需要延迟启动的,不然可是看不到后台服务的。具体怎么做。我写了一个定时器启动,程序挂掉了、、、、接着测。稍后补上

测了一下 原因是忘配 <service android:name=".MyService"></service> 这个了

加完 定时 启动服务 可以了

if(intent.getAction().equals(ACTION)) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub context.startService(new Intent(context,MyService.class)); Toast.makeText(context, "MyService has started!", 1).show(); } }, 3000); }


<category android:name="android.intent.category.HOME"/>

这句话 不知道什么意思,我自己猜想 可能是一个主界面的类别

sdk 提到过一嘴

It then displays the icons and labels of those activities in the launcher. Similarly, it discovers the home screen by looking for the activity with "android.intent.category.HOME" in its filter.

貌似 好像 是开机界面时候 才能接收到这个开机广播 等我把 定时器去了 再试试

测完了 , 不测了 总结:

的确 和定时器没有关系 而且启用定时器的话

02-10 17:16:52.000: ERROR/AndroidRuntime(471): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
消息队列会阻塞 挂掉启动Service的进程。。。。

<category android:name="android.intent.category.HOME"/>

这句话的意思 显而易见 就是加载完 主页面后 才会执行接收到系统开机广播要启动的服务。。。。可以见得写框架的这帮人是多么的有才。厉害人太多了,学吧。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值