我有点迷失:在我的主要活动中,我注册一个LocationManager并将其连接到LocationListener以使用myLocation.getLatitude()等.
现在我需要使用另一个类的Location-方法.
我无法使用其他类中的那些对象,因为我无法实现主要活动.我不能使用getter来传递L.Manager或L.Listener,因为那些是非静态的.
因此,一般来说,我如何访问我在主要活动中创建的对象?关于如何更好地组织这个的任何提示?主活动类中的LocationListener类通常是一件蠢事吗?
public class URNavActivity extends Activity
{
public LocationManager mlocManager;
public LocationListener mlocListener;
...
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
actVar=this;
initGraph();
setMap();
gpsEnable();
initMyLocation();
getItems();
initOverlay();
}
public void gpsEnable ()
{
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
myMap.getController().setCenter(new GeoPoint(lati, longi));
}
Run Code Online (Sandbox Code Playgroud)
首先,您的LocationListener不应该是活动的一部分.活动具有明确定义的生命周期,可以根据需要由Android框架生成并销毁.因此,您的Activity的实例变量需要在您的activity的onResume()方法中重新初始化,使它们完全不适合长期存储.
所以.首先创建一个粘性服务来管理位置更新的启动和停止.粘性意味着服务实例在调用之间挂起,因此您可以可靠地使用实例变量并知道它们将保留其值,直到服务终止.此服务还应实现LocationListener接口,现在它可以在调用onLocationChanged时存储通知给它的Location:
public class LocationService extends Service implements LocationListener {
private LocationManager locationManager;
private Location location;
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
Logging.i(CLAZZ, "onHandleIntent", "invoked");
if (intent.getAction().equals("startListening")) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else {
if (intent.getAction().equals("stopListening")) {
locationManager.removeUpdates(this);
locationManager = null;
}
}
return START_STICKY;
}
@Override
public IBinder onBind(final Intent intent) {
return null;
}
public void onLocationChanged(final Location location) {
this.location = location;
// TODO this is where you'd do something like context.sendBroadcast()
}
public void onProviderDisabled(final String provider) {
}
public void onProviderEnabled(final String provider) {
}
public void onStatusChanged(final String arg0, final int arg1, final Bundle arg2) {
}
}
Run Code Online (Sandbox Code Playgroud)
现在您有了一项服务,您可以根据需要启动和停止位置更新.即使您的应用程序不在前台,这也允许您继续接收和处理位置更改,如果这是您想要的.
您现在有两个关于如何使该位置信息可用的选择:使用context.sendBroadcast()将新位置传播到(例如)一个活动,或使用绑定服务方法允许其他类调用公开的API并获取那个地点.有关创建绑定服务的更多详细信息,请参阅http://developer.android.com/guide/topics/fundamentals/bound-services.html.
请注意,为了清楚起见,还有很多其他方面来监听我未包含在内的位置更新.