我正在开发一个android
应用,我想知道检查互联网连接是否存在的最佳方法。我尝试过使用connectivity manager
和networkinfo
类,但无效,因为我的应用程序在没有网络的情况下继续崩溃,否则我会使用HttpConnection
方法。有人可以提出宝贵的建议。
答案 0 :(得分:3)
URL myurl = new URL(url);
URLConnection connection = myurl.openConnection();
connection.setConnectTimeout(20 * 1000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
} catch (Exception e1) {
throw e1;
}
if (responseCode == HttpURLConnection.HTTP_OK) {
//connection is OK and do what you want
//...
}
else
{
//connection is not OK
httpConnection.disconnect();
}
答案 1 :(得分:0)
这是一个古老的问题,但我正在做的是回答这里,以使其对其他人也有用。制作如下课程:
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public boolean isConnectedToInternet() {
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;
}
}
然后从method
调用类activity
来检查连接:
if(new ConnectionDetector(context).isConnectedToInternet()){
//Connected
//do what you want to do here
} else{
// Not connected
// show appropriate message
}
答案 2 :(得分:0)
Udacity卓越的高级Android应用开发课程使用getActiveNetworkInfo()
https://www.udacity.com/course/advanced-android-app-development--ud855
/**
* @param context Context used to get the ConnectivityManager
* @return true if network has connectivity (i.e. is reachable), else return false
*/
static public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return ((activeNetworkInfo != null)
&& activeNetworkInfo.isConnectedOrConnecting());
}
顺便说一句:Clairvoyant使用getAllNetworkInfo的答案很好,现在已在API级别23中弃用。
Android文档说使用getAllNetworks()和getNetworkInfo(android.net.Network)。
http://developer.android.com/reference/android/net/ConnectivityManager.html#getAllNetworkInfo()
我更新了Clairvoyant的方法,并使用它,直到我看到Udacity上面简单的isNetworkAvailable方法。
/**
* @return true if network has connectivity (i.e. is reachable), else return false
*/
boolean hasConnectivity(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
Network[] networks = connectivityManager.getAllNetworks();
if ((networks != null)
&& (networks.length > 0)) {
for (Network network : networks) {
NetworkInfo info = connectivityManager.getNetworkInfo(network);
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
答案 3 :(得分:0)
我建议你检查Exception以指定发生了什么错误,并且可以根据错误提示用户。
try {
URL url = new URL("https://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.connect();
success = connection.getResponseCode() == 200;
} catch (IOException e) {
//use the function here
onError(this,e);
}
public void onError(Activity activity,Throwable e){
try {
e.printStackTrace();
FirebaseCrash.report(e);
if (e instanceof HttpException) {
Response body = ((HttpException) e).response();
if (body.code() == 401) {
Toast.makeText(activity, "Not Authorized Access", Toast.LENGTH_SHORT).show();
} else if (body.code() == 404) {
Toast.makeText(activity, "Request not found", Toast.LENGTH_SHORT).show();
} else if (body.code() == 400) {
Toast.makeText(activity, "Bad Request", Toast.LENGTH_SHORT).show();
} else if (body.code() == 500) {
Toast.makeText(activity, "Internal Server Error", Toast.LENGTH_SHORT).show();
} else {
Log.e(Constants.TAG, "Error : Code HTTP = " + body.code());
}
}else if(e instanceof ConnectException || e instanceof SocketException){
Toast.makeText(activity, "No Internet Connection", Toast.LENGTH_SHORT).show();
} else if (e instanceof UnknownHostException) {
Toast.makeText(activity, "Make Sure Your Internet Connection is Properly Connected", Toast.LENGTH_SHORT).show();
} else if (e instanceof SSLHandshakeException || e instanceof SSLPeerUnverifiedException) {
Toast.makeText(activity, "Server Connection Problem..Please Try Again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Data Load Error", Toast.LENGTH_SHORT).show();
}
}
catch (Exception ex){
FirebaseCrash.report(e);
e.printStackTrace();
}
}