Android L (API 21) - java.lang.IllegalArgumentException:服务意图必须是显式的

son*_*ida 3 android android-intent android-service android-5.0-lollipop

Android 新版本 - “Lollipop”(API 21)带来了很多变化,但如果您希望将您的应用程序定位到该 API,它会付出一些代价。

当我们开始让我们的应用程序适应新的 API 时,我们遇到的第一个问题是 IllegalArgumentException: Service Intent must be explicit

如果您遇到了该问题,并且您实际上打算以显式方式使用您的意图(这意味着在启动服务时您希望恰好命中 1 个服务操作),那么这里有一个快速解决方法来转换隐式 --> 显式:

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;
    }
Run Code Online (Sandbox Code Playgroud)

那应该这样做。请随时发表评论以获取有关此新问题的更多见解。

rds*_*rds 5

显式启动服务

intent = new Intent(context, Service.class);
Run Code Online (Sandbox Code Playgroud)

或以隐式意图显式提供包

intent = new Intent("com.example.intent.ACTION");
intent.setPackage("com.example")
Run Code Online (Sandbox Code Playgroud)