android wakelock not released after getActiveNetworkInfo

ε祈祈猫儿з 提交于 2019-12-11 03:39:42

问题


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.


回答1:


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();
}


来源:https://stackoverflow.com/questions/18128155/android-wakelock-not-released-after-getactivenetworkinfo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!