2

我想每隔 x 分钟自动检查一次互联网连接并将数据发送到服务器。然而,下面的(最小的)代码在 Eclipse 中给出了一个警告,指出并不总是能到达 release() 调用。

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

我看不出 wl.release() 怎么可能不能被调用所以是 Eclipse 中的错误还是我错过了什么?我绝对不希望我的应用程序导致唤醒锁定。

4

1 回答 1

3

我看不出如何可能无法调用 wl.release()

好吧,如果没有别的,你没有处理任何异常。如果介于acquire()和之间的东西release()引发了 a RuntimeException,您将崩溃并泄漏WakeLock. 用这个:

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();
}
于 2013-08-08T14:27:31.973 回答