我尝试使用此代码来检查我的移动网络连接
final ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if( mobile.isAvailable() ){
Toast tst = Toast.makeText(this, "There is a network", Toast.LENGTH_SHORT);
tst.show();
}
else
{
Toast tst = Toast.makeText(this, "There is No network",Toast.LENGTH_SHORT);
tst.show();
}
该程序总是说"没有网络",尽管有一个网络。也许是因为我使用的是 2G SIM 卡,而这种方法适用于 3G。 有什么线索吗?
我想你想要的是电话状态,而不是数据状态。
尝试使用其他 API。
http://developer.android.com/reference/android/telephony/ServiceState.html
这可能会起作用。
http://developer.android.com/reference/android/telephony/TelephonyManager.html
可能也很方便。
尝试使用:
try{
if(mobile.getState() == NetworkInfo.State.CONNECTED){
//connected
}else{
//not connected
}
}catch (Exception e){
// if device doesnt have mobile
}
我用它来检查网络连接,希望它对:)有所帮助
public static boolean isOnline(Context applicationContext){
ConnectivityManager cm = (ConnectivityManager) applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
try{
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
catch(NullPointerException npe){
return false; //Airplane mode is on
}
}