2

I want to automatically check for an internet connection every x minutes and send data to a server. However, the following (minimal) code gives a warning in Eclipse, saying that the release() call is not always reached.

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();

// check active network
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
// start a service that uploads data
wl.release();

I don't see how wl.release() could possibly not be called so is that a bug in Eclipse or what am I missing? I definitely don't want my app to cause a wake lock.

stofl
  • 47
  • 1
  • 7

1 Answers1

3

I don't see how wl.release() could possibly not be called

Well, if nothing else, you are not handling any exceptions. If something between acquire() and release() raises a RuntimeException, you will crash and leak the WakeLock. Use this:

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();

try {
  // check active network
  ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo info = cm.getActiveNetworkInfo();
  // start a service that uploads data
}
finally {
  wl.release();
}
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks, that solved it. Odd, nevertheless, no exception should be thrown by cm.getActiveNetworkInfo() – stofl Aug 08 '13 at 15:25
  • @user2633688: First, not all runtime exceptions are documented. Second, I'm presuming that your `// start a service that uploads data` comment implies the existence of additional code, and that could have runtime exceptions. – CommonsWare Aug 08 '13 at 15:31
  • I only put the comment to signal that I intend to do something useful with that bit of code but the warning shows up with exactly that code. Maybe it is an undocumented exception then. – stofl Aug 20 '13 at 11:30