سؤال

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.

هل كانت مفيدة؟

المحلول

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();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top