2012-06-19 221 views
1

我想实现一个LocationListener。经过一些教程,发现这个:在onCreate中添加事件侦听器

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

// Acquire a reference to the system Location Manager 
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

    // Define a listener that responds to location updates 
    LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      // Called when a new location is found by the network location provider. 
      makeUseOfNewLocation(location); 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras) {} 

     public void onProviderEnabled(String provider) {} 

     public void onProviderDisabled(String provider) {} 
     }; 

    // Register the listener with the Location Manager to receive location updates 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); 


} 

但事件侦听器在onCreate方法真的加入?看起来很凌乱。将它们添加到单独的类并在onCreate中创建类的实例更常见吗?我想知道这里的最佳做法。

谢谢!

回答

1

你的做法几乎是正确的,但有步骤,有没有“好”的理由来实施分离类LocationListener但是你要实现你的LocationListeneronCreate()方法和

requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); 

通常被称为宁可在onResume()方法和removeUpdates()onDestroy()方法。

我建议你检查WeatherPlus申请CommonsWare,我想所有的都会更清晰。

+0

我猜的愚蠢问题,但如果我调用'onCreate'之外的'requestLocationUpdates',我将如何得到最后一个参数'locationListener'?在类中创建它作为一个私有变量,并在'onCreate'中初始化它? – Johan

+0

这很简单,只需创建'LocationListener onLocationChange = new LocationListener(){};'通常在'onCreate()'之外,就像创建普通方法一样。然后只需调用'mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t 10000,10000。0f,onLocationChange);' – Sajmon

+1

感谢您的阐述! – Johan

1

这真的取决于你想要你的应用程序待办事项。 所以首先我同意在onCreate()中看起来很凌乱。 假设你写了一个init()方法并从你的onCreate()中调用它,但没有什么变化。 你唯一要注意的Activity LifeCycle。 如果您的注册接收位置更新比您的活动更新,那么当您没有屏幕焦点时可能会更新。 另一种选择是将寄存器移动到onResume(),但是您需要在onPause()中取消注册。如果你的应用当前在屏幕上,这将只会得到更新。

+0

好的,“onResume”的时间和频率是多少? – Johan

+0

@Johan:回答你的问题WRT何时/多久调用一次'onResume()',请参阅“Activity”工作原理的解释,特别是“Activity Lifecycle”的图解。当我开始使用Android时,我将这个图表打印出来并粘贴在我的开发机器上... http://developer.android.com/reference/android/app/Activity.html – Squonk

+0

@Squonk谢谢你。基本上,经验法则是,只要你的应用程序被视觉阻挡(例如通过对话活动或主页按钮),onPause就会被调用,一旦它重新获得完整的焦点,将比OnResume被调用。 –

相关问题