ragrawal
ragrawal

Reputation: 13

How to trigger wifi state change using a background service in android?

I have an application where I want to upload some data as soon as the wifi is turned-on even if the application is not running. I think this can be done using android background services. Please help me uploading the data using background services when the app is not running or suggest me some other way to achieve this.

Thanks in advance!!

Upvotes: 1

Views: 1974

Answers (2)

Santosh
Santosh

Reputation: 419

To be more eloborate, implement following

  • Create a Started service (service which is started using startService() instead of bindService().
  • Implement onStartCommand() callback of this service. In this callback method check if there is any data to be uploaded (if this data is created by an activity, it is wise to use a DB table to queue the data to be uploaded and service picks up data from that DB). Check WIFI connectivity and if available upload the data.
  • Now you need to trigger this service whenever WIFI is available. Here you 2 ways to imeplemnt
  • Method 1 : register in your application manifest file to be notified of WIFI connectivity changes refer this link . registered broadcast receiver would be called when WIFI state changes. from the broadcast receiver start your service if WIFI is available
  • Method 2 : using AlarmManager launch you service periodically (say every 10 minutes). refer this link. This method would be beneficial if data to be uploaded gets generated once in a while.

Hope this is helpful. Let me know if you have any questions.

Upvotes: 1

ovluca
ovluca

Reputation: 291

You must use an unbounded service, who is completely independent for the activity (for more details check this ). After starting service monitor your internet connection using ConnectivityManager. Use this like example. Have Fun.

Upvotes: 0

Related Questions