(Original) Solve the error: Service Intent must be explicit: Intent

I recently encountered this error, which appeared in startService. Two solutions are provided below

The first:

Add the package name to the intent you started the Service

Note that this package name is the package name of the started Service

If the application starts its own internal Service, just fill in its own package name

like this:

intent.setPackage(context.getPackageName());
context.startService(intent);  

The second type:

Use the following method to pass in your own intent

The returned intent can be used directly

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;
    }

 

Guess you like

Origin blog.csdn.net/Android_xiong_st/article/details/105840945