【问题标题】:Location Listener in Background Service Android后台服务Android中的位置侦听器
【发布时间】:2012-08-26 23:39:42
【问题描述】:
哪种方法更好,像这样直接实现LocationListener
public class BackgroundService extends Service implements LocationListener {}
或者通常在类中声明LocationListener?
LocationListener locationListener = new LocationListener() {};
【问题讨论】:
标签:
java
android
implementation
locationlistener
【解决方案1】:
在第二段代码中,你必须在调用接口的方法之前调用属性locationListener。
在第一段代码中,您可以直接访问接口方法。
因此,如果您知道每个方法调用都会花费 cpu 时间,那么直接在类中实现它而不是将其作为属性将是有益的。
在这种情况下,您有 1 个对 BackgroundService 的引用,您可以使用它访问 LocationListener 的方法
public class BackgroundService extends Service implements LocationListener {}
在这种情况下,您有 2 个引用,一个指向 BackgroundService,另一个指向 locationListener
public class BackgroundService extends Service {
private LocationListener locationListener = new LocationListener() {};
}
但是话又说回来,如果您的程序没有关键的时间限制,那真的没关系。
最重要的是你的代码是可读的。
我希望这能回答你的问题。