2017-01-31 32 views
0

我想要再次使用lat,lon变量,但是在onConnected()中设置它时,它不会在MainActivity中设置。 这里是我的代码,无法将经度和纬度存储在变量中

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 
    private static final int PERMISSION_ACCESS_FINE_LOCATION = 1; 
private GoogleApiClient googleApiClient; 
protected Context context; 
double lat, lon; 
TextView txtLat; 
double latitude = 0, longitude = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 
     ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
       PERMISSION_ACCESS_FINE_LOCATION); 
    } 

    googleApiClient = new GoogleApiClient.Builder(this, this, this).addApi(LocationServices.API).build(); 


} 

和这里的,其中包括了获得Lat Long网的另一部分。

@Override 
public void onConnected(Bundle bundle) { 
    Log.i(MainActivity.class.getSimpleName(), "Connected to Google Play Services!"); 

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
      == PackageManager.PERMISSION_GRANTED) { 
     Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 

     lat = lastLocation.getLatitude(); 
     lon = lastLocation.getLongitude(); 
     txtLat = (TextView) findViewById(R.id.textView1); 
     txtLat.setText(lat + " " + lon); 
    } 

} 
+0

什么'双纬度= 0,经度= 0;'这是你想再次使用这个? –

+0

@ntaloventi no。 lat,lon –

回答

1

具有位置的权限允许的,并具有启用的位置是不一样的东西(如:用户可以允许该位置的权限,但位置不使这样LastLocation可能是空的) 例如,您可以:

LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
boolean gps_enabled = false; 
boolean network_enabled = false; 

gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

if (gps_enabled || network_enabled) { 
    LocationRequest mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(1000); 
    mLocationRequest.setFastestInterval(1001); 
    mLocationRequest.setNumUpdates(1); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    LocationServices.FusedLocationApi.requestLocationUpdates(GoogleClient, mLocationRequest, new LocationListener() { 
     @Override 
     public void onLocationChanged(Location location) { 
        LocationServices.FusedLocationApi.removeLocationUpdates(GoogleClient, this); 
        lat = location.getLatitude(); 
        lon = location.getLongitude(); 
       } 
      }); 
     }