android公共方法,Android - 在ConnectivityManager中的公共方法setMobileDataEnabled在SDK中不可用...

此博客给出了一段Android代码,定义了一个名为setMobileData的公共方法,用于设置移动数据的开启或关闭。方法中通过反射机制调用系统服务的相关方法,处理了可能出现的类未找到、方法未找到等异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public void setMobileData(boolean toBeEnabled){

Object myObj= getSystemService(CONNECTIVITY_SERVICE);

ConnectivityManager cm = (ConnectivityManager) myObj;

Class c = null;

try {

c = Class.forName(cm.getClass().getName());

} catch (ClassNotFoundException e2) {

// TODO Auto-generated catch block

e2.printStackTrace();

}

Method m = null;

try {

m = c.getDeclaredMethod("getMobileDataEnabled");

} catch (SecurityException e2) {

// TODO Auto-generated catch block

e2.printStackTrace();

} catch (NoSuchMethodException e2) {

// TODO Auto-generated catch block

e2.printStackTrace();

}

Object mobileDataEnabled=null;

if (m!=null){

m.setAccessible(true);

Type res_of_m= m.getGenericReturnType();

Type[] pars_of_m= m.getGenericParameterTypes();

try {

mobileDataEnabled = (m.invoke(cm));

if (mobileDataEnabled!=null)

if (mobileDataEnabled.equals(!toBeEnabled)){

Method m2 = null;

try {

int index=0;

boolean method_found=false;

Method[] available_methods= c.getDeclaredMethods();

for (Method method : available_methods) {

// following line doesn't work

// method.getName()=="setMobileDataEnabled"

if (method.getName().contains("setMobileDataEnabled"))

{

method_found=true;

}

if (method_found==false)

index++;

}

// following line doesn't work

//m2 = c.getDeclaredMethod("setMobileDataEnabled");

m2 = (c.getDeclaredMethods())[index];

if (m2!=null){

m2.setAccessible(true);

m2.invoke(cm,toBeEnabled);

}

} catch (SecurityException e2) {

// TODO Auto-generated catch block

e2.printStackTrace();

} catch (InvocationTargetException e2) {

// TODO Auto-generated catch block

e2.printStackTrace();

}

}

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值