Android的激活锁定getActiveNetworkInfo后没有释放 [英] android wakelock not released after getActiveNetworkInfo

查看:715
本文介绍了Android的激活锁定getActiveNetworkInfo后没有释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要自动检查Internet连接的每隔x分钟和发送数据到服务器。但是,下面的(最小的)code给出Eclipse的一个警告,称释​​放()调用不是总能达到。

 电源管理PM =(电源管理)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock WL = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,);
wl.acquire();//检查活动网络
ConnectivityManager厘米=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
的NetworkInfo信息= cm.getActiveNetworkInfo();
//启动上传数据的服务
wl.release();

我不明白怎么wl.release()可能可能不能被称为所以,在Eclipse或什么错误我缺少什么?我绝对不希望我的应用程序引起唤醒锁。


解决方案

  

我不明白怎么wl.release()可能可能不能称之为


好吧,如果没有别的,你没有处理任何异常。如果获取)之间的事情()发布(提出了一个的RuntimeException ,你会崩溃和泄漏的激活锁定。使用此:

 电源管理PM =(电源管理)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock WL = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,);
wl.acquire();尝试{
  //检查活动网络
  ConnectivityManager厘米=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  的NetworkInfo信息= cm.getActiveNetworkInfo();
  //启动上传数据的服务
}
最后{
  wl.release();
}

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

这篇关于Android的激活锁定getActiveNetworkInfo后没有释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆