Use a BroadcastReceiver that gets notified, when the connection state changes. It is very important that you register it in your manifeset!
Add a class, similar to this to your project:
public class NetworkChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Network state changed!
// Check if the user connected using ConnectivityManager.getActiveNetworkInfo()
}
}
Add it to your manifest file, so the systems knows it should notify you:
<manifest>
...
<application>
...
<receiver
android:name=".NetworkChangedReceiver"
android:process=":remote">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
...
</application>
</manifest>
Edit:
From the docs:
Apps targeting Android 7.0 (API level 24) do not receive CONNECTIVITY_ACTION broadcasts if they register to receive them in their manifest, and processes that depend on this broadcast will not start. This could pose a problem for apps that want to listen for network changes or perform bulk network activities when the device connects to an unmetered network. Several solutions to get around this restriction already exist in the Android framework, but choosing the right one depends on what you want your app to accomplish.
Note: A BroadcastReceiver registered with Context.registerReceiver()
continues to receive these broadcasts while the app is running.
I didn't knew about this, so thanks to @Paul Nie for letting me know :D
I can't really help further at this point. But this seems like a good point to start some research about this topic: https://developer.android.com/topic/performance/background-optimization.html#connectivity-action