Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyncAdapter only on WIFI

Tags:

android

sync

I want to run my SyncAdapter only on Wifi. In the beginning of onPerformSync, I can check if wifi is present. If it's not, I want to postpone it until there is WIFI available.

I know of syncresult.delayUntil but that means that the sync adapter is uselessly called every x minutes although the wifi could be disabled for example for the entire day. Also, from what I've read delayUntil does not apply if you use triggerSync directly.

What is the best approach here? Apps like Evernote seem to have this option of syncing only on WIFI.

like image 668
Catalin Morosan Avatar asked Nov 04 '22 04:11

Catalin Morosan


1 Answers

Don't set your SyncAdapter to run periodically.

Instead add a BroadcastReceiver to your app with this filter:

<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>

and in the BroadcastReceiver code, check if WiFi was turned on, and if so, call:

ContentResolver.requestSync(<Your account, <Your authority>, extras);

To request Android to run your SyncAdapter.

like image 71
marmor Avatar answered Nov 08 '22 10:11

marmor