在整个应用程序中管理互联网连接
Manage Internet connectivity in the entire app
我知道如何检查设备中的互联网连接的代码,但我想知道如何管理互联网连接检查,因为我的应用程序包含许多异步任务、服务等,这意味着在何处显示互联网错误对话框。
您可以注册 ConnectivityManager.CONNECTIVITY_ACTION 广播操作以侦听设备上的连接变化。
ConnectivityManager.CONNECTIVITY_ACTION
http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION
创建一个实用程序 class,其中添加一个方法来检查 Internet 可用性,如下所示:
/**
* method to check the connection
*
* @return true if network connection is available
*/
public static boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) MainApplication.getsApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null)
return false;
State network = info.getState();
return (network == State.CONNECTED || network == State.CONNECTING);
}
/**
* method to toast message if internet is not connected
*
* @return true if internet is connected
*/
public static boolean isInternetConnected() {
if (isNetworkAvailable()) {
return true;
} else {
// TODO Here write the code to show dialog with Internet Not Available message
......
return false;
}
}
现在您可以在执行 AsyncTask 之前使用它,只需添加此检查
if (Utility.isInternetConnected()) {
// TODO start your asyntask here
}
我知道如何检查设备中的互联网连接的代码,但我想知道如何管理互联网连接检查,因为我的应用程序包含许多异步任务、服务等,这意味着在何处显示互联网错误对话框。
您可以注册 ConnectivityManager.CONNECTIVITY_ACTION 广播操作以侦听设备上的连接变化。
ConnectivityManager.CONNECTIVITY_ACTION http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION
创建一个实用程序 class,其中添加一个方法来检查 Internet 可用性,如下所示:
/**
* method to check the connection
*
* @return true if network connection is available
*/
public static boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) MainApplication.getsApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null)
return false;
State network = info.getState();
return (network == State.CONNECTED || network == State.CONNECTING);
}
/**
* method to toast message if internet is not connected
*
* @return true if internet is connected
*/
public static boolean isInternetConnected() {
if (isNetworkAvailable()) {
return true;
} else {
// TODO Here write the code to show dialog with Internet Not Available message
......
return false;
}
}
现在您可以在执行 AsyncTask 之前使用它,只需添加此检查
if (Utility.isInternetConnected()) {
// TODO start your asyntask here
}