我正在开发一款能够持续保持与互联网连接的Android应用。如果Internet是dow,它应该向用户发出适当的消息。
有没有像Internet Listener这样的东西?或者如何实现此事件,每当Internet连接不可用时,它应该提供警报。
答案 0 :(得分:49)
为此创建一个广播接收器并将其注册到清单文件中。
首先创建一个新类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");
}
}
}
将此代码放在Android应用程序元素下的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"/>
修改强>
此代码仅检测连接更改,但无法判断其连接的网络是否具有Internet访问权限。使用此方法检查 -
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;
}
答案 1 :(得分:1)
上面的Chirag Raval的代码肯定有用。问题是即使应用程序没有在前台运行,也会调用侦听器。
恕我直言,更好的方法是在所有应用程序活动的onResume()
/ onPause()
方法中注册/取消注册接收器。这段代码应该这样做:
private final NetworkStateReceiver stateReceiver = new NetworkStateReceiver();
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(stateReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(stateReceiver);
}
显然,请从AndroidManifest.xml
文件中删除注册。
使用此解决方案,在应用程序的活动之间切换时也会调用接收器(假设您正在关闭它们)。在这种情况下,使用静态标志(在所有活动之间共享),如下例所示(称为online
):
public class NetworkStateReceiver extends BroadcastReceiver {
private static boolean online = true; // we expect the app being online when starting
public static final String TAG = NetworkStateReceiver.class.getSimpleName();
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"Network connectivity change");
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if (ni == null || ni.getState() != NetworkInfo.State.CONNECTED) {
Log.d(TAG,"There's no network connectivity");
if (online) // don't show the message if already offline
Toast.makeText(context, R.string.noInternet, Toast.LENGTH_SHORT).show();
online = false;
} else {
Log.d(TAG,"Network "+ni.getTypeName()+" connected");
if (!online) // don't show the message if already online
Toast.makeText(context, R.string.backOnline, Toast.LENGTH_SHORT).show();
online = true;
}
}
}
如果在离线时启动应用,则会显示Toast消息;否则只有在丢失/重新建立连接时才会出现。