I have a service that checks the server at regular intervals. I use AlarmManager and BroadcastReceiver to start the service. My problem is that after a certain duration, although Wi-Fi is still turned on, but for some reason my application cannot contact the server. I get an "Unreachable network" error message.
Please note that I have already acquired a partial tracking lock as well as wifilock.
Here is my code for BroadcastReceiver.
public class ServiceAlarmBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { WakeLock wakeLock = null; WifiLock wifiLock = null; try { PowerManager pm = (PowerManager) context .getSystemService(Context.POWER_SERVICE); // acquire a WakeLock to keep the CPU running wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock"); if(!wakeLock.isHeld()){ wakeLock.acquire(); } Log.i("ServiceAlarmBroadcastReceiver", "WakeLock acquired!"); WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock"); if(!wifiLock.isHeld()){ wifiLock.acquire(); } Log.i("ServiceAlarmBroadcastReceiver", "WifiLock acquired!"); context.startService(new Intent(context, ThePollerService.class)); } finally { // release the WakeLock to allow CPU to sleep if (wakeLock != null) { if (wakeLock.isHeld()) { wakeLock.release(); Log.i("ServiceAlarmBroadcastReceiver", "WakeLock released!"); } } // release the WifiLock if (wifiLock != null) { if (wifiLock.isHeld()) { wifiLock.release(); Log.i("ServiceAlarmBroadcastReceiver", "WiFi Lock released!"); } } } } }
android
javauser
source share