【发布时间】:2016-09-05 23:21:17
【问题描述】:
我正在创建一个应用程序来在地图上显示用户位置。问题是当调用方法 requestLocationUpdates 或 removeUpdates 时,我在 LocationListener 参数中收到错误。我知道这可能是由于导入了错误的文件,但我确实导入了 com.google.android.gms.location.LocationListener 之一。 我做了我的研究,但真的找不到解决方案。我会放一些我的代码,所以它可能会有所帮助。 感谢您的帮助。
import com.google.android.gms.location.LocationListener;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(),false);
}
@Override
public void onResume(){
super.onResume();
locationManager.requestLocationUpdates(provider,400,1,this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng cali = new LatLng(3.451234, -76.532694);
mMap.moveCamera(CameraUpdateFactory.newLatLng(cali));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
@Override
public void onLocationChanged(Location location) {
Double lat = location.getAltitude();
Double lng = location.getLongitude();
}
@Override
protected void onPause(){
super.onPause();
locationManager.removeUpdates(this);
}
}
正如我所说的,问题出在以下几行:
locationManager.requestLocationUpdates(provider,400,1,this);
和
locationManager.removeUpdates(this);
顺便说一句,如果我删除这 2 行并仅显示地图和标记,则代码可以正常工作。
【问题讨论】:
-
将“this”替换为“getApplicationContext()”
-
感谢您的回复,我按照您说的做了,但遇到了同样的错误。 locationManager.removeUpdates(getApplicationContext()); locationManager.requestLocationUpdates(provider,400,1,getApplicationContext());
标签: android this locationlistener