尝试在我的应用程序中检查 Internet 连接。我的清单有一个代码:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
还有一个句柄类:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction() != null && intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE"));
{
Log.d("myLogs", "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("myLogs", "Network " + ni.getTypeName() + " connected");
}
}
if (intent.getExtras().getBoolean(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.d("myLogs", "There's no network connectivity");
}
}
}
}
在我的 Logcat 中,我得到一张像这样的图片:
04-11 23:24:48.021: D/myLogs(10261): Network connectivity change
04-11 23:24:48.021: I/myLogs(10261): Network WIFI connected
04-11 23:24:48.202: D/myLogs(10261): Network connectivity change
04-11 23:24:48.202: I/myLogs(10261): Network WIFI connected
因此,接收者呼叫了两次。为什么?所有类型的连接都存在一些问题。