我想检查移动数据是否开启/关闭,为此我使用以下代码:
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean) method.invoke(cm);
但是,此代码在某些设备上不起作用,并引发no such method exists
的异常。
我发现它在Android 4.1.x中不起作用。为什么要抛弃这个执行,我该如何解决?
答案 0 :(得分:0)
connection.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
//return (connectivity != null && connectivity.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
if (connectivity.getActiveNetworkInfo() != null && connectivity.getActiveNetworkInfo().isAvailable() && connectivity.getActiveNetworkInfo().isConnected())
{
return true;
} else {
//System.out.println("Internet Connection Not Present");
return false;
}
}
}
internetchecking.java
Boolean isInternetPresent = false;
ConnectionDetector cd;
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
dotask();
}
else
{
display("No Internet Connection...");
}
在模拟器中使用F8
键进行Internet连接