2016-08-30 4 views
0

Я пытаюсь добавить маркер в текущее местоположение своего устройства. Независимо от того, что я пытаюсь, метод onLocationChanged запускает приложение сразу после запуска приложения.OnLocationChanged работает только один раз

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, 
    LocationListener { 

private GoogleMap mMap; 
GoogleApiClient mGoogleApiClient; 
Location mLastLocation; 
Marker mCurrLocationMarker; 
LocationRequest mLocationRequest; 
private static final String LOG_TAG = "MainActivity"; 
/** 
* ATTENTION: This was auto-generated to implement the App Indexing API. 
* See https://g.co/AppIndexing/AndroidStudio for more information. 
*/ 
private GoogleApiClient client; 

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     checkLocationPermission(); 
    } 

    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
    mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); 


    //Initialize Google Play Services 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 
     } 
    } else { 
     buildGoogleApiClient(); 
     mMap.setMyLocationEnabled(true); 
    } 
} 

protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onConnected(Bundle bundle) { 

    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(5000); 
    mLocationRequest.setFastestInterval(3000); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      == PackageManager.PERMISSION_GRANTED) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, 
       mLocationRequest, this); 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onLocationChanged(Location location) { 

    Log.d(LOG_TAG, "current location " + location.toString()); 
    mLastLocation = location; 

    //Place current location marker 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 

    MarkerOptions markerOptions = new MarkerOptions(); 
    markerOptions.position(mLastLocation); 
    markerOptions.title("Test"); 
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); 
    mCurrLocationMarker = mMap.addMarker(markerOptions); 

    //move map camera 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(17)); 


    //stop location updates 
    if (mGoogleApiClient != null) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
    } 
} 

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

} 

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 

public boolean checkLocationPermission() { 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     // Asking user if explanation is needed 
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_FINE_LOCATION)) { 

      // Show an explanation to the user *asynchronously* -- don't block 
      // this thread waiting for the user's response! After the user 
      // sees the explanation, try again to request the permission. 

      //Prompt the user once explanation has been shown 
      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 


     } else { 
      // No explanation needed, we can request the permission. 
      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     } 
     return false; 
    } else { 
     return true; 
    } 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, 
             @NonNull String permissions[], int... grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_LOCATION: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // permission was granted. Do the 
       // contacts-related task you need to do. 
       if (ContextCompat.checkSelfPermission(this, 
         Manifest.permission.ACCESS_FINE_LOCATION) 
         == PackageManager.PERMISSION_GRANTED) { 

        if (mGoogleApiClient == null) { 
         buildGoogleApiClient(); 
        } 
        mMap.setMyLocationEnabled(true); 
       } 

      } else { 

       // Permission denied, Disable the functionality that depends on this permission. 
       Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 
} 

@Override 
public void onStart() { 
    super.onStart(); 
} 

@Override 
public void onStop() { 
    super.onStop(); 
} 

}

+1

вы останавливаете обновления местоположения в onLocationChanged! –

+0

@NDorigatti Спасибо. – korujzade

+0

@NDorigatti почему бы не сделать ответ? –

ответ

0

Вы можете попробовать с OnMyLocationChangeListener, как показано ниже:

public class MapsActivity extends FragmentActivity implements 
    OnMyLocationChangeListener { 


    @Override 
    public void onMyLocationChange(Location location) { 

    } 


} 
+0

Я просто попробовал, но метод 'onMyLocationChange' не запускался один раз, когда я начал приложение. – korujzade

+0

Вы включили «Местоположение»? –

1

Вы должны удалить эти заявления

//stop location updates 
    if (mGoogleApiClient != null) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
    } 
} 

После того, как они ушли, вы должны иметь OnLocatioChanged непрерывно работать ,

Смежные вопросы