简体   繁体   中英

Android: How to wake WIFI (or 3G) from AlarmManager?

I have this application that needs to pull data from a server every 30 minutes, after a lot of search I reached this solution: 1- using AlarmManager to notify the application each 30 minutes instead of keeping the service running in the background. 2- using wakelocks with PARTIAL_WAKE_LOCK

My only problem is that Wifi is off at sleep time.

How can I request that I need an internet connection when my alarm is triggered??

  1. alarm manager wakes your wakeful intent service via receiver
  2. wakeful intent service acquires a wifi lock
  3. service registers a receiver for connectivity and calls reconnect() , reassociate() and whatever is needed (this may be device specific)
  4. service waits on a latch
  5. the receiver wakes the service up when the wifi is connected

Skeleton code : https://stackoverflow.com/a/19968708/281545

Note for Android 6 (API level 23) and above. Since Google introduced Optimizing for Doze and App Standby, things are getting more complicated. Look here - https://developer.android.com/training/monitoring-device-state/doze-standby.html Now it is much harder to force access to the network at a specific time.

I had exactly the same problem some time ago. Unfortunately I did not succeed. I tried the following:

    WifiManager wman = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);

    try {
        wman.reconnect();
    } catch (Exception e) {
        e.printStackTrace();
        return false;

    }

Maybe you can play around with the WifiManager and find a way that I didn't find. Oh yea, don't forget to set the WIFI permissions in the manifest.

Cheers Lukas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM