无法解析方法requestLocationUpdates

时间:2015-04-20 21:31:01

标签: android android-maps-v2

我试图调用方法requestLocationUpdates,但最终我收到一条错误消息"无法解析方法"。 我认为这是因为"这个"争论,但我不确定。 我导入了LocationListener,但它没有帮助我。

以下是我的代码部分:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainMap extends ActionBarActivity implements LocationListener {

    private void addMarker(){
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
        if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available
            googleMap.setMyLocationEnabled(true);
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String provider = locationManager.getBestProvider(criteria, true);
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }

            // troubles here
            locationManager.requestLocationUpdates(provider, 20000, 10, this);

        }
    }

    @Override
    public void onLocationChanged(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
    }

}

2 个答案:

答案 0 :(得分:7)

您正在从错误的包中导入LocationListener。您似乎将其导入为:

com.google.android.gms.location.LocationListener

requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)方法是此类型的最后一个参数:

android.location.LocationListener

你可以看到here

将导入语句更改为加载android.location.LocationListener可以解决问题。

答案 1 :(得分:2)

您应该为MainActivityClass实施LocationListener并覆盖实施方法:onLocationChangedonStatusChangedonProviderEnabledonProviderDisabled

 public class MainActivity extends AppCompatActivity 
             implements OnMapReadyCallback, LocationListener

我得到了同样的错误,并通过实施如上所述修复了它。