安卓 L (API 21) - java.lang.IllegalArgumentException : Service Intent must be explicit

标签 android android-intent android-service android-5.0-lollipop

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

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

如果您遇到了这个问题,并且您实际上打算以显式方式使用您的 Intent (这意味着在启动服务时您期望恰好命中 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;
    }

应该可以了。请随时发表评论,以获取有关此新问题的更多见解。

最佳答案

显式启动服务

intent = new Intent(context, Service.class);

或以隐式 Intent 显式提供包

intent = new Intent("com.example.intent.ACTION");
intent.setPackage("com.example")

关于安卓 L (API 21) - java.lang.IllegalArgumentException : Service Intent must be explicit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27183164/

相关文章:

java - Android studio dalvik vm 找不到类

android - 在向上滑动android时显示其他 View

android - 尝试启用到 Android 应用程序的深度链接,测试 Intent 无法启动 Activity

android - 停止远程进程中的服务

android - OpenCVAndroid Imgproc.GaussianBlur 应用程序停止

java - 按钮大小不一样

android - 我如何获得值 EditText 对话框?

android - Xamarin android - 从相机拍照然后将其传递给其他 Activity

安卓服务应用

android - 如何在 Android 上运行无限服务(前台服务被杀死)?