【问题标题】:Android. Use service or application class for locationListener安卓。为 locationListener 使用服务或应用程序类
【发布时间】:2015-03-16 22:09:08
【问题描述】:

我的任务是确定用户位置。我可以在 Application 类中创建 LocationListener。或者我可以使用服务。

LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
  LocationListener locationListener=new LocationListener(){
public void onLocationChanged(    Location location){
  dive.setLongitude(location.getLongitude());
  dive.setLatitude(location.getLatitude());
  mapHelper.setMapPosition(dive.getLatitude(),dive.getLongitude());
}
public void onStatusChanged(    String provider,    int status,    Bundle extras){
}
public void onProviderEnabled(    String provider){
}
public void onProviderDisabled(    String provider){
}};
 locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,0,0,locationListener);
 locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,0,0,locationListener);

我需要用什么来完成这项任务?服务或应用程序类?服务的优点和缺点是什么?应用类的优缺点是什么?

【问题讨论】:

    标签: android service location


    【解决方案1】:

    您永远不会使用该应用程序。您可能会使用 Activity。使用Activity比较方便,但是不能坚持到下一个Activity。服务需要额外的样板文件并且不太容易访问数据,但它可以用于需要数据的多个活动。

    【讨论】:

    • “你永远不会使用这个应用程序” - 为什么?
    • 因为你不应该将它用于任何事情。这在Android中是一个死的想法。在某一时刻,人们用它来保持静态(单例等),但它对子类(你必须记住在清单中覆盖它)来说是一种痛苦,并且与在其他地方做这件事相比,它确实没有任何好处。现在它实际上只用于 1 或 2 个系统调用,例如几乎没有人覆盖的 onLowMemory。这有点像你的附录——它曾经有一个目的,但现在没有了。
    【解决方案2】:

    如果你的应用需要获取实时位置信息,两者都可以。

    MyApplication extends Application implements locationListener
    MyService extends Service implements locationListener
    

    因为应用程序的生命周期最长,所以你可以在服务中使用应用程序。你只需要关心如何将获取的数据传递给Activity(接口,广播...)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      相关资源
      最近更新 更多