Service Intent must be explicit: Intent

I have an app some time now in which I call a service through a broadcast receiver (MyStartupIntentReceiver). The code in the broadcast receiver in order to call the service is:

public void onReceive(Context context, Intent intent) {
    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.duk3r.eortologio2.MyService");
    context.startService(serviceIntent);
}

The problem is that in Android 5.0 Lollipop I get the following error (in previous versions of Android, everything works ok):

Unable to start receiver com.duk3r.eortologio2.MyStartupIntentReceiver: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.duk3r.eortologio2.MyService }

What do I have to change in order for the service to be declared as explicit and start normally? Tried some answers in other similar threads but although i got rid of the message, the service wouldn't start.


Solution 1:

any intent you make to a service, activity etc. in your app should always follow this format

Intent serviceIntent = new Intent(context,MyService.class);
context.startService(serviceIntent);

or

Intent bi = new Intent("com.android.vending.billing.InAppBillingService.BIND");
bi.setPackage("com.android.vending");

implicit intents (what you have in your code currently) are considered a security risk

Solution 2:

Set your packageName works.

intent.setPackage(this.getPackageName());

Solution 3:

Convert implicit intent to explicit intent then fire start service.

        Intent implicitIntent = new Intent();
        implicitIntent.setAction("com.duk3r.eortologio2.MyService");
        Context context = getApplicationContext();
        Intent explicitIntent = convertImplicitIntentToExplicitIntent(implicitIntent, context);
        if(explicitIntent != null){
            context.startService(explicitIntent);
            }


    public static Intent convertImplicitIntentToExplicitIntent(Intent implicitIntent, Context context) {
            PackageManager pm = context.getPackageManager();
            List<ResolveInfo> resolveInfoList = pm.queryIntentServices(implicitIntent, 0);

            if (resolveInfoList == null || resolveInfoList.size() != 1) {
                return null;
            }
            ResolveInfo serviceInfo = resolveInfoList.get(0);
            ComponentName component = new ComponentName(serviceInfo.serviceInfo.packageName, serviceInfo.serviceInfo.name);
            Intent explicitIntent = new Intent(implicitIntent);
            explicitIntent.setComponent(component);
            return explicitIntent;
        }