Как вернуть данные в Android LocationListener - PullRequest
0 голосов
/ 14 декабря 2011

Я хочу создать приложение, в котором пользователи могут делать фотографии, помеченные текущим местоположением телефона.Поэтому, сделав фото, пользователь может сохранить изображение, нажав на кнопку «Сохранить».Если нажать кнопку, текущее местоположение будет определено с помощью моего собственного класса LocationListener.Класс Listener показывает Progressdialog и отклоняет его после того, как местоположение найдено.Но теперь я хочу знать, какой я могу вернуть местоположение обратно в вызывающую активность, потому что методы слушателя Location являются методами обратного вызова.Есть ли для этого решение «передового опыта», или у кого-нибудь есть подсказка?

Location Listener:

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();

Ответы [ 2 ]

1 голос
/ 14 декабря 2011

Вы можете сделать еще одну простую вещь - поместить свой класс MyLocationListener в свой Activity и изменить поле в своей деятельности внутри самого MyLocationListener.

1 голос
/ 14 декабря 2011

Почему бы не передать свой собственный обратный вызов из действия в 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();
...