MainAbilitySlice.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. package com.fujica.abk.slice;
  2. import com.fujica.abk.ResourceTable;
  3. import com.fujica.abk.api.cache;
  4. import com.fujica.abk.utils.Log;
  5. import com.fujica.abk.utils.Toast;
  6. import com.fujica.abk.utils.api;
  7. import com.huawei.hms.accountsdk.constant.CommonConstant;
  8. import com.huawei.hms.accountsdk.exception.ApiException;
  9. import com.huawei.hms.accountsdk.support.account.AccountAuthManager;
  10. import com.huawei.hms.accountsdk.support.account.request.AccountAuthParams;
  11. import com.huawei.hms.accountsdk.support.account.request.AccountAuthParamsHelper;
  12. import com.huawei.hms.accountsdk.support.account.result.AuthAccount;
  13. import com.huawei.hms.accountsdk.support.account.service.AccountAuthService;
  14. import com.huawei.hms.accountsdk.support.account.tasks.OnFailureListener;
  15. import com.huawei.hms.accountsdk.support.account.tasks.OnSuccessListener;
  16. import com.huawei.hms.accountsdk.support.account.tasks.Task;
  17. import com.huawei.hms.maps.harmony.*;
  18. import com.huawei.hms.maps.harmony.model.CameraPosition;
  19. import com.huawei.hms.maps.harmony.model.LatLng;
  20. import com.huawei.hms.maps.harmony.model.Marker;
  21. import com.huawei.hms.maps.harmony.model.MarkerOptions;
  22. import ohos.aafwk.ability.AbilitySlice;
  23. import ohos.aafwk.ability.DataAbilityHelper;
  24. import ohos.aafwk.ability.IDataAbilityObserver;
  25. import ohos.aafwk.content.Intent;
  26. import ohos.account.AccountAbility;
  27. import ohos.agp.colors.RgbColor;
  28. import ohos.agp.colors.StateColor;
  29. import ohos.agp.components.*;
  30. import ohos.agp.components.element.ShapeElement;
  31. import ohos.agp.utils.Color;
  32. import ohos.agp.window.dialog.ToastDialog;
  33. import ohos.agp.window.service.Window;
  34. import ohos.agp.window.service.WindowManager;
  35. import ohos.global.resource.NotExistException;
  36. import ohos.global.resource.Resource;
  37. import ohos.location.Location;
  38. import ohos.location.Locator;
  39. import ohos.location.LocatorCallback;
  40. import ohos.location.RequestParam;
  41. import ohos.sysappcomponents.settings.AppSettings;
  42. import ohos.sysappcomponents.settings.SystemSettings;
  43. import java.io.IOException;
  44. import java.lang.reflect.Method;
  45. import java.util.ArrayList;
  46. import java.util.List;
  47. public class MainAbilitySlice extends AbilitySlice {
  48. // PageSlider相关
  49. private PageSlider pageSlider;
  50. private PageSliderProvider pageSliderProvider;
  51. // 底部导航栏组件
  52. private DirectionalLayout navMy;
  53. private DirectionalLayout navFindParking;
  54. private DirectionalLayout navReserveParking;
  55. private DirectionalLayout navCurrentLocation;
  56. // 底部导航栏文字和图标
  57. private Text textMy;
  58. private Text textPark;
  59. private Text textFee;
  60. private Image iconPark;
  61. private Image iconPark1;
  62. private Image iconMy;
  63. private Image iconMy1;
  64. private Image iconFee;
  65. private Image iconFee1;
  66. // 当前选中的 tab
  67. private int currentTab = 1; // 0: 我的, 1: 找车位, 2: 预约停车
  68. // 定位相关
  69. private Locator locator;
  70. private LocatorCallback locatorCallback;
  71. private Location currentLocation; // 当前定位坐标
  72. // 地图相关 - 完全按照 MarkerDemo 的方式
  73. private HuaweiMap mHuaweiMap;
  74. /**
  75. * Declare a MapView object.
  76. */
  77. private MapView mMapView;
  78. /**
  79. * Declare a Marker object.
  80. */
  81. private Marker mMarker;
  82. /**
  83. * 当前位置标记
  84. */
  85. private Marker currentLocationMarker;
  86. DataAbilityHelper dataAbilityHelper;
  87. IDataAbilityObserver dataAbilityObserver;
  88. @Override
  89. public void onStart(Intent intent) {
  90. super.onStart(intent);
  91. cache.setToken(getContext(), "sdfdsfdsf11111111111");
  92. String token = cache.getToken(getContext());
  93. // api.http(getContext(), "http://www.baidu.com", "GET", null, null, null);
  94. api.http(getContext(), "/park/near/page?longitude=0&latitude=0", "GET", null, null, null);
  95. // 设置全屏显示
  96. setFullScreen();
  97. // 设置 CommonContext,华为地图需要 - 完全按照示例代码
  98. CommonContext.setContext(this);
  99. // 设置布局
  100. super.setUIContent(ResourceTable.Layout_ability_main);
  101. // 初始化组件
  102. initComponents();
  103. // 初始化地图 - 完全按照 MarkerDemo 的方式
  104. initMap();
  105. // 设置事件监听
  106. setupListeners();
  107. // 初始化定位
  108. initLocation();
  109. Button mBtnHuaweiIdSignIn = findComponentById(ResourceTable.Id_btn_hwid_sign_in);
  110. mBtnHuaweiIdSignIn.setClickedListener((Component c) -> {
  111. huaweiIdSignIn();
  112. });
  113. final String key = "car_license_plate_number";
  114. // final String key = SystemSettings.Date.TIME_FORMAT;
  115. dataAbilityHelper = DataAbilityHelper.creator(this);
  116. dataAbilityObserver = () -> {
  117. String timeFormat = SystemSettings.getValue(dataAbilityHelper, key);
  118. setTimeFormat(timeFormat);
  119. };
  120. dataAbilityHelper.registerObserver(SystemSettings.getUri(key), dataAbilityObserver);
  121. String timeFormat1 = SystemSettings.getValue(dataAbilityHelper, "car_license_plate_number");
  122. String timeFormat = SystemSettings.getValue(dataAbilityHelper, key);
  123. }
  124. void setTimeFormat(String timeFormat) {
  125. String timeStr = "12";
  126. if (timeStr.equals(timeFormat)) {
  127. // Display in 12-hour format
  128. } else {
  129. // Display in 24-hour format
  130. }
  131. }
  132. void huaweiIdSignIn() {
  133. AccountAuthService accountAuthService;
  134. // 1、配置登录请求参数AccountAuthParams,包括请求用户id(openid、unionid)、email、profile(昵称、头像)等。
  135. // 2、DEFAULT_AUTH_REQUEST_PARAM默认包含了id和profile(昵称、头像)的请求。
  136. // 3、如需要再获取用户邮箱,需要setEmail();
  137. // 4、如需要获取其他受限信息,如国家和地区,则需要先申请scope,再设置请求参数。
  138. AccountAuthParams accountAuthParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
  139. .setEmail()
  140. .createParams();
  141. try {
  142. accountAuthService = AccountAuthManager.getService(accountAuthParams);
  143. } catch (ApiException e) {
  144. // 处理初始化登录授权服务失败,status code标识了失败的原因,请参考API中的错误码参考了解详细错误原因
  145. e.getStatusCode();
  146. Toast.error(getContext(),"Init Huawei accountAuthService FAILED.");
  147. return;
  148. }
  149. Toast.info(getContext(),"Init Huawei accountAuthService SUCCESS");
  150. if (accountAuthService == null) {
  151. Toast.error(getContext(),"获取不到账号信息");
  152. return;
  153. }
  154. // 调用静默登录接口。
  155. // 如果华为系统帐号已经登录,并且已经授权,会登录成功;
  156. // 否则静默登录失败,需要在失败监听中,显式地调用前台登录授权接口,完成登录授权。
  157. Task<AuthAccount> taskSilentSignIn = accountAuthService.silentSignIn();
  158. // Task<AuthAccount> taskSilentSignIn = accountAuthService.silentSignIn();
  159. Toast.info(getContext(),"SilentSign START.");
  160. // 添加静默登录成功处理监听
  161. taskSilentSignIn.addOnSuccessListener(authAccount -> updateUI(authAccount));
  162. // 添加静默登录失败监听
  163. taskSilentSignIn.addOnFailureListener(e -> {
  164. if (e instanceof ApiException) {
  165. ApiException apiException = (ApiException) e;
  166. Toast.error(getContext(),"SilentSignIn FAILED, status code: " + apiException.getStatusCode() + ". Need to foreground sign in" + "\r\n" + apiException.getStatusMessage()
  167. + "\r\n" + apiException.getMessage() + "\r\n" + apiException.getCause());
  168. // 静默登录失败,显式地调用前台登录授权接口,完成登录授权。
  169. Task<AuthAccount> taskSignIn = accountAuthService.signIn();
  170. Toast.info(getContext(),"SignIn foreground START.");
  171. if (taskSignIn == null) {
  172. Toast.info(getContext(),"SignIn foreground task is null.");
  173. return;
  174. }
  175. taskSignIn.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
  176. @Override
  177. public void onSuccess(AuthAccount result) {
  178. Toast.info(getContext(),"SignIn foreground SUCCESS.");
  179. updateUI(result);
  180. }
  181. });
  182. taskSignIn.addOnFailureListener(new OnFailureListener() {
  183. @Override
  184. public void onFailure(Exception e) {
  185. Toast.info(getContext(),"SignIn foreground FAILED.");
  186. if (e instanceof ApiException) {
  187. ApiException apiException = (ApiException) e;
  188. // 登录失败,status code标识了失败的原因,请参考API中的错误码参考了解详细错误原因
  189. apiException.getStatusCode();
  190. Toast.info(getContext(),"SignIn foreground FAILED. status code: "
  191. + apiException.getStatusCode()
  192. + ".");
  193. if (CommonConstant.RETCODE.SIGN_IN_CANCELLED == apiException.getStatusCode()) {
  194. Toast.info(getContext(),"Error message: User click CANCEL or Return, user cancel login in.");
  195. }
  196. }
  197. }
  198. });
  199. }
  200. });
  201. }
  202. private void updateUI(AuthAccount authAccount) {
  203. Toast.info(getContext(),authAccount.getOpenId() + " : " + authAccount.getUnionId());
  204. }
  205. /**
  206. * 设置全屏显示
  207. */
  208. private void setFullScreen() {
  209. try {
  210. Window window = getWindow();
  211. if (window != null) {
  212. WindowManager.LayoutConfig layoutConfig = window.getLayoutConfig().orElse(null);
  213. if (layoutConfig == null) {
  214. layoutConfig = new WindowManager.LayoutConfig();
  215. }
  216. layoutConfig.type = WindowManager.LayoutConfig.MARK_FULL_SCREEN;
  217. window.setLayoutConfig(layoutConfig);
  218. }
  219. } catch (Exception e) {
  220. Log.error("设置全屏失败: " + e.getMessage());
  221. }
  222. }
  223. /**
  224. * 初始化组件
  225. */
  226. private void initComponents() {
  227. // 初始化PageSlider
  228. pageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
  229. if (pageSlider != null) {
  230. // 创建PageSliderProvider
  231. pageSliderProvider = new PageSliderProvider() {
  232. private List<Component> pages = new ArrayList<>();
  233. @Override
  234. public int getCount() {
  235. return 3; // 三个页面:我的、找车位、预约停车
  236. }
  237. @Override
  238. public Object createPageInContainer(ComponentContainer componentContainer, int position) {
  239. Component page = null;
  240. try {
  241. switch (position) {
  242. case 0: // 我的
  243. page = LayoutScatter.getInstance(MainAbilitySlice.this)
  244. .parse(ResourceTable.Layout_layout_my, null, false);
  245. break;
  246. case 1: // 找车位
  247. page = LayoutScatter.getInstance(MainAbilitySlice.this)
  248. .parse(ResourceTable.Layout_layout_find_parking, null, false);
  249. break;
  250. case 2: // 预约停车
  251. page = LayoutScatter.getInstance(MainAbilitySlice.this)
  252. .parse(ResourceTable.Layout_layout_reserve_parking, null, false);
  253. break;
  254. }
  255. if (page != null) {
  256. componentContainer.addComponent(page);
  257. pages.add(page);
  258. }
  259. } catch (Exception e) {
  260. Log.error("创建页面失败: " + e.getMessage());
  261. e.printStackTrace();
  262. }
  263. return page;
  264. }
  265. @Override
  266. public void destroyPageFromContainer(ComponentContainer componentContainer, int position, Object object) {
  267. if (object instanceof Component) {
  268. componentContainer.removeComponent((Component) object);
  269. pages.remove(object);
  270. }
  271. }
  272. @Override
  273. public boolean isPageMatchToObject(Component component, Object object) {
  274. return component == object;
  275. }
  276. };
  277. pageSlider.setProvider(pageSliderProvider);
  278. // 默认显示找车位页面(索引1)
  279. pageSlider.setCurrentPage(1);
  280. // 添加页面切换监听
  281. pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
  282. @Override
  283. public void onPageChosen(int index) {
  284. // 页面切换完成
  285. currentTab = index;
  286. updateBottomNavState(index);
  287. Log.info("切换到页面: " + index);
  288. }
  289. @Override
  290. public void onPageSliding(int state, float v, int index) {
  291. }
  292. @Override
  293. public void onPageSlideStateChanged(int state) {
  294. // 滑动状态变化
  295. }
  296. });
  297. }
  298. // 初始化底部导航栏
  299. initBottomNavigation();
  300. }
  301. /**
  302. * 初始化底部导航栏
  303. */
  304. private void initBottomNavigation() {
  305. navMy = findComponentById(ResourceTable.Id_nav_my);
  306. navFindParking = findComponentById(ResourceTable.Id_nav_find_parking);
  307. navReserveParking = findComponentById(ResourceTable.Id_nav_reserve_parking);
  308. navCurrentLocation = findComponentById(ResourceTable.Id_nav_current_location);
  309. textMy = findComponentById(ResourceTable.Id_text_my);
  310. textPark = findComponentById(ResourceTable.Id_text_park);
  311. textFee = findComponentById(ResourceTable.Id_text_fee);
  312. iconPark = findComponentById(ResourceTable.Id_icon_park);
  313. iconPark1 = findComponentById(ResourceTable.Id_icon_park_1);
  314. iconMy = findComponentById(ResourceTable.Id_icon_my);
  315. iconMy1 = findComponentById(ResourceTable.Id_icon_my_1);
  316. iconFee = findComponentById(ResourceTable.Id_icon_fee);
  317. iconFee1 = findComponentById(ResourceTable.Id_icon_fee_1);
  318. // 设置点击事件
  319. if (navMy != null) {
  320. navMy.setClickedListener(component -> switchToPage(0));
  321. }
  322. if (navFindParking != null) {
  323. navFindParking.setClickedListener(component -> switchToPage(1));
  324. }
  325. if (navReserveParking != null) {
  326. navReserveParking.setClickedListener(component -> switchToPage(2));
  327. }
  328. if (navCurrentLocation != null) {
  329. navCurrentLocation.setClickedListener(component -> {
  330. Log.info("点击了当前位置按钮");
  331. locateCurrentPosition();
  332. });
  333. }
  334. // 默认选中找车位
  335. updateBottomNavState(1);
  336. }
  337. /**
  338. * 切换到指定页面
  339. */
  340. private void switchToPage(int index) {
  341. if (pageSlider != null && index >= 0 && index < 3) {
  342. pageSlider.setCurrentPage(index);
  343. }
  344. }
  345. /**
  346. * 更新底部导航栏状态
  347. */
  348. private void updateBottomNavState(int index) {
  349. // 重置所有导航项样式
  350. Color grayColor = new Color(Color.getIntColor("#FF666666"));
  351. Color blueColor = new Color(Color.getIntColor("#FA6332"));
  352. if (textMy != null) {
  353. textMy.setTextColor(grayColor);
  354. }
  355. if (textPark != null) {
  356. textPark.setTextColor(grayColor);
  357. }
  358. if (textFee != null) {
  359. textFee.setTextColor(grayColor);
  360. }
  361. iconPark.setImageAndDecodeBounds(ResourceTable.Media_park);
  362. iconMy.setImageAndDecodeBounds(ResourceTable.Media_my);
  363. // iconReserveParking.setImageAndDecodeBounds(ResourceTable.Media_fee);
  364. // 设置选中状态
  365. switch (index) {
  366. case 0: // 我的
  367. textMy.setTextColor(blueColor);
  368. iconMy.setImageAndDecodeBounds(ResourceTable.Media_my_1);
  369. iconMy.setVisibility(Component.HIDE);
  370. iconMy1.setVisibility(Component.VISIBLE);
  371. iconFee.setVisibility(Component.VISIBLE);
  372. iconFee1.setVisibility(Component.HIDE);
  373. iconPark.setVisibility(Component.VISIBLE);
  374. iconPark1.setVisibility(Component.HIDE);
  375. break;
  376. case 1: // 找车位
  377. textPark.setTextColor(blueColor);
  378. iconPark.setImageAndDecodeBounds(ResourceTable.Media_park_1);
  379. iconMy.setVisibility(Component.VISIBLE);
  380. iconMy1.setVisibility(Component.HIDE);
  381. iconFee.setVisibility(Component.VISIBLE);
  382. iconFee1.setVisibility(Component.HIDE);
  383. iconPark.setVisibility(Component.HIDE);
  384. iconPark1.setVisibility(Component.VISIBLE);
  385. break;
  386. case 2: // 预约停车
  387. textFee.setTextColor(blueColor);
  388. iconMy.setVisibility(Component.VISIBLE);
  389. iconMy1.setVisibility(Component.HIDE);
  390. iconFee.setVisibility(Component.HIDE);
  391. iconFee1.setVisibility(Component.VISIBLE);
  392. iconPark.setVisibility(Component.VISIBLE);
  393. iconPark1.setVisibility(Component.HIDE);
  394. break;
  395. }
  396. }
  397. /**
  398. * 初始化地图 - 完全按照 MarkerDemo 的方式
  399. */
  400. private void initMap() {
  401. try {
  402. // Declaring and Initializing the HuaweiMapOptions Object - 完全按照 MarkerDemo
  403. HuaweiMapOptions huaweiMapOptions = new HuaweiMapOptions();
  404. // Initialize Camera Properties
  405. CameraPosition cameraPosition =
  406. new CameraPosition(new LatLng(48.893478, 2.334595), 6, 0, 0);
  407. huaweiMapOptions
  408. // Set Camera Properties
  409. .camera(cameraPosition)
  410. // Enables or disables the zoom function. By default, the zoom function is enabled.
  411. .zoomControlsEnabled(false)
  412. // Sets whether the compass is available. The compass is available by default.
  413. .compassEnabled(true)
  414. // Specifies whether the zoom gesture is available. By default, the zoom gesture is available.
  415. .zoomGesturesEnabled(true)
  416. // Specifies whether to enable the scrolling gesture. By default, the scrolling gesture is enabled.
  417. .scrollGesturesEnabled(true)
  418. // Specifies whether the rotation gesture is available. By default, the rotation gesture is available.
  419. .rotateGesturesEnabled(false)
  420. // Specifies whether the tilt gesture is available. By default, the tilt gesture is available.
  421. .tiltGesturesEnabled(true)
  422. // Sets whether the map is in lite mode. The default value is No.
  423. .liteMode(false)
  424. // Set Preference Minimum Zoom Level
  425. .minZoomPreference(3)
  426. // Set Preference Maximum Zoom Level
  427. .maxZoomPreference(13);
  428. if (true) return;
  429. // Initialize MapView Object. - 完全按照 MarkerDemo
  430. mMapView = new MapView(this, huaweiMapOptions);
  431. mMapView.onCreate();
  432. // Obtains the HuaweiMap object. - 完全按照 MarkerDemo
  433. mMapView.getMapAsync(huaweiMap -> {
  434. mHuaweiMap = huaweiMap;
  435. // If mHuaweiMap is null, the program stops running. - 完全按照 MarkerDemo
  436. if (null == mHuaweiMap) {
  437. Log.error("mHuaweiMap 为 null");
  438. return;
  439. }
  440. Log.info("地图已就绪,开始获取定位");
  441. mHuaweiMap.setOnMapClickListener(new OnMapClickListener() {
  442. @Override
  443. public void onMapClick(LatLng latLng) {
  444. new ToastDialog(CommonContext.getContext()).setText("onMapClick ").show();
  445. }
  446. });
  447. // If mMarker is not null, remove it from the map and then set it to null. - 完全按照 MarkerDemo
  448. if (null != mMarker) {
  449. mMarker.remove();
  450. mMarker = null;
  451. }
  452. // Add a marker to the map. - 完全按照 MarkerDemo
  453. MarkerOptions options = new MarkerOptions()
  454. .position(new LatLng(48.893478, 2.334595))
  455. .title("Hello Huawei Map")
  456. .snippet("This is a snippet!");
  457. mMarker = mHuaweiMap.addMarker(options);
  458. // Set the marker title. - 完全按照 MarkerDemo
  459. if (mMarker != null) {
  460. mMarker.setTitle("Marker title");
  461. }
  462. // Set whether the marker can be dragged. - 完全按照 MarkerDemo
  463. if (mMarker != null) {
  464. mMarker.setDraggable(true);
  465. }
  466. // Set the marker anchor point. - 完全按照 MarkerDemo
  467. if (mMarker != null) {
  468. mMarker.setMarkerAnchor(0.9F, 0.9F);
  469. }
  470. // Customizing the Marker Icon - 完全按照 MarkerDemo
  471. addCustomMarker();
  472. mHuaweiMap.setOnMarkerClickListener(new OnMarkerClickListener() {
  473. @Override
  474. public boolean onMarkerClick(Marker marker) {
  475. new ToastDialog(CommonContext.getContext()).setText("onMarkerClick: " + marker.getTitle()).show();
  476. return false;
  477. }
  478. });
  479. mHuaweiMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
  480. @Override
  481. public void onInfoWindowClick(Marker marker) {
  482. new ToastDialog(CommonContext.getContext()).setText("onInfoWindowClick:").show();
  483. }
  484. });
  485. // 地图就绪后,自动获取当前位置
  486. if (locator != null && locatorCallback != null) {
  487. locateCurrentPosition();
  488. }
  489. });
  490. // ComponentContainer.LayoutConfig config = new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
  491. // PositionLayout myLayout = new PositionLayout(this);
  492. // myLayout.setLayoutConfig(config);
  493. PositionLayout myLayout = findComponentById(ResourceTable.Id_main_body);
  494. ShapeElement element = new ShapeElement();
  495. element.setShape(ShapeElement.RECTANGLE);
  496. element.setRgbColor(new RgbColor(255, 255, 255));
  497. // 加载MapView
  498. myLayout.addComponent(mMapView);
  499. } catch (Exception e) {
  500. Log.error("初始化地图失败: " + e.getMessage());
  501. e.printStackTrace();
  502. }
  503. }
  504. /**
  505. * addCustomMarker - 完全按照 MarkerDemo
  506. */
  507. private void addCustomMarker() {
  508. Resource resource = null;
  509. try {
  510. resource = getResourceManager().getResource(ResourceTable.Media_icon);
  511. } catch (IOException e) {
  512. e.printStackTrace();
  513. } catch (NotExistException e) {
  514. e.printStackTrace();
  515. }
  516. if (resource != null && mHuaweiMap != null) {
  517. mHuaweiMap.addMarker(new MarkerOptions()
  518. .position(new LatLng(47.8333, 2.8333))
  519. .icon(resource));
  520. }
  521. }
  522. /**
  523. * 设置事件监听
  524. */
  525. private void setupListeners() {
  526. // 事件监听已在initBottomNavigation中设置
  527. }
  528. /**
  529. * 初始化定位服务
  530. */
  531. private void initLocation() {
  532. try {
  533. locator = new Locator(this);
  534. locatorCallback = new LocatorCallback() {
  535. @Override
  536. public void onLocationReport(Location location) {
  537. // 保存当前位置坐标
  538. currentLocation = location;
  539. double latitude = location.getLatitude();
  540. double longitude = location.getLongitude();
  541. Log.info("定位成功: " + latitude + ", " + longitude);
  542. // 将坐标传递给地图
  543. updateMapWithLocation(location);
  544. }
  545. @Override
  546. public void onStatusChanged(int type) {
  547. Log.info("定位状态变化: " + type);
  548. }
  549. @Override
  550. public void onErrorReport(int errorCode) {
  551. Log.error("定位错误: " + errorCode);
  552. new ToastDialog(CommonContext.getContext())
  553. .setText("定位失败,错误码: " + errorCode)
  554. .show();
  555. }
  556. };
  557. } catch (Exception e) {
  558. Log.error("初始化定位服务失败: " + e.getMessage());
  559. }
  560. }
  561. /**
  562. * 定位到当前位置
  563. */
  564. private void locateCurrentPosition() {
  565. if (locator == null || locatorCallback == null) {
  566. Log.error("定位服务未初始化");
  567. return;
  568. }
  569. try {
  570. // 请求定位
  571. RequestParam requestParam = new RequestParam(RequestParam.PRIORITY_ACCURACY, 0, 0);
  572. locator.startLocating(requestParam, locatorCallback);
  573. Log.info("开始定位...");
  574. } catch (Exception e) {
  575. Log.error("定位失败: " + e.getMessage());
  576. }
  577. }
  578. /**
  579. * 将定位坐标传递给地图并更新地图显示
  580. */
  581. private void updateMapWithLocation(Location location) {
  582. if (mHuaweiMap == null) {
  583. Log.warn("地图未初始化完成,等待地图就绪");
  584. return;
  585. }
  586. try {
  587. double latitude = location.getLatitude();
  588. double longitude = location.getLongitude();
  589. Log.info("更新地图位置: " + latitude + ", " + longitude);
  590. // 创建坐标点
  591. LatLng latLng = new LatLng(latitude, longitude);
  592. // 移除旧的当前位置标记
  593. if (currentLocationMarker != null) {
  594. currentLocationMarker.remove();
  595. currentLocationMarker = null;
  596. }
  597. // 在地图上添加当前位置标记
  598. MarkerOptions currentLocationOptions = new MarkerOptions()
  599. .position(latLng)
  600. .title("当前位置")
  601. .snippet("纬度: " + latitude + ", 经度: " + longitude);
  602. currentLocationMarker = mHuaweiMap.addMarker(currentLocationOptions);
  603. // Method 8: Set the center point and zoom level of the camera. - 完全按照示例代码
  604. float zoom = 15.0f;
  605. CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
  606. // move camera - 完全按照示例代码
  607. mHuaweiMap.moveCamera(cameraUpdate);
  608. Log.info("地图已更新到当前位置");
  609. // 显示提示
  610. new ToastDialog(CommonContext.getContext())
  611. .setText("已定位到当前位置")
  612. .show();
  613. } catch (Exception e) {
  614. Log.error("更新地图位置失败: " + e.getMessage());
  615. e.printStackTrace();
  616. }
  617. }
  618. /**
  619. * 移动地图到当前位置 - 完全按照 MapViewCameraDemo 的方式
  620. */
  621. private void moveToCurrentLocation(Location location) {
  622. updateMapWithLocation(location);
  623. }
  624. // 生命周期管理 - 完全按照示例代码 MapViewDemo.java 的方式
  625. @Override
  626. protected void onActive() {
  627. super.onActive();
  628. if (mMapView != null) {
  629. mMapView.onResume();
  630. }
  631. }
  632. @Override
  633. protected void onInactive() {
  634. super.onInactive();
  635. if (mMapView != null) {
  636. mMapView.onPause();
  637. }
  638. }
  639. @Override
  640. protected void onBackground() {
  641. super.onBackground();
  642. if (mMapView != null) {
  643. mMapView.onStop();
  644. }
  645. }
  646. @Override
  647. protected void onForeground(Intent intent) {
  648. super.onForeground(intent);
  649. if (mMapView != null) {
  650. mMapView.onStart();
  651. }
  652. }
  653. @Override
  654. protected void onStop() {
  655. super.onStop();
  656. // 停止定位
  657. if (locator != null && locatorCallback != null) {
  658. try {
  659. locator.stopLocating(locatorCallback);
  660. } catch (Exception e) {
  661. Log.error("停止定位失败: " + e.getMessage());
  662. }
  663. }
  664. // 销毁地图 - 完全按照示例代码
  665. if (mMapView != null) {
  666. mMapView.onDestroy();
  667. }
  668. if (dataAbilityHelper != null) {
  669. }
  670. dataAbilityHelper.unregisterObserver(SystemSettings.getUri(SystemSettings.Date.TIME_FORMAT), dataAbilityObserver);
  671. }
  672. }