[TOC]

Android5.0以上不支持隐式启动服务,有常用的两种解决办法。

将隐式启动转换为显式启动,兼容编译sdk5.0以后版本

1
2
context.bindService(getExplicitIntent(mContext,new Intent(GPSBOARDCONTROL)),
serviceConnection, Context.BIND_AUTO_CREATE);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//将隐式启动转换为显式启动,兼容编译sdk5.0以后版本
public Intent getExplicitIntent(Context context,Intent implicitIntent){
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentServices(implicitIntent, 0);
if (resolveInfos == null || resolveInfos.size()!= 1) {
return null;
}
Intent explicitIntent = null;
ResolveInfo info = resolveInfos.get(0);
String packageName = info.serviceInfo.packageName;
String className = info.serviceInfo.name;
ComponentName component = new ComponentName(packageName,className);
explicitIntent = new Intent(implicitIntent);
explicitIntent.setComponent(component);
return explicitIntent;
}

显式通过包名来启动服务

1
2
3
4
Intent intent = new Intent("com.frewen.demo.service.ACTION");
intent.setAction(GPSBOARDCONTROL);//Service能够匹配的Action
intent.setPackage("com.frewen.demo.service");//应用的包名
context.bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);