在Activity中啟動Service的時候報錯: 服務意圖必須是顯性聲明。 這是為了防止造成沖突(i.e. 有多個Service用同樣的intent-filter的情況)
這是Android 5.0 (Lollipop) 之后的規定。 不能用包名的方式定義Service Intent, 而要用顯性聲明:
new Intent(context, xxxService.class);
如果一定要用隱性聲明,可以用下面的方法(Stackoverflow上的回答)
public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) { // Retrieve all services that can match the given intent PackageManager pm = context.getPackageManager(); List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0); // Make sure only one match was found if (resolveInfo == null || resolveInfo.size() != 1) { return null; } // Get component info and create ComponentName ResolveInfo serviceInfo = resolveInfo.get(0); String packageName = serviceInfo.serviceInfo.packageName; String className = serviceInfo.serviceInfo.name; ComponentName component = new ComponentName(packageName, className); // Create a new intent. Use the old one for extras and such reuse Intent explicitIntent = new Intent(implicitIntent); // Set the component to be explicit explicitIntent.setComponent(component); return explicitIntent; }