在不使用弃用方法的情况下检查 Android Nougat 上的互联网连接

Checking internet conection on Android Nougat without deprecated methods

根据文档,我无法使用

制作自己的 ConnectionChangeReceiver
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

因为 android.net.conn.CONNECTIVITY_CHANGE 已弃用。

并且使用 JobExecutor 是个坏主意,因为它至少每 15 分钟检查一次互联网连接...无用的工具。

那么,在 OS Android 的所有版本上,如何在不使用弃用方法的情况下在后台(服务或某些接收器)检查互联网连接?

如果您明确使用 BroadcastReceiver 并请求通知,您的应用仍然可以在 Nougat 上接收连接更改的通知。

引用文档:

Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare their broadcast receiver in the manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

要使其在不同的 android 版本中工作,您可以像我们通常那样在清单中声明权限,此外,在您的 activity 中使用以下代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}