《完美解決系列》Android5.0以上 Implicit intents with startService are not safe

在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(2, 3));
            }
        }
    }

解決方法:

設置Action的同時,還需要設置啓動或綁定此Service類的packageName。
我們在此處使用系統的getPackageName函數來獲取包名即可。

Intent intent = new Intent();
       intent.setAction("xxx.server");
       intent.setPackage(context.getPackageName());
       bindService(intent, mConn, Context.BIND_AUTO_CREATE);

改爲以上代碼,就不會再出現錯誤提示了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章