后台服务Android中的位置监听器

dmh*_*dmh 6 java implementation android locationlistener

哪种方法更好,直接实现LocationListener这样

public class BackgroundService extends Service implements LocationListener {}
Run Code Online (Sandbox Code Playgroud)

或者通常LocationListener在课堂内宣布?

LocationListener locationListener = new LocationListener() {};
Run Code Online (Sandbox Code Playgroud)

fon*_*onZ 9

在第二段代码中,您必须在调用locationListener接口方法之前调用该属性.

在第一段代码中,您可以直接访问接口方法.

因此,如果您知道每个方法调用花费cpu时间然后直接在类中实现它而不是将其作为属性将是有益的.

在这种情况下,您有1个引用BackgroundService,您可以使用它来访问LocationListener的方法

public class BackgroundService extends Service implements LocationListener {}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您有2个引用,一个引用到BackgroundService,另一个引用到locationListener

public class BackgroundService extends Service {
    private LocationListener locationListener = new LocationListener() {};
}
Run Code Online (Sandbox Code Playgroud)

但话说回来,如果你的程序没有关键时间限制,那真的不重要.最重要的是,您的代码是可读的.

我希望能回答你的问题.