Вы можете создать BroadcastReceiver , который обрабатывает изменения соединения Wi-Fi.
Точнее, вы захотите создать класс - скажем, NetWatcher:
public class NetWatcher extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//here, check that the network connection is available. If yes, start your service. If not, stop your service.
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
//start service
Intent intent = new Intent(context, MyService.class);
context.startService(intent);
}
else {
//stop service
Intent intent = new Intent(context, MyService.class);
context.stopService(intent);
}
}
}
}
(изменяя MyService
на название вашей услуги).
Кроме того, в вашем AndroidManifest
необходимо добавить следующие строки:
<receiver android:name="com.example.android.NetWatcher">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
(изменение com.example.android
на имя вашей посылки).