How to solve the warning in Android 5.0 and above: Service Intent must be expli, androidexpli
Sometimes we need to use the privacy startup method when using the Service, but after Android 5.0 is released, one feature is Service Intent must be explitict, that is, starting with Lollipop, the service must be started in the display mode.
The android source code is written in this way (Source Code Location: sdk/sources/android-21/android/app/ContextImpl. java ):
private void validateServiceIntent(Intent service) { if (service.getComponent() == null && service.getPackage() == null) { if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) { IllegalArgumentException ex = new IllegalArgumentException( "Service Intent must be explicit: " + service); throw ex; } else { Log.w(TAG, "Implicit intents with startService are not safe: " + service + " " + Debug.getCallers(2, 3)); } } }
Since the source code is written in this way, there are two solutions:
1. Set Action and packageName:
The reference code is as follows:
Intent mIntent = new Intent (); mIntent. setAction ("XXX. XXX. XXX "); // The actionmIntent of the service you define. setPackage (getPackageName (); // you need to set the package name context. startService (mIntent );
This method is recommended by google.
2. Convert implicit startup to display startup:
public static Intent getExplicitIntent(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; }
The above code solves the error.
The call method is as follows:
Intent mIntent = new Intent();mIntent.setAction("XXX.XXX.XXX");Intent eintent = new Intent(getExplicitIntent(mContext,mIntent));context.startService(eintent);