守则A运作良好。我在代码B中传递了一个类的参数,但是当我尝试使用EnableOrDisableCallMonitor(myContext,true,ReceiverSMS.class)调用函数时,代码B导致错误“它不适用于参数(Context, boolean, Class<ReceiverCall>)"
,为什么?
此外,使用EnableOrDisableCallMonitor(myContext, true, Class<ReceiverSMS.class>)
也会导致错误。
//----------------------------Code A-----------------------------------------
public void EnableOrDisableCallMonitor(Context myContext, boolean isEnable) {
ComponentName receiver = new ComponentName(myContext, ReceiverSMS.class);
PackageManager pm = myContext.getPackageManager();
int state = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
if (isEnable) {
state = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
}
pm.setComponentEnabledSetting(receiver, state,
PackageManager.DONT_KILL_APP);
}
//----------------------------Code B-----------------------------------------
public void EnableOrDisableCallMonitor(Context myContext, boolean isEnable, Class<BroadcastReceiver> myClass) {
ComponentName receiver = new ComponentName(myContext, myClass);
PackageManager pm = myContext.getPackageManager();
int state = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
if (isEnable) {
state = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
}
pm.setComponentEnabledSetting(receiver, state,
PackageManager.DONT_KILL_APP);
}
//----------------------------Code C-----------------------------------------
public static void EnableOrDisableCallMonitor(Context myContext, boolean isEnable) {
PublicParFun.EnableOrDisableBroadcastReceiver(myContext, isEnable,ReceiverCall.class);
}
public static void EnableOrDisableBroadcastReceiver(Context myContext, boolean isEnable, Class myClass) {
ComponentName receiver = new ComponentName(myContext, myClass);
PackageManager pm = myContext.getPackageManager();
int state = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
if (isEnable) {
state = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
}
pm.setComponentEnabledSetting(receiver, state,PackageManager.DONT_KILL_APP);
}
答案 0 :(得分:1)
您可以在param类型中使用泛型通配符。将Class<BroadcastReceiver> myClass
更改为Class<? extends BroadcastReceiver> myClass
。
答案 1 :(得分:0)
更改第二种方法的签名(代码B中的签名),如下所示:
public <T extends BroadcastReceiver> void EnableOrDisableCallMonitor(Context myContext, boolean isEnable, Class<T> myClass) {