每次我打开该应用程序时,都会说您的应用程序已停止。
我找不到错误
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
protected LocationManager locationManager;
TextView tv1;
@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);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, (android.location.LocationListener) mLocationListener);
}
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
};
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
}
这是日志错误-
java.lang.RuntimeException:无法启动活动
ComponentInfo {manishsaran.maper / manishsaran.maper.MapsActivity}:
java.lang.ClassCastException:manishsaran.maper.MapsActivity $ 1无法
被强制转换为android.location.LocationListener
最佳答案
问题是您的LocationListener,应该通过导入
import android.location.LocationListener;
并实现其所有方法,如下所示:
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
并且不需要强制转换您的locationListener:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, mLocationListener);