帮助我...... 我使用此代码检查Internet连接,但在每个状态中它都返回“false”
boolean check;
ConnectivityManager connectivityManager
=(ConnectivityManager)this.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
check=(activeNetworkInfo != null && activeNetworkInfo.isConnected());
答案 0 :(得分:1)
试试这段代码
此代码检查所有类型的网络连接,如wifi,网络数据等... 当你想检查互联网连接时,只需要调用此方法,如
if (isConnectingToInternet(this)) {
//do internet available here
}
else{
//internet not available here
}
public static boolean isConnectingToInternet(Context _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Log.d("Network",
"NETWORKnAME: " + info[i].getTypeName());
return true;
}
}
return false;
}
答案 1 :(得分:0)
protected boolean isNetworkConnected() {
Context ctx = this;
ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null)
return info.isAvailable();
else
return false;
}
还在清单中设置了以下权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 2 :(得分:0)
试试这个,
创建一个ConnectionDetector类。
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible Internet providers
* **/
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
当你想在任何活动/片段/其他人检查互联网时使用此代码..
ConnectionDetector conn = new ConnectionDetector(ActivityName.this);
if(conn.isConnectingToInternet()){
// Do your Network Operations
}else{
// No Network , show a dialog , etc
}
的Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />