检测 android 设备是否已连接到互联网
Detect if android device is connected to the internet
这是我的 class,用于检查设备是否已连接到互联网。
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(
"http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000);
urlc.setReadTimeout(4000);
urlc.connect();
// networkcode2 = urlc.getResponseCode();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return (false);
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
然后我在这里调用它,但它似乎 return 不是真或假。没有错误,我的应用程序没有崩溃,只是没有打印出任何东西。有人知道为什么吗?
public void CheckInternet(){
// Boolean isInternetPresent;
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// isInternetPresent = cd.isConnectingToInternet();
if (cd.isConnectingToInternet()) {
// Internet Connection is Present
Log.i(TAG, "INTERNET IS GUUD");
} else {
// Internet connection is not present
// Ask user to connect to Internet
Log.i(TAG, "INTERNET IS NOOOO GUUD");
}
}
这不是检查互联网连接的正确方法。为此,您应该使用 Android 内置的 ConnectivityManager class。
使用起来非常简单,您只需执行以下操作即可检查网络连接:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
这还可以让您确定连接类型、是否受到监控等,以便您可以对正在执行的网络任务做出明智的决定。
在 Android 开发者网站的 this lesson 中有更多信息。
创建 class :
public class Utility {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
然后你从 activity 调用方法,它会 return true 或 false:
Utility.isNetworkAvailable(AnyActivity.this);
并且不要忘记向 android 清单添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
您必须在异步任务中执行此操作。我用 http://clients3.google.com/generate_204
检测连接。
import java.net.HttpURLConnection;
import java.net.URL;
...
private int inter = 0;
...
new checkconne().execute();
...
class checkconne extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... args) {
int kk=0;
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
kk= urlc.getResponseCode();
} catch (IOException e) {
Log.e("qweqwe", "Error checking internet connection", e);
}
inter=kk;
return null;
}
@Override
protected void onPostExecute(String file_url) {
if (inter == 204){
Toast.makeText(MainActivity3.this, "is connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity3.this, "No connection", Toast.LENGTH_LONG).show();
}
}
}
调用此函数:
public static boolean isNetworkAvailable()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 1500;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try
{
httpClient.execute(httpGet);
return true;
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return false;
}
这是我的 class,用于检查设备是否已连接到互联网。
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(
"http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000);
urlc.setReadTimeout(4000);
urlc.connect();
// networkcode2 = urlc.getResponseCode();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return (false);
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
然后我在这里调用它,但它似乎 return 不是真或假。没有错误,我的应用程序没有崩溃,只是没有打印出任何东西。有人知道为什么吗?
public void CheckInternet(){
// Boolean isInternetPresent;
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// isInternetPresent = cd.isConnectingToInternet();
if (cd.isConnectingToInternet()) {
// Internet Connection is Present
Log.i(TAG, "INTERNET IS GUUD");
} else {
// Internet connection is not present
// Ask user to connect to Internet
Log.i(TAG, "INTERNET IS NOOOO GUUD");
}
}
这不是检查互联网连接的正确方法。为此,您应该使用 Android 内置的 ConnectivityManager class。
使用起来非常简单,您只需执行以下操作即可检查网络连接:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
这还可以让您确定连接类型、是否受到监控等,以便您可以对正在执行的网络任务做出明智的决定。
在 Android 开发者网站的 this lesson 中有更多信息。
创建 class :
public class Utility {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
然后你从 activity 调用方法,它会 return true 或 false:
Utility.isNetworkAvailable(AnyActivity.this);
并且不要忘记向 android 清单添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
您必须在异步任务中执行此操作。我用 http://clients3.google.com/generate_204 检测连接。
import java.net.HttpURLConnection;
import java.net.URL;
...
private int inter = 0;
...
new checkconne().execute();
...
class checkconne extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... args) {
int kk=0;
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
kk= urlc.getResponseCode();
} catch (IOException e) {
Log.e("qweqwe", "Error checking internet connection", e);
}
inter=kk;
return null;
}
@Override
protected void onPostExecute(String file_url) {
if (inter == 204){
Toast.makeText(MainActivity3.this, "is connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity3.this, "No connection", Toast.LENGTH_LONG).show();
}
}
}
调用此函数:
public static boolean isNetworkAvailable()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 1500;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try
{
httpClient.execute(httpGet);
return true;
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return false;
}