我正在开发一个将持续保持连接到互联网的 Android 应用程序。如果 Internet 中断,它应该给用户一个适当的消息。
有没有类似 Internet Listener 的东西?或者如何实现这个事件,只要互联网连接不可用,它就会发出警报。
最佳答案
为此创建一个广播接收器并将其注册到 list 文件中。
首先新建一个类NetworkStateReceiver
并扩展BroadcastReceiver。
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("app","Network connectivity change");
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
Log.i("app","Network "+ni.getTypeName()+" connected");
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
Log.d("app","There's no network connectivity");
}
}
}
将此代码放入您的 AndroidManifest.xml 中的“应用程序”元素下:
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
并添加此权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
编辑
此代码仅检测连接更改,但无法判断其连接的网络是否可以访问互联网。使用此方法检查 -
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
关于java - 互联网监听器 Android 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157130/