哪种方法更好,直接像这样实现LocationListener
public class BackgroundService extends Service implements LocationListener {}
或者通常在类中声明 LocationListener
?
LocationListener locationListener = new LocationListener() {};
最佳答案
在第二段代码中,您必须在调用接口(interface)方法之前调用属性 locationListener
。
在第一段代码中,您可以直接访问接口(interface)方法。
因此,如果您知道每个方法调用都需要花费 CPU 时间,那么直接在类中实现它而不是将其作为属性来实现将是有益的。
在这种情况下,您有 1 个对 BackgroundService
的引用,您可以通过它访问 LocationListener 的方法
public class BackgroundService extends Service implements LocationListener {}
在这种情况下,您有 2 个引用,一个指向 BackgroundService,另一个指向 locationListener
public class BackgroundService extends Service {
private LocationListener locationListener = new LocationListener() {};
}
但话又说回来,如果您的程序没有关键的时间限制,那也无所谓。 最重要的是您的代码可读。
我希望这能回答您的问题。
关于java - 后台服务 Android 中的位置监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12227446/