LoginSignup
8
10

More than 5 years have passed since last update.

Android N 以降のネットワーク接続状態の監視方法

Last updated at Posted at 2017-06-01

単にネットワークの接続状態を監視したかったのですが、Android 7 Nougat以降では方法が異なり十数分ほど無駄にしたのでメモしておきます。Nougatでの変更点としてまとめられている記事はいくつかありますがこの点が他の情報に埋もれているように思いました。

<manifest ...>

    <application ...>

        <receiver android:name=".NetworkWatcher">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Nougatをターゲットにしているプロジェクトでは、上記のようにAndroidManifest.xmlに記述すると次のようなWarningが出ます。

Declaring a broadcastreceiver for android.net.conn.CONNECTIVITY_CHANGE is deprecated for apps targeting N and higher. In general, apps should not rely on this broadcast and instead use JobScheduler or GCMNetworkManager.

Nougat以降ではAndroidManifest.xmlandroid.net.conn.CONNECTIVITY_CHANGEを設定しても無視されます。

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

しかし、公式ページに書かれているようにコードで指定するとOKということです。
上記AndroidManifest.xmlの記述とともにApplicationサブクラスにNougat以降を指定した処理を記述することで動作を確認できました。

MainApplication.kt
class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()

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

    }
}
// MainApplicationはAndroidManifest.xmlで登録済み
// <manifest ...>
//     <application android:name=".MainApplication">
//         ...
//     </application>
// </manifest>
NetworkWatcher.kt
class NetworkWatcher : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null || context == null) return
        val action = intent.action
        if (action != ConnectivityManager.CONNECTIVITY_ACTION) return

        // do something

    }

}

Nougatより前のバージョンではアプリを終了してもBroadcastReceiverが実行されますが、Nougat以降では実行されません。バッテリー節約のためこのような仕様変更を行ったそうです。

8
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
10