Commit 7d0fe74f by liimin

feat(定位): 新增百度定位与按需权限

引入百度定位和 POI 检索作为可选定位源,新增通用权限检查与定位追踪器以支持按需申请;修复定位回调地址为空时被吞的问题,补充高德搜索 SDK 隐私合规配置,并恢复高德地图 API Key。
1 parent 248269da
package com.glsx.commonres.permission;
import android.Manifest;
import android.content.Context;
import com.blankj.utilcode.util.PermissionUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
/**
* 通用权限检测 / 按需申请类(渐进式)。
*
* 合规改造移除首页统一授权(MainFragment.requestPermissionAll)后,各页面需自行按需检测与申请权限。
* 本类把所有“是否已授权”的判断收敛到一处:新增权限类型时按同构追加 hasXxxPermission 即可,
* 内部统一走 hasGranted,避免按权限散建 *PermissionHelper 或在各 fragment 内联检测逻辑。
*
* 同时承载“按需申请”辅助方法(requestXxxBeforeAction,渐进式):已授权直接跑 onGranted,
* 未授权走 AndPermission 申请,拒绝仅降级不阻断。各页面进入对应场景前统一调此方法,
* 集中管理授权,避免各 fragment 内联权限检测与申请逻辑。
*
* 注意:存储的 requestStorageBeforeAction 为既有代码、仍留在 PermissionRequestUtil,
* 本次未迁移(避免扩大对已有文件的改动);后续如需彻底统一,可一并迁入本类。
*/
public final class PermissionChecker {
private PermissionChecker() {
}
/** 是否已授予定位权限(ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION 任一即可) */
public static boolean hasLocationPermission(Context context) {
return hasGranted(Manifest.permission.ACCESS_FINE_LOCATION)
|| hasGranted(Manifest.permission.ACCESS_COARSE_LOCATION);
}
/** 是否已授予存储权限(READ 或 WRITE 任一即可) */
public static boolean hasStoragePermission(Context context) {
return hasGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
|| hasGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
/** 是否已授予相机权限 */
public static boolean hasCameraPermission(Context context) {
return hasGranted(Manifest.permission.CAMERA);
}
/**
* 使用定位功能前按需申请定位权限(合规整改路线,与 PermissionRequestUtil.requestStorageBeforeAction 对齐)。
* 要点:
* 1. 仅在用户真正使用定位功能时申请(非启动/首页前置),不触发“启动前置弹窗”违规;
* 2. 用户拒绝后仅降级提示,不阻断其他核心功能;
* 3. 已具备定位权限则直接执行 onGranted,不再弹窗。
*
* 取消首页统一授权(MainFragment.requestPermissionAll)后,原依赖首页一次性授予定位权限的页面
* 都会踩“定位拿不到 fix → 坐标落在 (0,0) → 提交被判非法参数”的坑。
* 各页面统一改调本方法,集中管理授权,避免在各自 fragment 内联权限检测与申请逻辑。
*
* @param context 上下文(需 Activity,用于弹窗与权限请求 UI)
* @param onGranted 已具备权限或用户授权后执行的定位动作
* @param onDenied 用户拒绝/不可用时降级处理(不抛异常、不阻断)
*/
public static void requestLocationBeforeAction(Context context, Runnable onGranted, Runnable onDenied) {
if (hasLocationPermission(context)) {
if (onGranted != null) onGranted.run();
return;
}
AndPermission.with(context)
.permission(Permission.Group.LOCATION)
.rationale(new DefaultRationale())
.onGranted(permissions -> {
if (onGranted != null) onGranted.run();
})
.onDenied(permissions -> {
if (AndPermission.hasAlwaysDeniedPermission(context, permissions)) {
new PermissionSetting(context).showSetting(permissions);
}
if (onDenied != null) onDenied.run();
})
.start();
}
private static boolean hasGranted(String permission) {
return PermissionUtils.isGranted(permission);
}
}
......@@ -269,9 +269,9 @@
tools:replace="android:resource" />
</provider>
<!-- 高德地图SDK接入,Key参数2021.12.9 user 15018517717 -->
<!-- <meta-data-->
<!-- android:name="com.amap.api.v2.apikey"-->
<!-- android:value="15787bb490e8d9132c9fbe0ba45aa008" />-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="15787bb490e8d9132c9fbe0ba45aa008" />
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
......
......@@ -20,6 +20,7 @@ import com.alipay.mobile.framework.quinoxless.QuinoxlessApplicationLike;
//import com.alipay.mobile.framework.quinoxless.QuinoxlessPrivacyUtil;
import com.alipay.mobile.framework.quinoxless.QuinoxlessFramework;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.services.core.ServiceSettings;
//import com.facebook.drawee.backends.pipeline.Fresco;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
......@@ -337,6 +338,10 @@ public class AiCarApplication extends Application implements Application.Activit
AMapLocationClient.updatePrivacyShow(AiCarApplication.getConext().getApplicationContext(), true, true);
//设置是否同意用户授权政策 <b>必须在AmapLocationClient实例化之前调用
AMapLocationClient.updatePrivacyAgree(AiCarApplication.getConext().getApplicationContext(), true);
//高德搜索 SDK(GeocodeSearch 等 sea 引擎)隐私合规,必须在使用搜索能力前调用,否则抛 10001
//2026-09-24 实测 RemoteCarPositionManager 调 GeocodeSearch 抛 10001,全仓此前缺失该调用
ServiceSettings.getInstance().updatePrivacyShow(AiCarApplication.getConext().getApplicationContext(), true, true);
ServiceSettings.getInstance().updatePrivacyAgree(AiCarApplication.getConext().getApplicationContext(), true);
}
/**
......
package com.glsx.aicar.manager;
import android.content.Context;
import android.text.TextUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.glsx.aicar.util.MapUtil;
import com.glsx.commonres.util.ToastUtil;
import com.blankj.utilcode.util.LogUtils;
/**
* 百度定位提供者。自包含,不依赖高德 SDK。
*
* 百度返回 BD-09 坐标,在 onReceiveLocation 内通过 MapUtil.bdToGaoDe 转为 GCJ-02 后回调,
* 以保持 LocationManager 对外“输出 GCJ-02”的坐标契约不变(PhotoDamageFragment 仍用
* gaoDeToBaidu 转回 BD-09 给百度地图画蓝点,链路闭环)。
*/
public class BaiduLocationProvider implements LocationManager.ILocationSource {
public interface Observer {
void onLocation(double gcjLat, double gcjLon, String address, String city, String district, String describe);
}
private static final String TAG = "BaiduLocationProvider";
private LocationClient mLocClient;
private Observer mObserver;
public BaiduLocationProvider(Context context) {
// 必须在 new LocationClient 之前同意隐私协议(百度合规要求)
LocationClient.setAgreePrivacy(true);
try {
mLocClient = new LocationClient(context.getApplicationContext());
} catch (Exception e) {
LogUtils.e(TAG, "BaiduLocationProvider 构造 LocationClient 失败: " + e.getMessage());
e.printStackTrace();
return;
}
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
option.setCoorType("bd09ll");
option.setScanSpan(1000 * 30);
option.setOpenGps(true);
option.setIsNeedAddress(true);
// 开启语义化位置描述(“在XX附近”),否则 getLocationDescribe() 恒为空;
// 该值经 Observer 喂给 LocationManager 合成 AMapLocation.setDescription(),与高德 getDescription() 对齐
option.setIsNeedLocationDescribe(true);
mLocClient.setLocOption(option);
mLocClient.registerLocationListener(mListener);
}
public void setObserver(Observer observer) {
mObserver = observer;
}
private final BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null) {
LogUtils.e(TAG, "onReceiveLocation location==null");
return;
}
int type = location.getLocType();
// 成功类型:61=GPS 161=网络 66=离线(百度 BDLocation 定义)
if (type == 61 || type == 161 || type == 66) {
double[] gcj = MapUtil.bdToGaoDe(location.getLatitude(), location.getLongitude());
// 语义化位置描述:优先“在XX附近”(getLocationDescribe),与高德 getDescription() 对应;
// 空则回退完整地址。该值经 Observer 喂给 LocationManager 合成 AMapLocation.setDescription(),
// 父页面 tv_accident_positon 与子页面 POI 搜索(参考高德)都复用它,无需额外 Bundle。
String describe = location.getLocationDescribe();
if (TextUtils.isEmpty(describe)) {
describe = location.getAddrStr();
}
if (!TextUtils.isEmpty(describe)) {
describe = describe.replace("中国", "");
}
if (mObserver != null) {
mObserver.onLocation(gcj[0], gcj[1],
location.getAddrStr(), location.getCity(), location.getDistrict(), describe);
}
} else {
LogUtils.e(TAG, "百度定位失败 locType=" + type + " desc=" + location.getLocTypeDescription());
ToastUtil.show("定位失败 百度错误码" + type);
}
}
};
public void start() {
if (mLocClient != null) {
mLocClient.start();
}
}
public void stop() {
if (mLocClient != null) {
mLocClient.stop();
}
}
public void restart() {
if (mLocClient != null) {
mLocClient.restart();
}
}
}
package com.glsx.aicar.manager;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.blankj.utilcode.util.LogUtils;
import com.glsx.aicar.manager.LocationManager;
import com.glsx.dao.bean.TrafficSearchResultBean;
import java.util.ArrayList;
import java.util.List;
/**
* 百度 POI 城市检索提供者。自包含,不依赖高德 SDK。
*
* 与 {@link BaiduLocationProvider} 同理:把百度检索封装成独立类,调用方(DamageChoosePosFragment)
* 保留原高德检索代码,仅在其入口按 LocationManager.USE_BAIDU 分支调用本类,做到“新增不替换”。
*
* 返回的 TrafficSearchResultBean 坐标为百度 BD-09(bd09ll),与同页百度地图蓝点、下游
* PhotoDamageFragment 的百度地图/百度路线规划 datum 一致,无需转换。
*/
public class BaiduPoiSearchProvider {
public interface Callback {
void onResult(List<TrafficSearchResultBean> list);
void onError(String msg);
}
private PoiSearch mPoiSearch;
private Callback mCallback;
public BaiduPoiSearchProvider() {
mPoiSearch = PoiSearch.newInstance();
mPoiSearch.setOnGetPoiSearchResultListener(mListener);
}
private final OnGetPoiSearchResultListener mListener = new OnGetPoiSearchResultListener() {
@Override
public void onGetPoiResult(PoiResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
LogUtils.w("BaiduPoiSearchProvider onGetPoiResult error=" + (result == null ? "null" : result.error));
if (mCallback != null) {
mCallback.onError("未找到结果");
}
return;
}
List<PoiInfo> allPoi = result.getAllPoi();
List<TrafficSearchResultBean> list = new ArrayList<>();
if (allPoi != null) {
for (PoiInfo info : allPoi) {
TrafficSearchResultBean bean = new TrafficSearchResultBean();
bean.setName(info.name); // POI 名称
bean.setDistrict(info.area); // 行政区域
bean.setCity(info.city); // 城市名
bean.setLatitude(info.location != null ? info.location.latitude : 0); // BD-09 纬度
bean.setLongitude(info.location != null ? info.location.longitude : 0); // BD-09 经度
bean.setUid(info.uid); // POI ID
list.add(bean);
}
}
if (mCallback != null) {
mCallback.onResult(list);
}
}
@Override
public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
// 室内 POI 检索本页不使用,空实现以满足接口契约
}
@Override
public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
// POI 详情检索本页不使用,空实现以满足接口契约
}
@Override
public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
// POI 详情检索(旧重载)本页不使用,空实现以满足接口契约
}
};
/**
* 按城市检索关键字 POI。
*
* @param city 城市名(来自定位结果);为空时退化为全国/按关键字检索
* @param keyword 检索关键字
* @param callback 结果回调(主线程)
*/
public void searchCity(String city, String keyword, Callback callback) {
this.mCallback = callback;
PoiCitySearchOption option = new PoiCitySearchOption()
.city(city)
.keyword(keyword)
.pageNum(0)
.pageCapacity(10);
mPoiSearch.searchInCity(option);
}
/**
* 关键字检索当前城市周边 POI。封装原 DamageChoosePosFragment.searchByBaidu 的取城市 + 调检索逻辑,
* 调用方(fragment)只需传 keyword 与结果回调,无需再关心城市来源。城市统一从
* {@link LocationManager#getCurrentCity()} 取(百度/高德分支下均由对应定位源填充)。
*
* @param keyword 检索关键字
* @param callback 结果回调(主线程)
*/
public void searchByKeyword(String keyword, Callback callback) {
searchCity(LocationManager.getCurrentCity(), keyword, callback);
}
public void destroy() {
if (mPoiSearch != null) {
mPoiSearch.destroy();
mPoiSearch = null;
}
}
}
......@@ -32,6 +32,15 @@ public class LocationManager {
public double mLatitude = 0;
public double mLongitude = 0;
public static final boolean USE_BAIDU = true;
private ILocationSource mSource;
public static interface ILocationSource {
void start();
void stop();
void restart();
}
private Handler mHandler;
private final long STOP_BDLOCATION_DELAY_TIME = 10 * 60 * 1000;//延迟停止时间10分钟
......@@ -59,13 +68,8 @@ public class LocationManager {
*/
public void startAMapLocationClientListener() {
LogUtils.e(TAG, "startAMapLocationClientListener , isRegister=" + isRegister);
if (isRegister) {
if (locationClient != null)
// 开始请求定位
locationClient.startLocation();
} else {
//先设置监听,再开始请求定位
registerAMapListener();
if (mSource != null) {
mSource.start();
}
if (mHandler != null) {
mHandler.removeCallbacks(stopAMapLocationRunnable);
......@@ -77,8 +81,39 @@ public class LocationManager {
*/
public void stopAmapClientListener() {
LogUtils.e(TAG, "stopAmapClientListener , isRegister=" + isRegister);
if (isRegister) {
unregisterAMapListener();
if (mSource != null) {
mSource.stop();
}
}
/**
* 干净地重启高德定位监听:先注销内部 AMap 回调并 stop,再重新 setListener + start。
* 合规改造后首页可能在"无定位权限"状态下先启用过定位(返回 errorCode=12 卡在错误态),
* 后续页面拿到权限后仅 startLocation() 无法让 AMap 从"无权限错误态"恢复,
* 必须 stop 后重新 start 才能产出有效 fix(线上版因首页已一次性授权,从不踩此坑)。
*/
public void restartAMapLocationClient() {
LogUtils.e(TAG, "restartAMapLocationClient");
if (mSource != null) {
mSource.restart();
}
}
/**
* 高德定位源的重启实现(仅当 USE_BAIDU=false 时由 ILocationSource 委托调用)。
* 干净地重启高德:先注销内部 AMap 回调并 stop,再重新 setListener + start。
*/
private void restartAmapInner() {
LogUtils.e(TAG, "restartAmapInner");
if (locationListener != null) {
if (isRegister) {
locationClient.unRegisterLocationListener(locationListener);
locationClient.stopLocation();
isRegister = false;
}
locationClient.setLocationListener(locationListener);
isRegister = true;
locationClient.startLocation();
}
}
......@@ -86,6 +121,32 @@ public class LocationManager {
return mAmapLocation;
}
/**
* 当前定位城市名(用于百度城市 POI 检索)。
* 百度分支下 mAmapLocation 由 BaiduLocationProvider 合成并填充 city;
* 高德分支下由高德定位原生填充。统一从这里取,避免调用方各自触碰 AMapLocation(高德 SDK 类型)。
*/
public static String getCurrentCity() {
AMapLocation loc = getInstance().getmAmapLocationn();
return (loc != null && loc.getCity() != null) ? loc.getCity() : "";
}
/**
* 把百度定位数据适配成统一的 AMapLocation 对象:上层消费方(PhotoDamageFragment、
* DamageChoosePosFragment、TrafficAddSubscriberActivity 等)只认 AMapLocation,不感知百度/高德。
* 百度分支在 initLocation() 的 observer 中调用本方法,避免“new + 一连串 set”散落在匿名内部类里。
*/
private AMapLocation buildBaiduAmapLocation(double gcjLat, double gcjLon, String address, String city, String district, String describe) {
AMapLocation loc = new AMapLocation("");
loc.setLatitude(gcjLat);
loc.setLongitude(gcjLon);
loc.setAddress(address);
loc.setCity(city);
loc.setDistrict(district);
loc.setDescription(describe);
return loc;
}
/***
* 注册高德定位监听
*/
......@@ -161,16 +222,51 @@ public class LocationManager {
* @since 2.8.0
*/
private void initLocation() {
//初始化client
try {
locationClient = new AMapLocationClient(AiCarApplication.getConext().getApplicationContext());
locationOption = getDefaultOption();
//设置定位参数
locationClient.setLocationOption(locationOption);
} catch (Exception e) {
e.printStackTrace();
}
if (USE_BAIDU) {
// 百度定位源:BD-09 在 BaiduLocationProvider 内转 GCJ-02 后通过 observer 喂回 manager
BaiduLocationProvider p = new BaiduLocationProvider(
AiCarApplication.getConext().getApplicationContext());
p.setObserver(new BaiduLocationProvider.Observer() {
@Override
public void onLocation(double gcjLat, double gcjLon, String address, String city, String district, String describe) {
try {
mAmapLocation = buildBaiduAmapLocation(gcjLat, gcjLon, address, city, district, describe);
mLatitude = gcjLat;
mLongitude = gcjLon;
notifReceiveAMapLocation(mAmapLocation);
} catch (Exception e) {
e.printStackTrace();
}
}
});
mSource = p;
} else {
//初始化client
try {
locationClient = new AMapLocationClient(AiCarApplication.getConext().getApplicationContext());
locationOption = getDefaultOption();
//设置定位参数
locationClient.setLocationOption(locationOption);
} catch (Exception e) {
e.printStackTrace();
}
mSource = new ILocationSource() {
@Override
public void start() {
registerAMapListener();
}
@Override
public void stop() {
unregisterAMapListener();
}
@Override
public void restart() {
restartAmapInner();
}
};
}
}
/**
......@@ -234,13 +330,16 @@ public class LocationManager {
mLongitude = mAmapLocation.getLongitude();
LogUtils.v("LocationManager", "aMapLocation:" + mAmapLocation.getLatitude() + "," + mAmapLocation.getLongitude());
// 定位成功即通知观察者(坐标已就绪);地址判空仅影响地址文本回填,不应阻断坐标回调。
// 原逻辑把 notifReceiveAMapLocation 包在 !isEmpty(getAddress()) 内,逆地理地址为空时会吞掉坐标回调,
// 导致依赖定位的页面(碰撞救援等)观察者收不到 fix、地图中心停留在 (0,0)。
try {
notifReceiveAMapLocation(mAmapLocation);
} catch (Exception e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(mAmapLocation.getAddress())) {
LogUtils.v("LocationManager", "onReceiveLocation aMapLocation:" + mAmapLocation.getAddress());
try {
notifReceiveAMapLocation(mAmapLocation);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
//定位失败
......@@ -248,6 +347,17 @@ public class LocationManager {
sb.append("错误码:" + location.getErrorCode() + "\n");
sb.append("错误信息:" + location.getErrorInfo() + "\n");
sb.append("错误描述:" + location.getLocationDetail() + "\n");
// 失败分支此前无任何日志,合规改造后“定位拿不到 fix”无法排查;这里补 error 级日志
LogUtils.e(TAG, "onLocationChanged 定位失败 errorCode=" + location.getErrorCode()
+ " errorInfo=" + location.getErrorInfo()
+ " detail=" + location.getLocationDetail());
// release 包不便看日志时,把关键错误码直接弹到页面,便于排查。
// 例如 errorCode=7 + “KEY错误” 即高德 Key 的 SHA1/包名未在高德后台登记(当前 (0,0) 的真凶)。
String errTip = "定位失败 错误码" + location.getErrorCode();
if (!TextUtils.isEmpty(location.getErrorInfo())) {
errTip += ":" + location.getErrorInfo();
}
ToastUtil.show(errTip);
}
sb.append("***定位质量报告***").append("\n");
sb.append("* WIFI开关:").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
......
package com.glsx.aicar.manager;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.amap.api.location.AMapLocation;
import com.blankj.utilcode.util.LogUtils;
import com.glsx.commonres.permission.PermissionChecker;
/**
* 高德实时定位观察的通用收敛类(仅负责定位订阅 + 权限按需申请,不耦合任何具体地图/页面 UI)。
*
* <p>背景:合规改造移除了首页 {@code requestPermissionAll()}(一次性授权全部权限)后,
* 依赖定位权限的页面无法在首页拿到 fix,{@link LocationManager#getmAmapLocationn()} 返回 null、
* {@code mLatitude/mLongitude} 恒为 0.0,导致地图中心落在 (0,0)(几内亚湾)、
* 提交经纬度为 0.0 被服务端判“非法的参数”。</p>
*
* <p>本类把“订阅 LocationManager 实时定位 + 进入时按需申请定位权限 + 我的位置按钮”收敛为通用能力,
* 任何需要定位的页面(碰撞救援、选点、WebView、POI、交通、爱车位置等)统一调用,
* 避免在每个 fragment 里重复内联观察者注册 / 权限判断 / 居中逻辑。</p>
*
* <p>权限“是否已授予 / 按需申请”统一收敛到 {@link PermissionChecker}
* (渐进式 hasXxxPermission + requestLocationBeforeAction),避免按权限散建 *PermissionHelper。</p>
*
* <p>页面只需提供一个 {@link UiBinder}(匿名类/lambda)来落地具体的 UI 反应(回填坐标、居中地图、更新地址文本),
* fragment 自身不再新增定位观察者方法、不再内联权限判断、不再持有“是否已居中”之类的状态位。</p>
*/
public class LocationTracker implements LocationManager.IAMapTrackViewLocationObserver {
private static final String TAG = "LocationTracker";
/** 把定位结果应用到页面的 UI 动作。由调用页以匿名类提供,fragment 不再内联观察者/权限逻辑。 */
public interface UiBinder {
/** 每次拿到有效 fix 时回调(高德回调线程):用于回填提交用坐标等轻量动作 */
void onLocationUpdate(double latitude, double longitude);
/** 首次拿到有效 fix 时回调(主线程,仅一次):用于居中地图、回填地址文本 */
void onFirstLocation(double latitude, double longitude, String description, String address);
/** “我的位置”按钮触发(主线程):用最新坐标居中地图(不要求首次) */
void onCenterToLatest(double latitude, double longitude);
}
private final Context mContext;
private final UiBinder mUi;
private final Handler mMainHandler = new Handler(Looper.getMainLooper());
private boolean mRegistered = false;
// 进入后是否已用真实定位把地图中心到过一次,避免每次 GPS 回调都平移镜头(状态位收口到本类)
private boolean mCenteredOnce = false;
// 缓存最新定位,供“我的位置”按钮与提交前校验读取
private double mLastLat = 0.0;
private double mLastLng = 0.0;
public LocationTracker(Context context, UiBinder ui) {
mContext = context;
mUi = ui;
}
/**
* 进入页面时调用:先确保定位权限(按需申请,内部走 PermissionChecker.requestLocationBeforeAction),
* 拿到授权后开始观察实时定位。未授予时弹窗申请,用户拒绝则仅记日志、不阻断页面。
*/
public void requestOnEntry() {
PermissionChecker.requestLocationBeforeAction(mContext,
this::startLocationObserve,
() -> LogUtils.d(TAG, "requestOnEntry location permission denied"));
}
/** “我的位置”按钮:已授权则直接订阅定位并即时居中(若有历史坐标),未授权则走 requestOnEntry 按需申请 */
public void centerMyLocation() {
if (PermissionChecker.hasLocationPermission(mContext)) {
startLocationObserve();
if (hasValidLocation() && mUi != null) {
mUi.onCenterToLatest(mLastLat, mLastLng);
}
} else {
requestOnEntry();
}
}
/** 坐标是否仍是默认的 (0,0),供提交前校验 */
public boolean hasValidLocation() {
return Math.abs(mLastLat) > 0.0001 || Math.abs(mLastLng) > 0.0001;
}
/** 最新纬度,供提交使用 */
public double getLatitude() {
return mLastLat;
}
/** 最新经度,供提交使用 */
public double getLongitude() {
return mLastLng;
}
/** 开始订阅高德实时定位(幂等:重复调用不会重复注册) */
public void startLocationObserve() {
if (mRegistered) {
return;
}
try {
// 合规改造后首页可能已以“无定位权限”状态启动过 AMap 定位并卡在错误态(errorCode=12),
// 这里拿到权限后强制干净重启,确保 AMap 能产出有效 fix(线上版因首页已授权不会踩此坑)。
LocationManager.getInstance().restartAMapLocationClient();
LocationManager.getInstance().registerAMapTVListener(this);
mRegistered = true;
} catch (Exception e) {
LogUtils.e(TAG, "startLocationObserve failed", e);
}
}
/** LocationManager 实时定位回调,转发给外部监听者 */
@Override
public void onReceiveAMapLocation(AMapLocation location) throws Exception {
if (location == null || location.getErrorCode() != 0) {
return;
}
mLastLat = location.getLatitude();
mLastLng = location.getLongitude();
if (mUi != null) {
mUi.onLocationUpdate(mLastLat, mLastLng);
}
if (mCenteredOnce) {
return;
}
mCenteredOnce = true;
final double lat = mLastLat;
final double lng = mLastLng;
final String desc = location.getDescription();
final String addr = location.getAddress();
final UiBinder ui = mUi;
mMainHandler.post(() -> {
if (ui != null) {
ui.onFirstLocation(lat, lng, desc, addr);
}
});
}
/** 页面停止时注销观察者,防止内存泄漏与重复回调 */
public void stopObserve() {
if (mRegistered) {
LocationManager.getInstance().unregisterAMapTVListener(this);
mRegistered = false;
}
}
}
......@@ -20,6 +20,7 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
......@@ -58,6 +59,7 @@ import com.baidu.mapapi.utils.DistanceUtil;
import com.glsx.aicar.R;
import com.glsx.aicar.adapter.TrafficSearchAdapter;
import com.glsx.aicar.ly.LogFileEx;
import com.glsx.aicar.manager.BaiduPoiSearchProvider;
import com.glsx.aicar.manager.LocationManager;
import com.glsx.aicar.manager.RemoteCarPositionManager;
import com.glsx.aicar.map.bean.StdLatLng;
......@@ -115,6 +117,27 @@ public class DamageChoosePosFragment extends BaseFragment implements View.OnClic
private TrafficSearchAdapter mTrafficSearchAdapter;
private List<TrafficSearchResultBean> listSearchString;
// 百度 POI 检索提供者(仅当 LocationManager.USE_BAIDU=true 时启用,与原高德检索并存)
private BaiduPoiSearchProvider mBaiduPoiSearchProvider;
// 百度 POI 检索结果回调(复用,不每次 new 匿名类)。仅做列表刷新 + Toast,不触碰原高德 onPoiSearched 链路。
// 检索编排已收进 BaiduPoiSearchProvider.searchByKeyword(内部取城市),fragment 不再持搜索逻辑。
private final BaiduPoiSearchProvider.Callback mBaiduCallback = new BaiduPoiSearchProvider.Callback() {
@Override
public void onResult(List<TrafficSearchResultBean> list) {
listSearchString.clear();
listSearchString.addAll(list);
updateSearchResultUI();
}
@Override
public void onError(String msg) {
listSearchString.clear();
updateSearchResultUI();
Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}
};
public static DamageChoosePosFragment newInstance() {
DamageChoosePosFragment fragment = new DamageChoosePosFragment();
Bundle args = new Bundle();
......@@ -443,6 +466,13 @@ public class DamageChoosePosFragment extends BaseFragment implements View.OnClic
private void searchInputAddress(String searchName) throws AMapException {
if (LocationManager.USE_BAIDU) {
if (mBaiduPoiSearchProvider == null) {
mBaiduPoiSearchProvider = new BaiduPoiSearchProvider();
}
mBaiduPoiSearchProvider.searchByKeyword(searchName, mBaiduCallback);
return;
}
String city = null;
AMapLocation aMapLocation = LocationManager.getInstance().getmAmapLocationn();
if (aMapLocation != null)
......@@ -479,6 +509,10 @@ public class DamageChoosePosFragment extends BaseFragment implements View.OnClic
public void onDestroyView() {
super.onDestroyView();
// mBaiduMap.setMyLocationEnabled(false);
if (mBaiduPoiSearchProvider != null) {
mBaiduPoiSearchProvider.destroy();
mBaiduPoiSearchProvider = null;
}
mMapView.getMap().clear();
mMapView.onDestroy();
mMapView = null;
......
......@@ -75,6 +75,7 @@ import com.blankj.utilcode.util.PermissionUtils;
import com.glsx.aicar.R;
import com.glsx.aicar.adapter.DamagePhotoAdapter;
import com.glsx.aicar.manager.LocationManager;
import com.glsx.aicar.manager.LocationTracker;
import com.glsx.aicar.map.bean.StdLatLng;
import com.glsx.aicar.ui.fragment.BaseFragment;
import com.glsx.aicar.ui.fragment.server.OverlayManager;
......@@ -192,6 +193,8 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
public double mDamageLatitude = 0;
public double mDamageLongitude = 0;
public String mDamageAddress = "";
// 定位观察的通用收敛类(LocationTracker);权限检测统一走 PermissionChecker
private LocationTracker mLocationHelper;
//救援门店所在的地址及经纬度
private String storeAddress;
private String storeCity;
......@@ -378,6 +381,38 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
getTimeRouteResult(mDamageLatitude, mDamageLongitude, storeLat, storeLng);
}
clearDamagePhotosPath();
// 进入碰撞救援按需申请定位权限,确保地图中心与提交经纬度取真实 fix(合规改造后首页不再一次性授权)。
// 定位观察/权限/居中逻辑全部收敛到 LocationTracker;fragment 仅通过 UiBinder 落地具体 UI 反应。
mLocationHelper = new LocationTracker(mContext, new LocationTracker.UiBinder() {
@Override
public void onLocationUpdate(double latitude, double longitude) {
// 每次有效 fix 回填提交用坐标(与手动选点 onDamageChoosePositionSuccess 共同维护同一对字段)
mDamageLatitude = latitude;
mDamageLongitude = longitude;
}
@Override
public void onFirstLocation(double latitude, double longitude, String description, String address) {
// 首次真实 fix:居中地图 + 回填地址文本(仅一次,状态由 LocationTracker 维护)
setUserMapCenter(latitude, longitude);
// 地图底图是百度(BD-09),定位来自高德(GCJ-02):把高德坐标转百度后喂给百度“我的位置”蓝点,
// 否则 setMyLocationEnabled(true) 没有数据源,地图上不显示当前位置标注。
double[] bd = MapUtil.gaoDeToBaidu(longitude, latitude);
map.setMyLocationData(new MyLocationData.Builder()
.latitude(bd[0]).longitude(bd[1]).accuracy(0).build());
if (TextUtils.isEmpty(mDamageAddress)) {
tv_accident_positon.setText(description);
tv_accident_positon_address.setText(address);
}
}
@Override
public void onCenterToLatest(double latitude, double longitude) {
// “我的位置”按钮:用最新坐标居中(即时,不等新 fix)
setUserMapCenter(latitude, longitude);
}
});
mLocationHelper.requestOnEntry();
}
// /**
......@@ -476,28 +511,21 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
}
private void clearDamagePhotosPath() {
if (!PermissionUtils.isGranted(WRITE_EXTERNAL_STORAGE)) {
PermissionUtils.permission(WRITE_EXTERNAL_STORAGE).request();
} else {
String sdcardState = Environment.getExternalStorageState();
String sdcardPathDir = CommonConst.SDCARD_DAMAGE_PHOTOS_PATH;
if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
// 有sd卡,是否有myImage文件夹
File fileDir = new File(sdcardPathDir);
if (!fileDir.exists()) {
fileDir.mkdirs();
} else {
//遍历文件夹
if (fileDir.isDirectory()) {
File[] files = fileDir.listFiles();
for (File tempfile : files) {
tempfile.delete();
}
}
// 与 fromCamera 保持一致:清理应用私有外部存储目录(/Android/data/com.glsx.aicar/files/Pictures/damagephotos/)下的拍照缓存。
// 该目录为应用私有,不需要 WRITE_EXTERNAL_STORAGE 权限。
File picRoot = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (picRoot == null) {
return;
}
File fileDir = new File(picRoot, "damagephotos");
if (fileDir.exists() && fileDir.isDirectory()) {
File[] files = fileDir.listFiles();
if (files != null) {
for (File tempfile : files) {
tempfile.delete();
}
}
}
}
@Override
......@@ -515,6 +543,9 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
if (mLocationHelper != null) {
mLocationHelper.stopObserve();
}
}
@SuppressLint("NonConstantResourceId")
......@@ -536,6 +567,11 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
if (mAccidentRecordPhotoList.size() < 2) {
showDialog(getResources().getString(R.string.warnning_tips), getResources().getString(R.string.toSureSendRequest), TYPE_MESSAGE_DIALOG, true);
// sendDamageEventToServer();
} else if (Math.abs(mDamageLatitude) < 0.0001 && Math.abs(mDamageLongitude) < 0.0001) {
// 未获取到定位,避免把 (0,0) 提交服务端被判“非法的参数”
showDialog(getResources().getString(R.string.tips),
"正在获取您的位置,请稍候或在系统设置中开启定位权限后重试", TYPE_MESSAGE_DIALOG, true);
mLocationHelper.requestOnEntry();
} else {
//开始上传已选择文件列表
startUpLoadMediaFileList();
......@@ -543,7 +579,7 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
}
break;
case R.id.iv_current_location:
showCurrentLocation(); //高德
mLocationHelper.centerMyLocation(); //高德
// initLocation(); ///百度
break;
case R.id.common_next2:
......@@ -555,25 +591,6 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
}
}
/**
* 在高德地图上显示当前位置
*/
private void showCurrentLocation() {
PermissionRequestUtil.requestLocationPermissions(mContext, new PermissionReqCallback() {
@Override
public void onGranted() {
LogUtils.d(TAG, "showCurrentLocation ...");
mDamageLatitude = LocationManager.getInstance().mLatitude;
mDamageLongitude = LocationManager.getInstance().mLongitude;
setUserMapCenter(mDamageLatitude, mDamageLongitude);
}
@Override
public void onDenied() {
}
});
}
private static final int TYPE_WAITDIALOG = 1;
private static final int TYPE_SUCCEED_DIALOG = 2;
......@@ -1138,18 +1155,19 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
*/
private void fromCamera() {
try {
// 获取文件
// 获取文件:改用应用私有外部存储目录(/Android/data/com.glsx.aicar/files/Pictures/damagephotos/)。
// 原因:Android 10+ scoped storage 下,应用无法在 /storage/emulated/0/aicar/ 建目录、相机也写不进去,
// 导致拍照文件始终不存在(一直显示旧图 / 弹“保存失败”)。应用私有目录各版本均可写,
// 且 FileProvider 已配 external-files-path(provider_path.xml)可共享给系统相机写、自己读。
File file = null;
String sdcardState = Environment.getExternalStorageState();
String sdcardPathDir = CommonConst.SDCARD_DAMAGE_PHOTOS_PATH;
if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
// 有sd卡,是否有myImage文件夹
File fileDir = new File(sdcardPathDir);
File picRoot = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (picRoot != null) {
File fileDir = new File(picRoot, "damagephotos");
if (!fileDir.exists()) {
fileDir.mkdirs();
}
// 是否有headImg文件
file = new File(CommonConst.SDCARD_DAMAGE_PHOTOS_PATH + "damage" + gvDamageIndex + ".JPEG");
// 文件名加时间戳,保证每次拍照是独立文件,避免同一路径被 Glide 缓存住旧图(一直显示键盘照片)
file = new File(fileDir, "damage" + gvDamageIndex + "_" + System.currentTimeMillis() + ".JPEG");
chosePhotoIconPath = file.getPath();
}
......@@ -1168,6 +1186,9 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
}
}
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, chosePhotoIconUri);
// 关键修复:把 FileProvider URI 的读写权限临时授予系统相机。否则相机拿不到写权限,
// 照片写不进我们的路径,每次都显示该路径下旧文件(如首次测试留下的键盘照片)。
openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//openCameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(openCameraIntent, FROM_CAMERA);
......@@ -1336,6 +1357,12 @@ public class PhotoDamageFragment extends BaseFragment implements View.OnClickLis
if (requestCode == FROM_CAMERA && resultCode == Activity.RESULT_OK) {
//onActivityResult() requestCode=8192,resultCode=-1,data=null
File tempfile = new File(chosePhotoIconPath);
if (!tempfile.exists()) {
// release 包不便看日志时,直接弹提示:相机未能把照片写入我们的路径(多为 URI 写权限 / 存储权限问题)
ToastUtil.show("拍照保存失败,请重试或检查存储权限");
LogUtils.e(TAG, "onActivityResult FROM_CAMERA 拍照文件不存在: " + chosePhotoIconPath);
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
chosePhotoIconUri = FileProvider.getUriForFile(getActivity(), CommonConst.AICAR_PROVIDER_AUTHORITY, tempfile);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!