1.å¦ä½è§£å³android 5.0ä¸åºç°çè¦åservice intent must be expl
å¦ä½è§£å³android 5.0ä¸åºç°çè¦åservice intent must be expl
æäºæ¶åæ们使ç¨Serviceçæ¶éè¦éç¨éç§å¯å¨çæ¹å¼ï¼ä½æ¯Android 5.0ä¸åºæ¥åï¼å ¶ä¸æ个ç¹æ§å°±æ¯Service Intent must be explitictï¼ä¹å°±æ¯è¯´ä»Lollipopå¼å§ï¼serviceæå¡å¿ é¡»éç¨æ¾ç¤ºæ¹å¼å¯å¨ã
èandroidæºç æ¯è¿æ ·åçï¼æºç ä½ç½®ï¼sdk/sources/android-/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));
}
}
}
å¤å¶ä»£ç
æ¢ç¶ï¼æºç éæ¯è¿æ ·åçï¼é£ä¹è¿éæ两ç§è§£å³æ¹æ³ï¼
1ã设置ActionåpackageNameï¼
åè代ç å¦ä¸ï¼
Intent mIntent = new Intent();
mIntent.setAction("XXX.XXX.XXX");//ä½ å®ä¹çserviceçaction
mIntent.setPackage(getPackageName());//è¿éä½ éè¦è®¾ç½®ä½ åºç¨çå å
context.startService(mIntent);
å¤å¶ä»£ç
æ¤æ¹å¼æ¯googleå®æ¹æ¨è使ç¨ç解å³æ¹æ³ã
2ãå°éå¼å¯å¨è½¬æ¢ä¸ºæ¾ç¤ºå¯å¨ï¼
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;
}
å¤å¶ä»£ç
è°ç¨æ¹å¼å¦ä¸ï¼
Intent mIntent = new Intent();
mIntent.setAction("XXX.XXX.XXX");
Intent eintent = new Intent(getExplicitIntent(mContext,mIntent));
context.startService(eintent);