我想以编程方式启用移动网络/数据网络。为此,我正在使用下面给出的代码,但它不起作用。我没有收到任何错误。Toast 弹出并说“移动网络已启用”但实际上并未启用。请任何帮助。
这是完整的代码。
public class MainActivity extends Activity {
ConnectivityManager connectivity;
NetworkInfo wifiNetworkInfo, mobileNetworkInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
wifiNetworkInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobileNetworkInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifiNetworkInfo.isConnected())
Toast.makeText(this, "WiFi is connected", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "WiFi is not connected", Toast.LENGTH_LONG).show();
if(mobileNetworkInfo.isConnected())
Toast.makeText(this, "MObileNetwork is connected", Toast.LENGTH_LONG).show();
else{
boolean enabled = false;
try {
setMobileDataEnabled(getBaseContext(), enabled);
Toast.makeText(this, "MObileNetwork has been Enabled", Toast.LENGTH_LONG).show();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
private void setMobileDataEnabled(Context context, boolean enabled) throws Throwable {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class<?> conmanClass = Class.forName(conman.getClass().getName());
final java.lang.reflect.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, enabled);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}