在Android6.0上,使用了以下代碼:
Intent intent = new Intent();
intent.setAction("xxx.server");
bindService(intent, mConn, Context.BIND_AUTO_CREATE);
提示了警告的異常:
Implicit intents with startService are not safe
查了一下源碼,原來在5.0上就必須強制使用顯示方式來啟動Service。
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(, ));
}
}
}
解決方法:
設定Action的同時,還需要設定啟動或綁定此Service類的packageName。
我們在此處使用系統的getPackageName函數來擷取包名即可。
Intent intent = new Intent();
intent.setAction("xxx.server");
intent.setPackage(context.getPackageName());
bindService(intent, mConn, Context.BIND_AUTO_CREATE);
改為以上代碼,就不會再出現錯誤提示了。