在最近的项目的中某项功能需要在项目启动的时候开启服务,由于从8.0系统开始google已经不允许我们启动后台服务了,所以所有的服务必须是前台的,而且创建通知栏的规则也进行了调整,channelid变成了必要的参数,于是我们一步一步的按照8.0的要求来,通知按照最新规则创建了,在服务oncreate(),onStartCommond()都调用了显示通知的方法,但是...在部分手机中还是会抛异常,这个异常无法被bugtags捕获但是可以被友盟错误统计和百度错误统计捕获,于是直线上升的错误率让领导疯了,我们开发人员惨了...
具体错误信息如下:
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1817)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:6642)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
通过错误信息我们可以轻易的查到原因是由于我们在调用了startForegroundService()方法5s内没有Service.startForeground()超时导致的,可是我们明明调用了呀,而且错误只在某些机型的某些未知场景下出现,只能通过统计平台捕获的这点信息来猜测问题出在了哪,因为根本无法复现,即使在问题机型上也一直没有复现出来?,于是疯狂的猜测问题出现在了哪疯狂的改代码疯狂的上测试版的包...
经过几天的测试,问题终于还是没有解决!
于是万念俱灰之间我们决定将服务的启动方式修改了,由原来的
Intent intent = new Intent(application, TodayStepService.class);
ContextCompat.startForegroundService(application, intent);
这种方式修改为
stepServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//Activity和Service通过aidl进行通信
iSportStepInterface = ISportStepInterface.Stub.asInterface(service);
try {
mStepSum = iSportStepInterface.getCurrentTimeSportStep();
updateStepCount();
} catch (RemoteException e) {
e.printStackTrace();
}
shareHandler.sendEmptyMessageDelayed(REFRESH_STEP_WHAT, TIME_INTERVAL_REFRESH);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//开启Service,同时绑定Activity进行aidl通信
Intent stepIntent = new Intent(this, TodayStepService.class);
bindService(stepIntent, stepServiceConnection, Context.BIND_AUTO_CREATE);
再做一次尝试,惊喜的是竟然好了。
由于不知道具体的错误原因,所以做出以下推断:
9以后就没有上述问题,说明android8.0和8.1系统对服务的管理是有问题的。由于8.0系统进行了大量的电量优化,又有国内厂商的定制,某段不成熟的代码导致上述问题,虽然问题解决了,但原因不明,希望看到的大佬可以解惑。