互联网监听器安卓示例

我正在开发一个Android应用程序,该应用程序将持续保持与互联网的连接。如果互联网是陶氏,它应该给用户一个适当的信息。

有没有像互联网监听器这样的东西?或者如何实现此事件,即每当互联网连接不可用时,它都应该发出警报。


答案 1

为此创建一个广播接收器,并将其注册到清单文件中。

首先创建一个新类并扩展 BroadcastReceiver。NetworkStateReceiver

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“application”元素下:

<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;
}

答案 2

上面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 消息;否则,它仅在丢失/重新建立连接时出现。


推荐