我已经开发了一个简单的天气应用程序,但是我的weatheractivity中有太多的代码,一个类有两个职责(处理天气json和使用googleapclient检索位置信息)。我试图从weatheractivity类中获取处理位置的代码,但是当我试图在oncreate方法中获取任何位置时,它通常会导致null,这可能是因为没有足够的时间进行更新。有什么方法可以在活动之外获取用户的位置吗?或者,如果你有其他的建议,可能有助于在这种情况下?

最佳答案

我一直在寻找一个解决方案,有一个对象来处理当前位置,但我没有找到任何东西。
所以我是这样做的,但有点棘手。
希望对你有帮助。

import android.Manifest;
import android.app.Activity;

import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

/**
 * This class uses GoogleApiClient to track location changes.
 * In order to connect the GoogleApiClient correctly, this class must be instanciated in onCreate callback.
 */
public class Locator implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private static final String TAG = "Locator";
    private Activity activity;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;
    private static final long UPDATE_INTERVAL = 60 * 1000;
    private static final long FASTEST_UPDATE_INTERVAL = 10 * 1000;
    private static final int LOCATION_REQUEST = 1;
    private static boolean locationPermissionRequested = false;
    private static boolean locationPermissionGranted = false;
    private Location location;

    /**
     * Default constructor. Ex. Locator locator = new Locator(getActivity());
     *
     * @param activity The activity to instanciate from.
     */
    public Locator(Activity activity) {
        this.activity = activity;
        if (activity != null) {
            googleApiClient = new GoogleApiClient.Builder(activity)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            locationRequest = new LocationRequest();
            locationRequest.setInterval(UPDATE_INTERVAL);
            locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL);
            locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            googleApiClient.connect();
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        requestLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }

    /**
     * Requests the current location to the GoogleApiClient.
     * NB: If device os is Marshmallow or higher, il will also ask permission to acces location services.
     */
    private void requestLocation() {
        if (googleApiClient.isConnected()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                locationPermissionGranted = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
                if (!locationPermissionGranted) {
                    if (!locationPermissionRequested) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST);
                        locationPermissionRequested = true;
                        requestLocation();
                    }
                }
            } else {
                locationPermissionGranted = true;
            }
            if (locationPermissionGranted) {
                LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
            } else {
            }
        }
    }

    /**
     * Requests the current location et gets.
     *
     * @return The location.
     */
    public Location getLocation() {
        requestLocation();
        return location;
    }

    /**
     * Stops updating the location. (save battery power).
     */
    public void removeUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }
}

关于android - Activity 之外的googleApiClient,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31361499/

10-13 05:08