如何及时找到设备位置

时间:2016-07-08 20:31:36

标签: java android google-play-services location-services

我正在创建一个应用,需要找到本地设备的位置,并将其与其他设备的位置进行比较。我正在尝试使用Google Play服务位置apis来查找设备的位置,但似乎只需要很长时间才能连接。我还没看到它连接起来。它要么非常慢,要么没有正确设置。连接时这些apis通常很快吗?

这就是我所拥有的:

public class LocationHandler implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
    private Activity currActivity = null;
    private GoogleApiClient mGoogleApiClient = null;

    public LocationHandler(Activity act)
    {
        currActivity = act;
    }

    public void Setup()
    {
        if (mGoogleApiClient == null)
        {
            mGoogleApiClient = new GoogleApiClient.Builder(currActivity)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
            mGoogleApiClient.connect();
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle)
    {
        Toast.makeText(currActivity, "Connected to service.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionSuspended(int i)
    {

    }

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

    }
}

我拥有以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.INTERNET" />

我还将此添加到build.gradle:

compile 'com.google.android.gms:play-services:9.2.0'

1 个答案:

答案 0 :(得分:1)

在这种情况下,我会使用LocationManager:

public class LocationHandler implements implements LocationListener{
LocationManager mLocationManager;

  public void Setup(){
    mLocationManager = (LocationManager) getApplicationContext()
            .getSystemService(LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            500, 10, this);
  }

  @Override
  public void onLocationChanged(Location location) {
    //do something with your location
  }

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

  @Override
  public void onProviderEnabled(String provider) {}

  @Override
  public void onProviderDisabled(String provider) {}
  }
}

此方法很简单,可让您跳过处理Google Play服务。