运行此源代码时发生异常:
public void setMobileDataState(boolean mobileDataEnabled) {
try {
TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataEnabledMethod) {
setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
}
} catch (Exception ex) {
Log.e(TAG, "Error setting mobile data state", ex);
}
}
例外:
java.lang.reflect.InvocationTargetException
答案 0 :(得分:0)
我在我的应用程序中使用这段代码。对我来说很好。希望对您有帮助。
要检查是否已启用数据,可以致电getMobileDataState()
要设置为启用或禁用,可以调用setMobileDataState(boolean)
。传递true启用移动数据,传递false禁用移动数据
/*Changing mobile data state - True to turn it ON*/
public void setMobileDataState(boolean mobileDataEnabled) {
try {
final ConnectivityManager conman = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
final Class<?> conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, mobileDataEnabled);
}
catch (Exception ex) {
Toasty.error(Main.this, "Exception: "+ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
/* getting mobile data current state - returns True if ON*/
public boolean getMobileDataState() {
try {
TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled");
if (null != getMobileDataEnabledMethod) {
boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);
return mobileDataEnabled;
}
}
catch (Exception ex) {
Toasty.error(Main.this, "Exception: "+ex.getMessage(), Toast.LENGTH_SHORT).show();
}
return false;
}
在您要打开移动数据
的地方调用此按钮setMobileDataState(true);
在您要关闭移动数据
的地方调用此按钮setMobileDataState(false);
更新:
您需要在 Manifest.xml
中添加MODIFY_PHONE_STATE
权限
if (ActivityCompat.checkSelfPermission(context,
android.Manifest.permission.MODIFY_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.MODIFY_PHONE_STATE}, 101);
} else {
setMobileDataEnabled(true);
}
然后在onRequestPermissionsResult
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 101) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setMobileDataEnabled(true);
} else {
Toasty.error(this, "Permission required to perform this action..", Toast.LENGTH_SHORT).show();
showAlert();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
ShowAlertDialog
private void showAlert(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(false);
dialog.setTitle("Permissions");
dialog.setMessage("Please allow this permission in Settings.");
dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.this, Settings.class));
finish();
}
});
dialog.show();
}
答案 1 :(得分:0)
您正在尝试使用反射获取和调用方法
Method setMobileDataEnabledMethod =
telephonyService.getClass().getDeclaredMethod("setDataEnabled",
boolean.class);
if (null != setMobileDataEnabledMethod) {
setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
}
java.lang.reflect.InvocationTargetException
是通用异常,如果您的代码在运行反射代码时遇到任何问题,则会引发该异常。在这里,这可能意味着两件事:
setDataEnabled
(参考:android docs)如果您也使用api <26运行应用程序设备,则不应依赖此方法。
MODIFY_PHONE_STATE
。您可以致电<invocationTargetExceptionObject>.getCause()
以获得真正的例外。