There are times when we need to use a privacy boot for our service, but when Android 5.0 comes out, one of the features is Service Intent must be explitict , which means that service services must be started in a display mode starting with Lollipop.
And the Android source code is written like this (source 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 is not safe:" + Service
- + "" + debug.getcallers (2, 3));
- }
- }
- }
Since the source code is written in this way, there are two ways to solve this:
1. set action and PackageName:
The reference code is as follows:
- Intent mintent = new Intent ();
- Mintent.setaction ("XXX.XXX.XXX");//The action of the service you define
- Mintent.setpackage (Getpackagename ());//Here you need to set the package name of your app
- Context.startservice (mintent);
This method is the solution that Google recommends using officially.
attached here for your reference: Http://developer.android.com/goo Tml#billing-service, interested can go to see.
2. Convert the implicit start to display start : --Reference address:http://stackoverflow.com/a/26318757/1446466
- 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-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 method is called as follows:
- Intent mintent = new Intent ();
- Mintent.setaction ("XXX.XXX.XXX");
- Intent eintent = new Intent (getexplicitintent (mcontext,mintent));
- Context.startservice (eintent);
Copy Code
How to troubleshoot alerts that appear in Android 5.0: Service Intent must be explicit