Pat
Pat

Reputation: 167

Restart Service as soon as wifi is available

I have got a little service that is going to download a file every day at 6am. This works totally fine (I solved this with the AlarmManager), but if there is no internet connection at 6am I would like to restart this service as soon as internet connection is available. The service is a started one and never bound.

I already invoke a method called "onNoInternetConnection" within my service whenever there is no internet connection available, so this is already implemented correctly and works fine, but as I am new to android I am a little lost in the issue about how to restart my service as soon as internet connection is available.

I thought about implementing a broadcast receiver listening for a connectivity change, but I run into different problems there like when exactly to register or unregister the receiver and how to avoid that the receiver will not start the service before 6am (this is important)...

Is this the right approach to achieve this and if yes, when exactly and how can I register my broadcast receiver? If not: Do you have other approaches to solve this issue?

Thanks in advance ! Please let me know if you need more information.

Upvotes: 0

Views: 748

Answers (1)

eleven
eleven

Reputation: 6847

You don't need to register the receiver dynamically. Just do it in your Manifest

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

Then check internet connection in onReceive method:

public class ConnectivityChangeReceiver extends WakefulBroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        //if connected to the internet then start service if not the do nothing
    }
}

Upvotes: 1

Related Questions