在一个程序中设置了一下属性,
android:persistent="true"
android:directBootAware="true"
以上属性的含义分别为:
android:persistent=“true”,设置该程序为常启动程序,开机启动,并且异常崩溃后,重新自动启动;
android:directBootAware=“true”,允许程序在android未启动完成时期(解锁阶段)启动,现象上来看,在开机动画结束之前就可以启动,设置为false,则表示在开机动画完成后,launcher启动后才启动。
在App程序中的Application中执行了启动服务的操作:
Intent intent = new Intent();
intent.setClass(this,CarControlService.class);
this.startService(intent);
出现问题
然后开机后程序报错:
2019-11-04 17:01:51.599 2467-2467/com.ad.carcontrol I/CarControlApplication: onCreate,start CarControlService.
2019-11-04 17:01:51.600 1750-2030/system_process W/ActivityManager: Unable to start service Intent { cmp=com.ad.carcontrol/.CarControlService } U=0: not found
即未找到相关服务。
经过调查发现该服务已经在AndroidManifest.xml中注册了,但是为什么还是找不到呢?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.ad.carcontrol">
<application>
<service
android:name=".CarControlService"
android:exported="true">
<intent-filter android:priority="999">
<action android:name="com.ad.carcontrol.CarControlService" />
</intent-filter>
</service>
</application>
</manifest>
解决方法
将属性改为:
android:directBootAware=“false”
服务启动正常。
原因
设置属性android:persistent="true"和android:directBootAware="true"后,该app程序启动的非常早,导致Application中的onCreate()很早就开始执行了,而这个时候Android系统对AndroidManifest.xml中注册的服务扫描还没有完成,所以进行startService()的时候,会报错提示找不到服务。