OnLocationChanged 只工作一次

Posted

技术标签:

【中文标题】OnLocationChanged 只工作一次【英文标题】:OnLocationChanged works only once 【发布时间】:2017-01-06 16:02:33 【问题描述】:

我正在尝试将标记添加到我设备的当前位置。无论我尝试什么,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();

【问题讨论】:

您正在 onLocationChanged 中停止位置更新! @NDorigatti 谢谢。 @NDorigatti 为什么不回答这个问题? 好吧,我不介意“获得积分”,这只是对可能从某处复制的行的简单评论,我没有输入代码,这就是我使用 cmets 的原因:D 【参考方案1】:

您需要删除这些语句

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

一旦它们消失,您应该让OnLocatioChanged 继续工作。

【讨论】:

【参考方案2】:

您可以尝试使用OnMyLocationChangeListener,如下所示:

public class MapsActivity extends FragmentActivity implements
    OnMyLocationChangeListener 


    @Override
    public void onMyLocationChange(Location location) 

    



【讨论】:

我刚试了一下,但是onMyLocationChange方法在我启动应用时没有触发一次。 你启用Location了吗?

以上是关于OnLocationChanged 只工作一次的主要内容,如果未能解决你的问题,请参考以下文章

Android Google Maps API OnLocationChanged 仅调用一次

onLocationChanged 仅使用网络提供商调用一次

可以永远不会调用 onLocationChanged 吗?

OnLocationChanged 将不再工作,在许多设备上

GPS Android - 只定位一次

onLocationChanged 从未调用过?