0

我想构建一个应用程序,用户可以在其中制作带有手机当前位置标记的照片。所以在拍完照片后,用户可以通过点击“保存”按钮来保存照片。如果按钮被触摸,当前位置将由我自己的 LocationListener 类确定。侦听器类显示一个进度对话框并在找到位置后将其关闭。但是现在我想知道哪个可以将位置返回给调用活动,因为位置侦听器方法是回调方法。是否有“最佳实践”解决方案,或者有人知道吗?

位置监听器:

public class MyLocationListener implements LocationListener {

private ProgressDialog progressDialog;
private Context mContext;
private LocationManager locationManager;

public MyLocationListener(Context context, ProgressDialog dialog) {
    mContext = context;
    progressDialog = dialog;
}

public void startTracking() {
    locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    String provider = locationManager.getBestProvider(criteria, true);
    locationManager.requestLocationUpdates(provider, 10, 10, this);
    progressDialog.show();
}

private void finishTracking(Location location) {
    if(location != null) {
        locationManager.removeUpdates(this);
        progressDialog.hide();
        Log.i("TRACKING",location.toString());
    }
}

@Override
public void onLocationChanged(Location location) {
    finishTracking(location);
}

@Override
public void onProviderDisabled(String provider) { }

@Override
public void onProviderEnabled(String provider) { }

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

}

调用代码:

ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Determine position...");
new MyLocationListener(this, dialog).startTracking();
4

2 回答 2

1

为什么不将您自己的回调从活动传递到 MyLocationListener 并从 finishTracking 调用它的方法?

它是一种常用的委托模式。像这样的东西:

class MyLocationListener implements LocationListener {
    public interface MyListener {
        void onLocationReceiver( Location location );
    }

    private MyListener listener;

    public MyLocationListener(Context context, ProgressDialog dialog, MyListener listener) {
        mContext = context;
        progressDialog = dialog;
        this.listener = listener;
    }

    private void finishTracking(Location location) {
        if(location != null) {
            locationManager.removeUpdates(this);
            progressDialog.hide();
            Log.i("TRACKING",location.toString());
            listener.onLocationReceiver(location);
        }
    }
}

并致电:

new MyLocationListener(this, dialog, new MyLocationListener.MyListener() {
    public void onLocationReceived( Location location ) {
        text.setText(location.toString());
    }
}).startTracking();
于 2011-12-14T17:39:23.743 回答
1

你可以做另一件简单的事情——把你的类MyLocationListener放在你自己里面,然后在你Activity自己里面修改你的活动中的字段MyLocationListener

于 2011-12-14T18:41:28.263 回答