我想实现setLocationSource()
来处理电池高使用率,我尝试从文档中搜索样本,但我在上得到了NullPointerException
mMap.setLocationSource(this);
我错过了什么。。
我有长代码。。这只是我显示的相关代码。。并非所有代码。
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationSource,
LocationListener {
and so on...
private OnLocationChangedListener mMapLocationListener;
private GoogleMap mMap;
@Override
public void onMapReady(final GoogleMap googleMap) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setLocationSource(this);
mMap = googleMap;
and so on....
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(INTERVAL)
.setFastestInterval(8000)
.setSmallestDisplacement(SMALLEST_DISPLACEMENT)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mMapLocationListener = onLocationChangedListener;
}
@Override
public void deactivate() {
mMapLocationListener = null;
}
@Override
public void onConnected(@Nullable Bundle bundle) {
isOnline();
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
if (mGoogleApiClient.isConnected()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, REQUEST, this);
}else{
Toast.makeText(this, "Koneksi ke Google API Terganggu, Coba lagi.", Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "Terhubung dari Google Play Services.", Toast.LENGTH_SHORT).show();
}
@Override
public void onLocationChanged(Location location) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
if (mMapLocationListener != null) {
mMapLocationListener.onLocationChanged(location);
}
latLng = new LatLng(location.getLatitude(), location.getLongitude());
and so on...
将代码更改为
@Override
public void onMapReady(final GoogleMap googleMap) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap = googleMap;
mMap.setLocationSource(this);
and so on....