从 AndroidManifest 读取服务名称
Read service name from AndroidManifest
我想在我的项目中像 service
一样编写 Firebase 的 InstanceId service
。该项目是一个 SDK
,集成它的开发人员可以覆盖此 service
。在这种情况下,我应该能够读取开发人员在其 AndroidManifest.xml
文件中通过特定操作指定的新服务的名称。
所以这里真正的问题是,如何通过特定操作读取 AndroidManifest.xml
文件中声明的服务名称?
使用下面的实用方法
public static void startService(Context context, String lookupAction) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(lookupAction);
serviceIntent.setPackage("package.of.your.application");
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(serviceIntent, 0);
if (resInfo != null && !resInfo.isEmpty()) {
ServiceInfo service = resInfo.get(0).serviceInfo;
ComponentName cmpService = new ComponentName(service.applicationInfo.packageName, service.name);
Intent serviceToStart = new Intent(lookupAction);
serviceToStart.setComponent(cmpService);
context.startService(serviceToStart);
} else {
// Handle error
}
}
我会尽快添加文档
我想在我的项目中像 service
一样编写 Firebase 的 InstanceId service
。该项目是一个 SDK
,集成它的开发人员可以覆盖此 service
。在这种情况下,我应该能够读取开发人员在其 AndroidManifest.xml
文件中通过特定操作指定的新服务的名称。
所以这里真正的问题是,如何通过特定操作读取 AndroidManifest.xml
文件中声明的服务名称?
使用下面的实用方法
public static void startService(Context context, String lookupAction) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(lookupAction);
serviceIntent.setPackage("package.of.your.application");
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(serviceIntent, 0);
if (resInfo != null && !resInfo.isEmpty()) {
ServiceInfo service = resInfo.get(0).serviceInfo;
ComponentName cmpService = new ComponentName(service.applicationInfo.packageName, service.name);
Intent serviceToStart = new Intent(lookupAction);
serviceToStart.setComponent(cmpService);
context.startService(serviceToStart);
} else {
// Handle error
}
}
我会尽快添加文档