使用ARouter启动服务的时候的错误
- 在启动服务的时候,由于理解错误导致服务在内存中新建了两个实例。(虽然只有一个执行了生命周期,但是确实不应该)
正常用法
public interface RouteService extends IProvider {
<T> void set(T ...t);
}
- 新建中间层RouterService(一个普通的类)实现RouteService接口
- 这个类是用来启动操作Service的。
- 实现接口
/**
* 中间层
*/
@Route(path = ArouterConstants.ROUTER_SERVICE)//路由路径,通过它来找到对应的组件
public class RouterService implements RouteService {
private Context context;
@Override
public <T> void set(T... t) {
String serviceName = (String) t[0];
switch (serviceName) {
case ArouterConstants.UPLOAD_SERVICE:
startUploadService(context);
break;
}
}
@Override
public void init(Context context) {
this.context = context;
}
public void startUploadService(Context context) {
Intent intent = new Intent(context, UploadService.class);
context.startService(intent);
}
}
/**
* 启动Service
*/
private void startService() {
RouteService routeService = (RouteService) ARouter.getInstance().build(ArouterConstants.ROUTER_SERVICE).navigation();
routeService.set(ArouterConstants.UPLOAD_SERVICE);
}
整个流程大概就是通过Arouter启动一个其他moudle中的类,在这个类中启动Service。只是这个类是不Activity罢了,我一开始写错了,应为用例都是命名的Service,我就直接用我的Service服务实现了那个接口,导致了ARouter新建了一个Service的对象,然后再对象中使用了startService,这样就会产生两个Service的实例。
所以以后CV的时候还是需要仔细看看代码,起码稍微思考下步骤,别什么一股脑的就写到程序里。