请求解决添加LocationRequest后App崩溃及requestLocationUpdates报错问题
com.google.android.gms.location.LocationRequest后的ClassCastException崩溃问题 从你给出的报错信息来看,核心问题很明确:你的DrawerActivity被错误地强制转换为com.google.android.gms.location.LocationListener,但你实际实现的是旧的系统位置监听器android.location.LocationListener——这两个是完全独立的类,根本不能互相转换,所以才会抛出ClassCastException导致崩溃。
下面是一步步的解决方法:
修正监听器的实现类
先检查你的DrawerActivity的导入和实现声明,把旧的系统位置监听器替换成Google Play服务提供的版本:// 删掉这行旧的导入 // import android.location.LocationListener; // 换成Google Play服务的监听器 import com.google.android.gms.location.LocationListener; public class DrawerActivity extends AppCompatActivity implements LocationListener { // 你的其他代码逻辑 }检查
requestLocationUpdates的调用
调用Google Play服务的位置更新API时,传入的监听器必须是com.google.android.gms.location.LocationListener的实例。确保你用的是FusedLocationProviderClient的API,而不是旧的LocationManager:// 初始化FusedLocationProviderClient FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); // 配置LocationRequest LocationRequest locationRequest = LocationRequest.create(); locationRequest.setInterval(10000); // 10秒更新一次 locationRequest.setFastestInterval(5000); // 最快5秒更新 locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // 这里的this就是实现了Google监听器的DrawerActivity,不会再报错 fusedLocationClient.requestLocationUpdates(locationRequest, this, Looper.getMainLooper());清理旧的系统位置API代码
如果你之前写过基于LocationManager的位置请求代码,一定要彻底移除或者替换掉,避免两种API混用导致类型混淆。比如下面这种旧代码就不能再保留了:// 旧的系统位置API,必须删除 // LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);验证依赖配置
最后确认你的Module级build.gradle里已经正确添加了Google Play服务的位置依赖,版本建议用最新稳定版:dependencies { implementation 'com.google.android.gms:play-services-location:21.0.1' }
如果做完这些还是有问题,建议你把完整的报错堆栈信息贴出来,这样能更精准地定位哪一行代码出了问题——毕竟你现在的报错信息被截断了,完整堆栈能帮我们更快找到根源。
内容的提问来源于stack exchange,提问作者hushtag

