diff --git a/BiuBike/.idea/caches/build_file_checksums.ser b/BiuBike/.idea/caches/build_file_checksums.ser index 68f53be..5274c13 100644 Binary files a/BiuBike/.idea/caches/build_file_checksums.ser and b/BiuBike/.idea/caches/build_file_checksums.ser differ diff --git a/BiuBike/app/build.gradle b/BiuBike/app/build.gradle index 0c846ed..90162d8 100644 --- a/BiuBike/app/build.gradle +++ b/BiuBike/app/build.gradle @@ -74,17 +74,10 @@ dependencies { androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' - implementation files('libs/baidumapapi_base_v4_1_1.jar') - implementation files('libs/baidumapapi_map_v4_1_1.jar') - implementation files('libs/nineoldandroids-2.4.0.jar') - implementation files('libs/baidumapapi_util_v4_1_1.jar') - implementation files('libs/gson-2.2.1.jar') - implementation files('libs/BaiduNaviSDK_3.2.0.jar') - implementation files('libs/Msc.jar') - implementation files('libs/Msc.jar') implementation 'com.github.tbruyelle:rxpermissions:0.10.2' implementation 'com.jcodecraeer:xrecyclerview:1.5.9' implementation 'org.greenrobot:eventbus:3.1.1' + implementation 'com.google.code.gson:gson:2.2.1' } diff --git a/BiuBike/app/libs/BaiduLBS_Android.jar b/BiuBike/app/libs/BaiduLBS_Android.jar new file mode 100644 index 0000000..03b8f77 Binary files /dev/null and b/BiuBike/app/libs/BaiduLBS_Android.jar differ diff --git a/BiuBike/app/libs/BaiduNaviSDK_3.2.0.jar b/BiuBike/app/libs/BaiduNaviSDK_3.2.0.jar deleted file mode 100755 index 05a87da..0000000 Binary files a/BiuBike/app/libs/BaiduNaviSDK_3.2.0.jar and /dev/null differ diff --git a/BiuBike/app/libs/BaiduTraceSDK_v3_1_3.jar b/BiuBike/app/libs/BaiduTraceSDK_v3_1_3.jar new file mode 100644 index 0000000..2fd5cb2 Binary files /dev/null and b/BiuBike/app/libs/BaiduTraceSDK_v3_1_3.jar differ diff --git a/BiuBike/app/libs/IndoorscapeAlbumPlugin.jar b/BiuBike/app/libs/IndoorscapeAlbumPlugin.jar new file mode 100644 index 0000000..6c1b773 Binary files /dev/null and b/BiuBike/app/libs/IndoorscapeAlbumPlugin.jar differ diff --git a/BiuBike/app/libs/Msc.jar b/BiuBike/app/libs/Msc.jar deleted file mode 100644 index ebdce75..0000000 Binary files a/BiuBike/app/libs/Msc.jar and /dev/null differ diff --git a/BiuBike/app/libs/SecurityEnvSDK-release-1.1.0.jar b/BiuBike/app/libs/SecurityEnvSDK-release-1.1.0.jar new file mode 100644 index 0000000..2b80819 Binary files /dev/null and b/BiuBike/app/libs/SecurityEnvSDK-release-1.1.0.jar differ diff --git a/BiuBike/app/libs/baidumapapi_base_v4_1_1.jar b/BiuBike/app/libs/baidumapapi_base_v4_1_1.jar deleted file mode 100644 index bf8a592..0000000 Binary files a/BiuBike/app/libs/baidumapapi_base_v4_1_1.jar and /dev/null differ diff --git a/BiuBike/app/libs/baidumapapi_map_v4_1_1.jar b/BiuBike/app/libs/baidumapapi_map_v4_1_1.jar deleted file mode 100644 index b0dce87..0000000 Binary files a/BiuBike/app/libs/baidumapapi_map_v4_1_1.jar and /dev/null differ diff --git a/BiuBike/app/libs/baidumapapi_search_v4_1_1.jar b/BiuBike/app/libs/baidumapapi_search_v4_1_1.jar deleted file mode 100644 index 02862fb..0000000 Binary files a/BiuBike/app/libs/baidumapapi_search_v4_1_1.jar and /dev/null differ diff --git a/BiuBike/app/libs/baidumapapi_util_v4_1_1.jar b/BiuBike/app/libs/baidumapapi_util_v4_1_1.jar deleted file mode 100644 index 7ff6517..0000000 Binary files a/BiuBike/app/libs/baidumapapi_util_v4_1_1.jar and /dev/null differ diff --git a/BiuBike/app/libs/bos-android-sdk-1.0.3.jar b/BiuBike/app/libs/bos-android-sdk-1.0.3.jar new file mode 100755 index 0000000..75145e2 Binary files /dev/null and b/BiuBike/app/libs/bos-android-sdk-1.0.3.jar differ diff --git a/BiuBike/app/libs/gson-2.2.1.jar b/BiuBike/app/libs/gson-2.2.1.jar deleted file mode 100755 index 93ac6d7..0000000 Binary files a/BiuBike/app/libs/gson-2.2.1.jar and /dev/null differ diff --git a/BiuBike/app/libs/locSDK_6.13.jar b/BiuBike/app/libs/locSDK_6.13.jar deleted file mode 100755 index fa7dc1b..0000000 Binary files a/BiuBike/app/libs/locSDK_6.13.jar and /dev/null differ diff --git a/BiuBike/app/libs/okhttp-3.8.1.jar b/BiuBike/app/libs/okhttp-3.8.1.jar new file mode 100755 index 0000000..97b1fd4 Binary files /dev/null and b/BiuBike/app/libs/okhttp-3.8.1.jar differ diff --git a/BiuBike/app/libs/okio-1.13.0.jar b/BiuBike/app/libs/okio-1.13.0.jar new file mode 100755 index 0000000..02c302f Binary files /dev/null and b/BiuBike/app/libs/okio-1.13.0.jar differ diff --git a/BiuBike/app/libs/permission-lib.jar b/BiuBike/app/libs/permission-lib.jar deleted file mode 100644 index 8e133a3..0000000 Binary files a/BiuBike/app/libs/permission-lib.jar and /dev/null differ diff --git a/BiuBike/app/libs/utdid4all-1.1.5.3_proguard.jar b/BiuBike/app/libs/utdid4all-1.1.5.3_proguard.jar new file mode 100644 index 0000000..5eed5be Binary files /dev/null and b/BiuBike/app/libs/utdid4all-1.1.5.3_proguard.jar differ diff --git a/BiuBike/app/src/main/AndroidManifest.xml b/BiuBike/app/src/main/AndroidManifest.xml index 0aa92ec..8d999a6 100644 --- a/BiuBike/app/src/main/AndroidManifest.xml +++ b/BiuBike/app/src/main/AndroidManifest.xml @@ -18,9 +18,20 @@ + + + + + + + + + + + @@ -43,7 +54,8 @@ android:label="@string/bybike" android:networkSecurityConfig="@xml/network_security_config" android:supportsRtl="true" - android:theme="@style/AppThemeDefault"> + android:theme="@style/AppThemeDefault" + tools:ignore="GoogleAppIndexingWarning"> @@ -53,52 +65,52 @@ - + - - - - - - - - - - - - - - - - + android:name=".activity.WalletActivity" + android:screenOrientation="portrait" /> + + + + - - + android:process=":remote" /> + pointsList; + + private OnTrackListener trackDistanceListener = null; + private OnTrackListener trackHistoryListener = null; + private OnGetRoutePlanResultListener bikeRouteListener; + //轨迹监听器(用于接收纠偏后实时位置回调) + private OnTrackListener trackListener = null; + //Entity监听器(用于接收实时定位回调) + private OnEntityListener entityListener = null; + private OnTraceListener mTraceListener = null; + //实时定位任务 + private RealTimeHandler realTimeHandler = new RealTimeHandler(); + private RealTimeLocRunnable realTimeLocRunnable = null; + private boolean isRealTimeRunning = true; + //地图工具 + private MapUtil mapUtil = null; + //轨迹点集合 + private List trackPoints; + //查询周期(单位:秒) + private int queryInterval = 3000; + private String showTime; + private String showDistance; + private String showPrice; + private boolean isGetLocation = false; + private Notification notification; + private RemoteViews contentView; + private NotificationManager notificationManager; + private RoutePlanSearch mSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - SDKInitializer.initialize(getApplicationContext());//在Application的onCreate()不行,必须在activity的onCreate()中 setContentView(R.layout.activity_main); - EventBus.getDefault().register(this); - initMap(); + initView(); - isServiceLive = Utils.isServiceWork(this, "com.biubike.service.RouteService"); - if (isServiceLive) - beginService(); + initNotification(); + initMap(); FragmentManager fm = getSupportFragmentManager(); LeftMenuFragment mMenuFragment = (LeftMenuFragment) fm.findFragmentById(R.id.id_container_menu); @@ -136,14 +168,46 @@ protected void onCreate(Bundle savedInstanceState) { if (mMenuFragment == null) { fm.beginTransaction().add(R.id.id_container_menu, mMenuFragment = new LeftMenuFragment()).commit(); } - pointsList = new ArrayList<>(); -// mLeftDrawerLayout.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { -// @Override -// public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) { -// return windowInsets.consumeSystemWindowInsets(); -// } -// }); + trackPoints = new ArrayList<>(); + if (Utils.isServiceWork(this, "com.baidu.trace.LBSTraceService")) { + beginService(); + } + } + + private void initView() { + current_addr = findViewById(R.id.current_addr); + llBikeLayout = findViewById(R.id.ll_bike_layout); + llBikeDetail = findViewById(R.id.ll_bike_detail); + bike_time = findViewById(R.id.bike_time); + bike_distance = findViewById(R.id.bike_distance); + bike_price = findViewById(R.id.bike_price); + textview_time = findViewById(R.id.textview_time); + textview_distance = findViewById(R.id.textview_distance); + textview_price = findViewById(R.id.textview_price); + unlock = findViewById(R.id.unlock); + divider = findViewById(R.id.divider); + llPrice = findViewById(R.id.ll_bike_price); + prompt = findViewById(R.id.prompt); + mLeftDrawerLayout = findViewById(R.id.id_drawerlayout); + shadowView = findViewById(R.id.shadow); + menu_icon = findViewById(R.id.menu_icon); + menu_icon.setOnClickListener(this); + shadowView.setOnClickListener(this); + btn_locale = findViewById(R.id.btn_locale); + btn_refresh = findViewById(R.id.btn_refresh); + end_route = findViewById(R.id.end_route); + title = findViewById(R.id.title); + book_bt = findViewById(R.id.book_bt); + book_bt.setOnClickListener(this); + btn_locale.setOnClickListener(this); + btn_refresh.setOnClickListener(this); + end_route.setOnClickListener(this); + + dragLocationIcon = BitmapDescriptorFactory.fromResource(R.mipmap.drag_location); + bikeIcon = BitmapDescriptorFactory.fromResource(R.mipmap.bike_icon); + startBmp = BitmapDescriptorFactory.fromResource(R.mipmap.route_start); + initListener(); } private void initMap() { @@ -153,13 +217,18 @@ private void initMap() { mMapView.showZoomControls(true); //去掉百度Logo的小技巧 View child = mMapView.getChildAt(1); - if (child != null && (child instanceof ImageView)){ + if ((child instanceof ImageView)) { child.setVisibility(View.INVISIBLE); } mBaiduMap = mMapView.getMap(); + mMapView.setOnClickListener(this); // 开启定位图层 mBaiduMap.setMyLocationEnabled(true); // 定位初始化 + mBaiduMap.setOnMapStatusChangeListener(changeListener); + mapUtil = MapUtil.getInstance(); + mapUtil.init(mMapView); + BitmapUtil.init(); mlocationClient = new LocationClient(this); myListener = new MyLocationListenner(); mlocationClient.registerLocationListener(myListener); @@ -167,26 +236,18 @@ private void initMap() { option.setOpenGps(true); // 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 option.setIsNeedAddress(true);//如想获得具体位置就需要设置为true + option.setIgnoreKillProcess(false); mlocationClient.setLocOption(option); if (!mlocationClient.isStarted()) { mlocationClient.start(); } - mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING; - mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration( - mCurrentMode, true, null)); -// myOrientationListener = new MyOrientationListener(this); -// //通过接口回调来实现实时方向的改变 -// myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() { -// @Override -// public void onOrientationChanged(float x) { -// mCurrentX = x; -// } -// }); -// -// myOrientationListener.start(); - mSearch = RoutePlanSearch.newInstance(); - mSearch.setOnGetRoutePlanResultListener(this); initMarkerClickEvent(); + if (!Utils.isServiceWork(this, "com.baidu.trace.LBSTraceService")) { + getMyLocation(); + } + + mSearch = RoutePlanSearch.newInstance(); + mSearch.setOnGetRoutePlanResultListener(bikeRouteListener); } /** @@ -195,7 +256,7 @@ private void initMap() { * 2、调用mlocationClient.requestLocation() * 3、RouteService中设置了setScanSpan(2000),所以行程中会每隔2s调用一次 */ - public class MyLocationListenner implements BDLocationListener { + public class MyLocationListenner extends BDAbstractLocationListener { @Override public void onReceiveLocation(BDLocation bdLocation) { @@ -203,36 +264,30 @@ public void onReceiveLocation(BDLocation bdLocation) { if (bdLocation == null || mMapView == null) { return; } -// MyLocationData locData = new MyLocationData.Builder() -// .accuracy(bdLocation.getRadius()) -// .direction(mCurrentX)//设定图标方向 // 此处设置开发者获取到的方向信息,顺时针0-360 -// .latitude(bdLocation.getLatitude()) -// .longitude(bdLocation.getLongitude()).build(); -// mBaiduMap.setMyLocationData(locData); - currentLatitude = bdLocation.getLatitude(); - currentLongitude = bdLocation.getLongitude(); + + double currentLatitude = bdLocation.getLatitude(); + double currentLongitude = bdLocation.getLongitude(); current_addr.setText(bdLocation.getAddrStr()); - currentLL = new LatLng(bdLocation.getLatitude(), - bdLocation.getLongitude()); - LocationManager.getInstance().setCurrentLL(currentLL); + currentLatLng = new LatLng(currentLatitude, currentLongitude); + LocationManager.getInstance().setCurrentLL(currentLatLng); LocationManager.getInstance().setAddress(bdLocation.getAddrStr()); - startNodeStr = PlanNode.withLocation(currentLL); - - Log.d("gaolei", "currentLL----------" + currentLL); - //可能会调用多次,而我们下面的逻辑只想第一次进入的时候调用一次,所以要判断一下isFirstLoc - if (isFirstLoc) { - isFirstLoc = false; - MapStatus.Builder builder = new MapStatus.Builder(); - //地图缩放比设置为18 - builder.target(currentLL).zoom(18.0f); - mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); - if (!isServiceLive) { - addOverLayout(currentLatitude, currentLongitude); - } - } + + Log.d("gaolei", "currentLL----------" + currentLatLng); + Log.d("gaolei", "getAddrStr()----------" + bdLocation.getAddrStr()); + mapUtil.setMapZoomStatus(currentLatLng, 18f); + addOverLayout(currentLatLng); + mlocationClient.stop(); + } } + public void getMyLocation() { + isGetLocation = true; + getCurrentLocation(entityListener, trackListener); +// if (!mlocationClient.isStarted()) { +// mlocationClient.requestLocation(); +// } + } public void openMenu() { mLeftDrawerLayout.openDrawer(); @@ -244,51 +299,6 @@ public void closeMenu() { shadowView.setVisibility(View.GONE); } - private void initView() { - current_addr = findViewById(R.id.current_addr); - llBikeLayout = findViewById(R.id.ll_bike_layout); - llBikeDetail = findViewById(R.id.ll_bike_detail); - bike_time = findViewById(R.id.bike_time); - bike_distance = findViewById(R.id.bike_distance); - bike_price = findViewById(R.id.bike_price); - textview_time = findViewById(R.id.textview_time); - textview_distance = findViewById(R.id.textview_distance); - textview_price = findViewById(R.id.textview_price); - unlock = findViewById(R.id.unlock); - divider = findViewById(R.id.divider); - llPrice = findViewById(R.id.ll_bike_price); - - prompt = findViewById(R.id.prompt); - mLeftDrawerLayout = findViewById(R.id.id_drawerlayout); - shadowView = findViewById(R.id.shadow); - menu_icon = findViewById(R.id.menu_icon); - menu_icon.setOnClickListener(this); - shadowView.setOnClickListener(this); - - mBaiduMap.setOnMapStatusChangeListener(changeListener); - btn_locale = findViewById(R.id.btn_locale); - btn_refresh = findViewById(R.id.btn_refresh); - end_route = findViewById(R.id.end_route); - title = findViewById(R.id.title); - book_bt = findViewById(R.id.book_bt); - book_bt.setOnClickListener(this); - btn_locale.setOnClickListener(this); - btn_refresh.setOnClickListener(this); - end_route.setOnClickListener(this); - mMapView.setOnClickListener(this); - dragLocationIcon = BitmapDescriptorFactory.fromResource(R.mipmap.drag_location); - bikeIcon = BitmapDescriptorFactory.fromResource(R.mipmap.bike_icon); - startBmp = BitmapDescriptorFactory.fromResource(R.mipmap.route_start); - } - - public void getMyLocation() { - mlocationClient.requestLocation(); - - LatLng latLng = new LatLng(currentLatitude, currentLongitude); - MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(latLng); - // 移动到某经纬度 - mBaiduMap.animateMapStatus(update); - } @Override public void onClick(View view) { @@ -302,10 +312,9 @@ public void onClick(View view) { case R.id.btn_locale: getMyLocation(); - addOverLayout(currentLatitude, currentLongitude); break; case R.id.btn_refresh: - addOverLayout(changeLatitude, changeLongitude); + addOverLayout(changeLatLng); break; case R.id.end_route: toastDialog(); @@ -321,83 +330,432 @@ public void onClick(View view) { } } - @Override - public void onGetWalkingRouteResult(final WalkingRouteResult result) { - if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) { - Toast.makeText(MainActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show(); - } - if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) { - // 起终点或途经点地址有岐义,通过以下接口获取建议查询信息 - // result.getSuggestAddrInfo() - return; + static class RealTimeHandler extends Handler { + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); } - if (result.error == SearchResult.ERRORNO.NO_ERROR) { - - if (result.getRouteLines().size() > 1) { - nowResultwalk = result; - - MyTransitDlg myTransitDlg = new MyTransitDlg(MainActivity.this, - result.getRouteLines(), - RouteLineAdapter.Type.WALKING_ROUTE); - myTransitDlg.setOnItemInDlgClickLinster(new OnItemInDlgClickListener() { - public void onItemClick(int position) { - routeLine = nowResultwalk.getRouteLines().get(position); - WalkingRouteOverlay overlay = new MyWalkingRouteOverlay(mBaiduMap); - - - routeOverlay = overlay; - //路线查询成功 - try { - overlay.setData(nowResultwalk.getRouteLines().get(position)); - overlay.addToMap(); - overlay.zoomToSpan(); - } catch (Exception e) { - e.printStackTrace(); - Toast.makeText(MainActivity.this, "路径规划异常", Toast.LENGTH_SHORT).show(); + } + + private void initListener() { + + + bikeRouteListener = new OnGetRoutePlanResultListener() { + @Override + public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) { + //创建WalkingRouteOverlay实例 + if (walkingRouteResult.getRouteLines().size() > 0) { + List stepList = walkingRouteResult.getRouteLines().get(0).getAllStep(); + List latLngList = new ArrayList<>(); + for (int i = 0; i < stepList.size(); i++) { + WalkingStep walkingStep = stepList.get(i); + latLngList.addAll(walkingStep.getWayPoints()); + } + mapUtil.drawHistoryTrack(latLngList, SortType.asc, true); + } + } + + @Override + public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) { + + } + + @Override + public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) { + + } + + @Override + public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) { + + } + + @Override + public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) { + + } + + @Override + public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) { + + } + }; + + + trackDistanceListener = new OnTrackListener() { + + @Override + public void onDistanceCallback(DistanceResponse response) { + // 里程回调 + + int totalDistance = (int) response.getDistance(); + + long totalTime = (System.currentTimeMillis() - startTime) / 1000 / 60; + + if (totalDistance > 1000) { + DecimalFormat df = new DecimalFormat("#.##"); + showDistance = df.format((float) totalDistance / 1000) + "千米"; + } else { + showDistance = totalDistance + "米"; + } + if (totalTime > 60) { + showTime = totalTime / 60 + "时" + totalTime % 60 + "分"; + } else { + showTime = totalTime + "分钟"; + } + + int totalPrice = (int) (Math.floor(totalTime / 30) * 1 + 1); + + bike_distance.setText(showDistance); + bike_time.setText(showTime); + showPrice = totalPrice + "元"; + bike_price.setText(showPrice); + Log.d("gaolei", "rideDistance:" + showDistance); + Log.d("gaolei", "minute:" + showTime); + Log.d("gaolei", "(System.currentTimeMillis() - startTime) / 1000 :" + (System.currentTimeMillis() - startTime) / 1000); + Log.d("gaolei", "price:" + showPrice); + startNotifi(showTime, showDistance, showPrice); + } + }; + + trackHistoryListener = new OnTrackListener() { + @Override + public void onHistoryTrackCallback(HistoryTrackResponse response) { + trackPoints.clear(); + // 历史轨迹回调 + List points = response.getTrackPoints(); + if (null != points) { + for (TrackPoint trackPoint : points) { + double lat = trackPoint.getLocation().getLatitude(); + double lng = trackPoint.getLocation().getLongitude(); + if (!TraceUtil.isZeroPoint(lat, lng)) { + trackPoints.add(new LatLng(lat, lng)); } } + } + mapUtil.drawHistoryTrack(trackPoints, SortType.asc, true); + if (points.size() > 1) { + TrackPoint trackPoint = points.get(points.size() - 1); + mapUtil.setCenter(new LatLng(trackPoint.getLocation().latitude, trackPoint.getLocation().longitude)); + } + } + }; + trackListener = new OnTrackListener() { - }); - myTransitDlg.show(); - - } else if (result.getRouteLines().size() == 1) { - // 直接显示 - routeLine = result.getRouteLines().get(0); - int totalDistance = routeLine.getDistance(); - int totalTime = routeLine.getDuration() / 60; - bike_distance.setText(Utils.distanceFormatter(totalDistance)); - bike_time.setText(Utils.timeFormatter(totalTime)); - - WalkingRouteOverlay overlay = new MyWalkingRouteOverlay(mBaiduMap); - routeOverlay = overlay; - overlay.setData(result.getRouteLines().get(0)); - overlay.addToMap(); - overlay.zoomToSpan(); - } else { - Log.d("route result", "结果数<0"); - return; + @Override + public void onLatestPointCallback(LatestPointResponse response) { + if (StatusCodes.SUCCESS != response.getStatus()) { + return; + } + + LatestPoint point = response.getLatestPoint(); + if (null == point || TraceUtil.isZeroPoint(point.getLocation().getLatitude(), point.getLocation() + .getLongitude())) { + return; + } + + currentLatLng = MapUtil.convertTrace2Map(point.getLocation()); + CurrentLocation.locTime = point.getLocTime(); + CurrentLocation.latitude = currentLatLng.latitude; + CurrentLocation.longitude = currentLatLng.longitude; +// trackPoints.add(currentLatLng); +// mapUtil.drawHistoryTrack(trackPoints, SortType.asc); + if (null != mapUtil) { +// Toast.makeText(MainActivity.this, "trackListener:" + currentLatLng.toString(), Toast.LENGTH_LONG).show(); + mapUtil.setCenter(currentLatLng); + } + + + if (isGetLocation) { + showCurrentLocationInfo(currentLatLng); + isGetLocation = false; + } + + } + + }; + + entityListener = new OnEntityListener() { + + @Override + public void onReceiveLocation(TraceLocation location) { + + if (StatusCodes.SUCCESS != location.getStatus() || TraceUtil.isZeroPoint(location.getLatitude(), + location.getLongitude())) { + return; + } + currentLatLng = mapUtil.convertTraceLocation2Map(location); + if (null == currentLatLng) { + return; + } + CurrentLocation.locTime = TraceUtil.toTimeStamp(location.getTime()); + CurrentLocation.latitude = currentLatLng.latitude; + CurrentLocation.longitude = currentLatLng.longitude; + if (null != mapUtil) { + mapUtil.setCenter(currentLatLng); +// Toast.makeText(MainActivity.this, "entityListener:" + currentLatLng.toString(), Toast.LENGTH_LONG).show(); + } + + if (isGetLocation) { + showCurrentLocationInfo(currentLatLng); + isGetLocation = false; + } + } + + }; + + mTraceListener = new OnTraceListener() { + + /** + * 绑定服务回调接口 + * @param errorNo 状态码 + * @param message 消息 + *

+ *

0:成功 
+ *
1:失败
+ */ + @Override + public void onBindServiceCallback(int errorNo, String message) { +// ViewUtil.showToast(MainActivity.this, +// String.format("onBindServiceCallback, errorNo:%d, message:%s ", errorNo, message)); + if (!EagleEyeUtil.get().isTraceStarted) { + startTrace(); + startGather(); + } + } + + /** + * 开启服务回调接口 + * @param errorNo 状态码 + * @param message 消息 + *

+ *

0:成功 
+ *
10000:请求发送失败
+ *
10001:服务开启失败
+ *
10002:参数错误
+ *
10003:网络连接失败
+ *
10004:网络未开启
+ *
10005:服务正在开启
+ *
10006:服务已开启
+ */ + @Override + public void onStartTraceCallback(int errorNo, String message) { + if (StatusCodes.SUCCESS == errorNo || StatusCodes.START_TRACE_NETWORK_CONNECT_FAILED <= errorNo) { + EagleEyeUtil.get().isTraceStarted = true; + SharedPreferences.Editor editor = EagleEyeUtil.get().trackConf.edit(); + editor.putBoolean("is_trace_started", true); + editor.apply(); + EagleEyeUtil.get().registerReceiver(); + } +// Toast.makeText(MainActivity.this, +// String.format("onStartTraceCallback, errorNo:%d, message:%s ", errorNo, message), Toast.LENGTH_SHORT); + } + + /** + * 停止服务回调接口 + * @param errorNo 状态码 + * @param message 消息 + *

+ *

0:成功
+ *
11000:请求发送失败
+ *
11001:服务停止失败
+ *
11002:服务未开启
+ *
11003:服务正在停止
+ */ + @Override + public void onStopTraceCallback(int errorNo, String message) { + if (StatusCodes.SUCCESS == errorNo || StatusCodes.CACHE_TRACK_NOT_UPLOAD == errorNo) { + EagleEyeUtil.get().isTraceStarted = false; + EagleEyeUtil.get().isGatherStarted = false; + // 停止成功后,直接移除is_trace_started记录(便于区分用户没有停止服务,直接杀死进程的情况) + SharedPreferences.Editor editor = EagleEyeUtil.get().trackConf.edit(); + editor.remove("is_trace_started"); + editor.remove("is_gather_started"); + editor.apply(); + EagleEyeUtil.get().unregisterPowerReceiver(); + } +// ViewUtil.showToast(MainActivity.this, +// String.format("onStopTraceCallback, errorNo:%d, message:%s ", errorNo, message)); + } + + /** + * 开启采集回调接口 + * @param errorNo 状态码 + * @param message 消息 + *

+ *

0:成功
+ *
12000:请求发送失败
+ *
12001:采集开启失败
+ *
12002:服务未开启
+ */ + @Override + public void onStartGatherCallback(int errorNo, String message) { + if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STARTED == errorNo) { + EagleEyeUtil.get().isGatherStarted = true; + SharedPreferences.Editor editor = EagleEyeUtil.get().trackConf.edit(); + editor.putBoolean("is_gather_started", true); + editor.apply(); + } +// ViewUtil.showToast(MainActivity.this, +// String.format("onStartGatherCallback, errorNo:%d, message:%s ", errorNo, message)); } + + /** + * 停止采集回调接口 + * @param errorNo 状态码 + * @param message 消息 + *

+ *

0:成功
+ *
13000:请求发送失败
+ *
13001:采集停止失败
+ *
13002:服务未开启
+ */ + @Override + public void onStopGatherCallback(int errorNo, String message) { + if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STOPPED == errorNo) { + EagleEyeUtil.get().isGatherStarted = false; + SharedPreferences.Editor editor = EagleEyeUtil.get().trackConf.edit(); + editor.remove("is_gather_started"); + editor.apply(); + } +// ViewUtil.showToast(MainActivity.this, +// String.format("onStopGatherCallback, errorNo:%d, message:%s ", errorNo, message)); + } + + /** + * 推送消息回调接口 + * + * @param messageType 状态码 + * @param pushMessage 消息 + *

+ *

0x01:配置下发
+ *
0x02:语音消息
+ *
0x03:服务端围栏报警消息
+ *
0x04:本地围栏报警消息
+ *
0x05~0x40:系统预留
+ *
0x41~0xFF:开发者自定义
+ */ + @Override + public void onPushCallback(byte messageType, PushMessage pushMessage) { +// if (messageType < 0x03 || messageType > 0x04) { +// ViewUtil.showToast(MainActivity.this, pushMessage.getMessage()); +// return; +// } +// FenceAlarmPushInfo alarmPushInfo = pushMessage.getFenceAlarmPushInfo(); +// if (null == alarmPushInfo) { +// ViewUtil.showToast(MainActivity.this, +// String.format("onPushCallback, messageType:%d, messageContent:%s ", messageType, +// pushMessage)); +// return; +// } +// StringBuffer alarmInfo = new StringBuffer(); +// alarmInfo.append("您于") +// .append(TraceUtil.getHMS(alarmPushInfo.getCurrentPoint().getLocTime() * 1000)) +// .append(alarmPushInfo.getMonitoredAction() == MonitoredAction.enter ? "进入" : "离开") +// .append(messageType == 0x03 ? "云端" : "本地") +// .append("围栏:").append(alarmPushInfo.getFenceName()); +// +// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) { +// Notification notification = new Notification.Builder(trackApp) +// .setContentTitle(getResources().getString(R.string.alarm_push_title)) +// .setContentText(alarmInfo.toString()) +// .setSmallIcon(R.mipmap.icon_app) +// .setWhen(System.currentTimeMillis()).build(); +// notificationManager.notify(notifyId++, notification); +// } + } + + @Override + public void onInitBOSCallback(int errorNo, String message) { +// ViewUtil.showToast(MainActivity.this, +// String.format("onInitBOSCallback, errorNo:%d, message:%s ", errorNo, message)); + } + }; + + + } + + private void showCurrentLocationInfo(LatLng latLng) { + Geocoder geocoder = new Geocoder(MainActivity.this); + try { + List
addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); + if (addressList.size() > 0) { + current_addr.setText(addressList.get(0).getAddressLine(0)); + Log.d("gaolei", "Address:" + addressList.get(0).toString()); + } + addOverLayout(currentLatLng); + mapUtil.setMapZoomStatus(currentLatLng, 18f); + } catch (Exception e) { + Log.d("gaolei", "" + e.getMessage()); } } - public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) { - System.out.print(""); + /** + * 实时定位任务 + * + * @author baidu + */ + class RealTimeLocRunnable implements Runnable { + + @Override + public void run() { + if (isRealTimeRunning) { +// getCurrentLocation(entityListener, trackListener); + getDistance(); + getTraceHistory(); + realTimeHandler.postDelayed(this, queryInterval); + } + } } - public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) { - System.out.print(""); + public void startRealTimeLoc() { + isRealTimeRunning = true; + realTimeLocRunnable = new RealTimeLocRunnable(); + realTimeHandler.post(realTimeLocRunnable); } - public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) { - System.out.print(""); + public void stopRealTimeLoc() { + isRealTimeRunning = false; + if (null != realTimeHandler && null != realTimeLocRunnable) { + realTimeHandler.removeCallbacks(realTimeLocRunnable); + } + EagleEyeUtil.get().mTraceClient.stopRealTimeLoc(); } - public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) { - System.out.print(""); + /** + * 获取当前位置 + */ + public void getCurrentLocation(OnEntityListener entityListener, OnTrackListener trackListener) { + // 网络连接正常,开启服务及采集,则查询纠偏后实时位置;否则进行实时定位 + if (NetUtil.isNetworkAvailable(this) + && EagleEyeUtil.get().trackConf.contains("is_trace_started") + && EagleEyeUtil.get().trackConf.contains("is_gather_started") + && EagleEyeUtil.get().trackConf.getBoolean("is_trace_started", false) + && EagleEyeUtil.get().trackConf.getBoolean("is_gather_started", false)) { + LatestPointRequest request = new LatestPointRequest(EagleEyeUtil.get().getTag(), EagleEyeUtil.get().serviceId, EagleEyeUtil.get().entityName); + ProcessOption processOption = new ProcessOption(); + processOption.setNeedDenoise(true); + processOption.setRadiusThreshold(50);//设置精度过滤,0为不需要;精度大于50米的位置点过滤掉 + processOption.setTransportMode(TransportMode.riding); + processOption.setNeedDenoise(true);//去噪处理 + processOption.setNeedMapMatch(true);//绑路处理 + request.setProcessOption(processOption); + EagleEyeUtil.get().mTraceClient.queryLatestPoint(request, trackListener); + } else { + EagleEyeUtil.get().mTraceClient.queryRealTimeLoc(EagleEyeUtil.get().locRequest, entityListener); + } + } + + public void getDistance() { + + EagleEyeUtil.get().getTraceDistance(trackDistanceListener, startTime / 1000, System.currentTimeMillis() / 1000); + } - public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) { - System.out.print(""); + public void getTraceHistory() { + + EagleEyeUtil.get().getTraceHistory(trackHistoryListener, startTime / 1000, System.currentTimeMillis() / 1000); + } @Override @@ -412,12 +770,18 @@ public void onMenuSlide(float offset) { public void onMapStatusChangeStart(MapStatus mapStatus) { } + @Override + public void onMapStatusChangeStart(MapStatus mapStatus, int i) { + + } + public void onMapStatusChangeFinish(MapStatus mapStatus) { String _str = mapStatus.toString(); String _regex = "target lat: (.*)\ntarget lng"; String _regex2 = "target lng: (.*)\ntarget screen x"; - changeLatitude = Double.parseDouble(latlng(_regex, _str)); - changeLongitude = Double.parseDouble(latlng(_regex2, _str)); + double changeLatitude = Double.parseDouble(latlng(_regex, _str)); + double changeLongitude = Double.parseDouble(latlng(_regex2, _str)); + changeLatLng = new LatLng(changeLatitude, changeLongitude); } @@ -455,15 +819,13 @@ public void addInfosOverlay(List infos) { } - private void addOverLayout(double _latitude, double _longitude) { + private void addOverLayout(LatLng point) { //先清除图层 mBaiduMap.clear(); infos.clear(); -// mlocationClient.requestLocation(); -// if (routeOverlay != null) -// routeOverlay.removeFromMap(); + double _latitude = point.latitude; + double _longitude = point.longitude; - LatLng point = new LatLng(_latitude, _longitude); MarkerOptions options = new MarkerOptions().position(point) .icon(dragLocationIcon); // 在地图上添加显示当前位置Marker @@ -504,11 +866,9 @@ private void initNearestBike(final BikeInfo bikeInfo, LatLng ll) { ImageView nearestIcon = new ImageView(getApplicationContext()); nearestIcon.setImageResource(R.mipmap.nearest_icon); InfoWindow.OnInfoWindowClickListener listener = null; - listener = new InfoWindow.OnInfoWindowClickListener() { - public void onInfoWindowClick() { - showBikeWalkingPlan(bikeInfo); - mBaiduMap.hideInfoWindow(); - } + listener = () -> { + showBikeWalkingPlan(bikeInfo); + mBaiduMap.hideInfoWindow(); }; InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(nearestIcon), ll, -108, listener); mBaiduMap.showInfoWindow(mInfoWindow); @@ -519,98 +879,24 @@ private void showBikeWalkingPlan(BikeInfo bikeInfo) { llBikeLayout.setVisibility(View.VISIBLE); bike_time.setText(bikeInfo.getTime()); bike_distance.setText(bikeInfo.getDistance()); - PlanNode endNodeStr = PlanNode.withLocation(new LatLng(bikeInfo.getLatitude(), bikeInfo.getLongitude())); - drawWalkingPlanRoute(endNodeStr); - llPrice.setVisibility(View.GONE); - } - - private void drawWalkingPlanRoute(PlanNode endNodeStr) { - if (routeOverlay != null) - routeOverlay.removeFromMap(); - if (endNodeStr != null) { - mSearch.walkingSearch((new WalkingRoutePlanOption()) - .from(startNodeStr).to(endNodeStr)); + llPrice.setVisibility(View.GONE); - } + PlanNode stNode = PlanNode.withLocation(currentLatLng); + PlanNode enNode = PlanNode.withLocation(new LatLng(bikeInfo.getLatitude(), bikeInfo.getLongitude())); + mSearch.walkingSearch((new WalkingRoutePlanOption()) + .from(stNode) + .to(enNode)); } @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.menu_main, menu); - return true; - } - - // 供路线选择的Dialog - class MyTransitDlg extends Dialog { - - private List mtransitRouteLines; - private ListView transitRouteList; - private RouteLineAdapter mTransitAdapter; - - OnItemInDlgClickListener onItemInDlgClickListener; - - public MyTransitDlg(Context context, int theme) { - super(context, theme); - } - - public MyTransitDlg(Context context, List transitRouteLines, RouteLineAdapter.Type - type) { - this(context, 0); - mtransitRouteLines = transitRouteLines; - mTransitAdapter = new RouteLineAdapter(context, mtransitRouteLines, type); - requestWindowFeature(Window.FEATURE_NO_TITLE); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_transit_dialog); - - transitRouteList = findViewById(R.id.transitList); - transitRouteList.setAdapter(mTransitAdapter); - - transitRouteList.setOnItemClickListener(new AdapterView.OnItemClickListener() { - - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { -// onItemInDlgClickListener.onItemClick( position); -// mBtnPre.setVisibility(View.VISIBLE); -// mBtnNext.setVisibility(View.VISIBLE); -// dismiss(); - - } - }); - } - - public void setOnItemInDlgClickLinster(OnItemInDlgClickListener itemListener) { - onItemInDlgClickListener = itemListener; - } - } - - // 响应DLg中的List item 点击 - interface OnItemInDlgClickListener { - void onItemClick(int position); + protected void onResume() { + mMapView.onResume(); + super.onResume(); } - private class MyWalkingRouteOverlay extends WalkingRouteOverlay { - - public MyWalkingRouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - @Override - public BitmapDescriptor getStartMarker() { - return BitmapDescriptorFactory.fromResource(R.mipmap.transparent_icon); - } - - @Override - public BitmapDescriptor getTerminalMarker() { - return BitmapDescriptorFactory.fromResource(R.mipmap.transparent_icon); - } - } public void gotoCodeUnlock(View view) { Intent intent = new Intent(this, CodeUnlockActivity.class); @@ -635,13 +921,40 @@ public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == RESULT_OK) { beginService(); - MarkerOptions options = new MarkerOptions().position(new LatLng(currentLatitude,currentLongitude)) - .icon(startBmp); - // 在地图上添加Marker,并显示 - mBaiduMap.addOverlay(options); + if (currentLatLng != null) { + MarkerOptions options = new MarkerOptions().position(currentLatLng) + .icon(startBmp); + // 在地图上添加Marker,并显示 + mBaiduMap.addOverlay(options); + MapUtil.getInstance().setMapZoomStatus(currentLatLng, 19f); + } + + startTrace(); + startGather(); + startTime = System.currentTimeMillis(); + } } + private void startTrace() { + EagleEyeUtil.get().mTraceClient.startTrace(EagleEyeUtil.get().mTrace, mTraceListener); + startRealTimeLoc(); + } + + private void stopTrace() { + EagleEyeUtil.get().mTraceClient.stopTrace(EagleEyeUtil.get().mTrace, mTraceListener); + stopRealTimeLoc(); + } + + private void startGather() { + + EagleEyeUtil.get().mTraceClient.startGather(mTraceListener); + } + + private void stopGather() { + EagleEyeUtil.get().mTraceClient.stopGather(mTraceListener); + } + private void backFromRouteDetail() { title.setText(getString(R.string.bybike)); textview_time.setText(getString(R.string.foot)); @@ -666,9 +979,7 @@ private void backFromRouteDetail() { btn_locale.setVisibility(View.VISIBLE); end_route.setVisibility(View.GONE); - getMyLocation(); - addOverLayout(currentLatitude, currentLongitude); } private void beginService() { @@ -677,27 +988,19 @@ private void beginService() { return; } - mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING; - mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration( - mCurrentMode, true, null)); title.setText(getString(R.string.routing)); textview_time.setText(getString(R.string.bike_time)); textview_distance.setText(getString(R.string.bike_distance)); textview_price.setText(getString(R.string.bike_price)); prompt.setText(getString(R.string.routing_prompt)); - bike_time.setText("0分钟"); - bike_distance.setText("0米"); - bike_price.setText("0元"); - llPrice.setVisibility(View.VISIBLE); - textview_time.setTextSize(20); textview_distance.setTextSize(20); textview_price.setTextSize(20); bike_time.setTextSize(20); bike_distance.setTextSize(20); bike_price.setTextSize(20); - + llPrice.setVisibility(View.VISIBLE); prompt.setVisibility(View.VISIBLE); llBikeLayout.setVisibility(View.VISIBLE); current_addr.setVisibility(View.GONE); @@ -708,34 +1011,26 @@ private void beginService() { llBikeDetail.setVisibility(View.VISIBLE); book_bt.setVisibility(View.GONE); - if (routeOverlay != null) - routeOverlay.removeFromMap(); btn_locale.setVisibility(View.GONE); end_route.setVisibility(View.VISIBLE); - mBaiduMap.clear(); - mlocationClient.requestLocation(); - Intent intent = new Intent(this, RouteService.class); - startService(intent); + if (!Utils.isServiceWork(this, "com.baidu.trace.LBSTraceService")) { + mBaiduMap.clear(); + bike_time.setText("0分钟"); + bike_distance.setText("0米"); + bike_price.setText("0元"); + + } } private void cancelBook() { llBikeLayout.setVisibility(View.GONE); prompt.setVisibility(View.GONE); - if (routeOverlay != null) - routeOverlay.removeFromMap(); - MapStatus.Builder builder = new MapStatus.Builder(); - //地图缩放比设置为18 - builder.target(currentLL).zoom(18.0f); - mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); + MapUtil.getInstance().setMapZoomStatus(currentLatLng, 18); + getMyLocation(); } - @Override - protected void onResume() { - mMapView.onResume(); - super.onResume(); - } @Override protected void onPause() { @@ -752,13 +1047,15 @@ protected void onDestroy() { mBaiduMap.setMyLocationEnabled(false); mMapView.onDestroy(); mMapView = null; + mSearch.destroy(); EventBus.getDefault().unregister(this); + } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if (llBikeLayout.getVisibility() == View.VISIBLE) { - if (!Utils.isServiceWork(this, "com.biubike.service.RouteService")) + if (!Utils.isServiceWork(this, "com.baidu.trace.LBSTraceService")) cancelBook(); return true; } @@ -773,67 +1070,29 @@ public boolean onKeyDown(int keyCode, KeyEvent event) { return super.onKeyDown(keyCode, event); } - @Subscribe(threadMode = ThreadMode.MAIN) - public void updateRoute(RoutePoints routePoints) { - if (Utils.isTopActivity(this)) { - - String showTime = routePoints.getTime(); - String showDistance = routePoints.getDistance(); - String showPrice = routePoints.getPrice(); - ArrayList routPointList = routePoints.getRouteList(); - - Log.d("gaolei", "totalTime---------get-----" + showTime); - Log.d("gaolei", "totalDistance-----get---------" + showDistance); - Log.d("gaolei", "totalPrice-------get-------" + showPrice); - Log.d("gaolei", "routPointList.size()-------get-------" + routPointList.size()); - - setPolyline(routPointList); - bike_time.setText(showTime); - bike_distance.setText(showDistance); - bike_price.setText(showPrice); - RoutePoint routePoint = routPointList.get(routPointList.size() - 1); - LatLng latLng = new LatLng(routePoint.routeLat, routePoint.routeLng); - MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(latLng); - // 移动到某经纬度 - mBaiduMap.animateMapStatus(update); - } - } - - public void setPolyline(ArrayList routePoints) { - pointsList.clear(); - for (int i = 0; i < routePoints.size(); i++) { - RoutePoint point = routePoints.get(i); - LatLng latLng = new LatLng(point.getRouteLat(), point.getRouteLng()); - pointsList.add(latLng); - } - if (pointsList.size() < 2) return; - OverlayOptions ooPolyline = new PolylineOptions().width(10) - .color(0xFF36D19D).points(pointsList); - mBaiduMap.clear(); - mBaiduMap.addOverlay(ooPolyline); - - LatLng newLatLng = pointsList.get(pointsList.size() - 1); - MarkerOptions options = new MarkerOptions().position(newLatLng) - .icon(bikeIcon); - // 在地图上添加Marker,并显示 - mBaiduMap.addOverlay(options); - } protected void toastDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("确认要结束进程吗?"); builder.setTitle("提示"); - builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - Intent intent = new Intent(MainActivity.this, RouteService.class); - stopService(intent); - CodeUnlockActivity.unlockSuccess = false; - mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL; - mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration( - mCurrentMode, true, null)); - backFromRouteDetail(); - } + builder.setPositiveButton("确认", (dialog, which) -> { + dialog.dismiss(); + CodeUnlockActivity.unlockSuccess = false; + + stopRealTimeLoc(); + stopTrace(); + stopGather(); + + endTime = System.currentTimeMillis(); + + backFromRouteDetail(); + + getMyLocation(); + + insertCycleData(); + notificationManager.cancel(1); + trackPoints.clear(); + startRoutDetail(); }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { @@ -843,4 +1102,78 @@ public void onClick(DialogInterface dialog, int which) { builder.create().show(); } + public void insertCycleData() { + if (trackPoints.size() < 2) return; + ContentValues values = new ContentValues(); + // 向该对象中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须和数据当中的数据类型一致 + values.put("cycle_date", Utils.getDateFromMillisecond(startTime)); + values.put("cycle_start_time", startTime); + values.put("cycle_end_time", endTime); + values.put("cycle_time", showTime); + values.put("cycle_distance", showDistance); + values.put("cycle_price", showPrice); + // 创建DatabaseHelper对象 + RouteDBHelper dbHelper = new RouteDBHelper(this); + // 得到一个可写的SQLiteDatabase对象 + SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase(); + // 调用insert方法,就可以将数据插入到数据库当中 + // 第一个参数:表名称 + // 第二个参数:SQl不允许一个空列,如果ContentValues是空的,那么这一列被明确的指明为NULL值 + // 第三个参数:ContentValues对象 + sqliteDatabase.insert("cycle_route", null, values); + sqliteDatabase.close(); + + + } + + private void startRoutDetail() { + Intent intent = new Intent(MainActivity.this, RouteDetailActivity.class); + RouteRecord routeRecord = new RouteRecord(); + routeRecord.setCycleStartTime(startTime); + routeRecord.setCycleEndTime(endTime); + routeRecord.setCycleTime(showTime); + routeRecord.setCycleDistance(showDistance); + routeRecord.setCyclePrice(showPrice); + intent.putExtra("routeRecord", routeRecord); + startActivity(intent); + } + + private void startNotifi(String time, String distance, String price) { + contentView.setTextViewText(R.id.bike_time, time); + contentView.setTextViewText(R.id.bike_distance, distance); + contentView.setTextViewText(R.id.bike_price, price); + notificationManager.notify(1, notification); + } + + private void initNotification() { + int icon = R.mipmap.bike_icon2; + notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + createNotificationChannel("id_route", "route"); + } + + contentView = new RemoteViews(getPackageName(), R.layout.notification_layout); + notification = new NotificationCompat.Builder(this, "id_route").setContent(contentView).setSmallIcon(icon).build(); + Intent notificationIntent = new Intent(this, MainActivity.class); + notificationIntent.putExtra("flag", "notification"); + notification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); + EagleEyeUtil.get().initTrace(notification); + + } + + @RequiresApi(Build.VERSION_CODES.O) + private void createNotificationChannel(String channelId, String channelName) { + + if (notificationManager.getNotificationChannel(channelId) != null) return; + + NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW); + notificationChannel.enableVibration(false); + notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); + notificationChannel.setShowBadge(true); + notificationChannel.setBypassDnd(true); + + notificationManager.createNotificationChannel(notificationChannel); + + } + } \ No newline at end of file diff --git a/BiuBike/app/src/main/java/com/biubike/activity/BDInnerNaviActivity.java b/BiuBike/app/src/main/java/com/biubike/activity/BDInnerNaviActivity.java deleted file mode 100755 index ba5691f..0000000 --- a/BiuBike/app/src/main/java/com/biubike/activity/BDInnerNaviActivity.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.biubike.activity; - -import android.content.Intent; -import android.os.Bundle; -import android.os.Handler; -import android.support.v7.app.AppCompatActivity; -import android.util.Log; -import android.view.View; - -import com.baidu.navisdk.adapter.BNRouteGuideManager; -import com.baidu.navisdk.adapter.BNRouteGuideManager.CustomizedLayerItem; -import com.baidu.navisdk.adapter.BNRouteGuideManager.OnNavigationListener; -import com.baidu.navisdk.adapter.BNRoutePlanNode; -import com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType; -import com.baidu.navisdk.adapter.BNaviBaseCallbackModel; -import com.baidu.navisdk.adapter.BaiduNaviCommonModule; -import com.baidu.navisdk.adapter.NaviModuleFactory; -import com.baidu.navisdk.adapter.NaviModuleImpl; -import com.biubike.R; -import com.biubike.util.NavUtil; - -import java.util.ArrayList; -import java.util.List; - -import static com.biubike.util.NavUtil.activityList; - - -public class BDInnerNaviActivity extends AppCompatActivity { - - private final String TAG = BDInnerNaviActivity.class.getName(); - private BNRoutePlanNode mBNRoutePlanNode = null; - private BaiduNaviCommonModule mBaiduNaviCommonModule = null; - - /* - * 对于导航模块有两种方式来实现发起导航。 1:使用通用接口来实现 2:使用传统接口来实现 - * - */ - // 是否使用通用接口 - private boolean useCommonInterface = true; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - activityList.add(this); - createHandler(); - - View view = null; - if (useCommonInterface) { - //使用通用接口 - mBaiduNaviCommonModule = NaviModuleFactory.getNaviModuleManager().getNaviCommonModule( - NaviModuleImpl.BNaviCommonModuleConstants.ROUTE_GUIDE_MODULE, this, - BNaviBaseCallbackModel.BNaviBaseCallbackConstants.CALLBACK_ROUTEGUIDE_TYPE, mOnNavigationListener); - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onCreate(); - view = mBaiduNaviCommonModule.getView(); - } - - } else { - //使用传统接口 - view = BNRouteGuideManager.getInstance().onCreate(this, mOnNavigationListener); - } - - if (view != null) { - setContentView(view); - } - - Intent intent = getIntent(); - if (intent != null) { - Bundle bundle = intent.getExtras(); - if (bundle != null) { - mBNRoutePlanNode = (BNRoutePlanNode) bundle.getSerializable(NavUtil.ROUTE_PLAN_NODE); - } - } - //显示自定义图标 - if (hd != null) { - hd.sendEmptyMessageAtTime(MSG_SHOW, 5000); - } - } - - @Override - protected void onResume() { - super.onResume(); - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onResume(); - } - } else { - BNRouteGuideManager.getInstance().onResume(); - } - } - - protected void onPause() { - super.onPause(); - - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onPause(); - } - } else { - BNRouteGuideManager.getInstance().onPause(); - } - - } - - ; - - @Override - protected void onDestroy() { - super.onDestroy(); - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onDestroy(); - } - } else { - BNRouteGuideManager.getInstance().onDestroy(); - } - activityList.remove(this); - - } - - @Override - protected void onStop() { - super.onStop(); - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onStop(); - } - } else { - BNRouteGuideManager.getInstance().onStop(); - } - - } - - @Override - public void onBackPressed() { - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onBackPressed(false); - } - } else { - BNRouteGuideManager.getInstance().onBackPressed(false); - } - } - - public void onConfigurationChanged(android.content.res.Configuration newConfig) { - super.onConfigurationChanged(newConfig); - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onConfigurationChanged(newConfig); - } - } else { - BNRouteGuideManager.getInstance().onConfigurationChanged(newConfig); - } - - } - - @Override - public boolean onKeyDown(int keyCode, android.view.KeyEvent event) { - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - Bundle mBundle = new Bundle(); - mBundle.putInt(RouteGuideModuleConstants.KEY_TYPE_KEYCODE, keyCode); - mBundle.putParcelable(RouteGuideModuleConstants.KEY_TYPE_EVENT, event); - mBaiduNaviCommonModule.setModuleParams(RouteGuideModuleConstants.METHOD_TYPE_ON_KEY_DOWN, mBundle); - try { - Boolean ret = (Boolean) mBundle.get(RET_COMMON_MODULE); - if (ret) { - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return super.onKeyDown(keyCode, event); - } - - @Override - protected void onStart() { - super.onStart(); - // TODO Auto-generated method stub - if (useCommonInterface) { - if (mBaiduNaviCommonModule != null) { - mBaiduNaviCommonModule.onStart(); - } - } else { - BNRouteGuideManager.getInstance().onStart(); - } - } - - private void addCustomizedLayerItems() { - List items = new ArrayList(); - CustomizedLayerItem item1 = null; - if (mBNRoutePlanNode != null) { - item1 = new CustomizedLayerItem(mBNRoutePlanNode.getLongitude(), mBNRoutePlanNode.getLatitude(), - mBNRoutePlanNode.getCoordinateType(), getResources().getDrawable(R.mipmap.ic_launcher), - CustomizedLayerItem.ALIGN_CENTER); - items.add(item1); - - BNRouteGuideManager.getInstance().setCustomizedLayerItems(items); - } - BNRouteGuideManager.getInstance().showCustomizedLayer(true); - } - - private static final int MSG_SHOW = 1; - private static final int MSG_HIDE = 2; - private static final int MSG_RESET_NODE = 3; - private Handler hd = null; - - private void createHandler() { - if (hd == null) { - hd = new Handler(getMainLooper()) { - public void handleMessage(android.os.Message msg) { - if (msg.what == MSG_SHOW) { - addCustomizedLayerItems(); - } else if (msg.what == MSG_HIDE) { - BNRouteGuideManager.getInstance().showCustomizedLayer(false); - } else if (msg.what == MSG_RESET_NODE) { - BNRouteGuideManager.getInstance().resetEndNodeInNavi( - new BNRoutePlanNode(116.21142, 40.85087, "百度大厦11", null, CoordinateType.GCJ02)); - } - } - - ; - }; - } - } - - private OnNavigationListener mOnNavigationListener = new OnNavigationListener() { - - @Override - public void onNaviGuideEnd() { - //退出导航 - finish(); - } - - @Override - public void notifyOtherAction(int actionType, int arg1, int arg2, Object obj) { - - if (actionType == 0) { - //导航到达目的地 自动退出 - Log.i(TAG, "notifyOtherAction actionType = " + actionType + ",导航到达目的地!"); - } - - Log.i(TAG, "actionType:" + actionType + "arg1:" + arg1 + "arg2:" + arg2 + "obj:" + obj.toString()); - } - - }; - - private final static String RET_COMMON_MODULE = "module.ret"; - - private interface RouteGuideModuleConstants { - int METHOD_TYPE_ON_KEY_DOWN = 0x01; - String KEY_TYPE_KEYCODE = "keyCode"; - String KEY_TYPE_EVENT = "event"; - } -} diff --git a/BiuBike/app/src/main/java/com/biubike/activity/BNaviGuideActivity.java b/BiuBike/app/src/main/java/com/biubike/activity/BNaviGuideActivity.java new file mode 100644 index 0000000..27ea10a --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/activity/BNaviGuideActivity.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. + */ +package com.biubike.activity; + +import android.app.Activity; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.util.Log; +import android.view.View; + +import com.baidu.mapapi.bikenavi.BikeNavigateHelper; +import com.baidu.mapapi.bikenavi.adapter.IBNaviStatusListener; +import com.baidu.mapapi.bikenavi.adapter.IBRouteGuidanceListener; +import com.baidu.mapapi.bikenavi.adapter.IBTTSPlayer; +import com.baidu.mapapi.bikenavi.model.BikeRouteDetailInfo; +import com.baidu.mapapi.bikenavi.params.BikeNaviLaunchParam; +import com.baidu.mapapi.walknavi.model.RouteGuideKind; + +public class BNaviGuideActivity extends Activity { + + private final static String TAG = BNaviGuideActivity.class.getSimpleName(); + + private BikeNavigateHelper mNaviHelper; + + BikeNaviLaunchParam param; + + @Override + protected void onDestroy() { + super.onDestroy(); + mNaviHelper.quit(); + } + + @Override + protected void onResume() { + super.onResume(); + mNaviHelper.resume(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mNaviHelper = BikeNavigateHelper.getInstance(); + + View view = mNaviHelper.onCreate(BNaviGuideActivity.this); + if (view != null) { + setContentView(view); + } + + mNaviHelper.setBikeNaviStatusListener(new IBNaviStatusListener() { + @Override + public void onNaviExit() { + Log.d(TAG, "onNaviExit"); + } + }); + + mNaviHelper.setTTsPlayer(new IBTTSPlayer() { + @Override + public int playTTSText(String s, boolean b) { + Log.d("tts", s); + return 0; + } + }); + + mNaviHelper.startBikeNavi(BNaviGuideActivity.this); + + mNaviHelper.setRouteGuidanceListener(this, new IBRouteGuidanceListener() { + @Override + public void onRouteGuideIconUpdate(Drawable icon) { + + } + + @Override + public void onRouteGuideKind(RouteGuideKind routeGuideKind) { + + } + + @Override + public void onRoadGuideTextUpdate(CharSequence charSequence, CharSequence charSequence1) { + + } + + @Override + public void onRemainDistanceUpdate(CharSequence charSequence) { + + } + + @Override + public void onRemainTimeUpdate(CharSequence charSequence) { + + } + + @Override + public void onGpsStatusChange(CharSequence charSequence, Drawable drawable) { + + } + + @Override + public void onRouteFarAway(CharSequence charSequence, Drawable drawable) { + + } + + @Override + public void onRoutePlanYawing(CharSequence charSequence, Drawable drawable) { + + } + + @Override + public void onReRouteComplete() { + + } + + @Override + public void onArriveDest() { + + } + + @Override + public void onVibrate() { + + } + + @Override + public void onGetRouteDetailInfo(BikeRouteDetailInfo bikeRouteDetailInfo) { + + } + }); + } + +} diff --git a/BiuBike/app/src/main/java/com/biubike/activity/MyRouteActivity.java b/BiuBike/app/src/main/java/com/biubike/activity/MyRouteActivity.java index d50e2ed..42149c7 100644 --- a/BiuBike/app/src/main/java/com/biubike/activity/MyRouteActivity.java +++ b/BiuBike/app/src/main/java/com/biubike/activity/MyRouteActivity.java @@ -81,38 +81,10 @@ public void onLoadMore() { public void onItemClick(View v, int position) { Intent intent = new Intent(MyRouteActivity.this, RouteDetailActivity.class); RouteRecord routeRecord = routeList.get(position); - Bundle bundle = new Bundle(); - bundle.putString("totalTime", routeRecord.getCycle_time()); - bundle.putString("totalDistance", routeRecord.getCycle_distance()); - bundle.putString("totalPrice", routeRecord.getCycle_price()); - bundle.putString("routePoints", routeRecord.getCycle_points()); - intent.putExtras(bundle); + intent.putExtra("routeRecord", routeRecord); startActivity(intent); } - public List getAllPoints() { - String sql = "select * from cycle_route order by route_id DESC "; - RouteDBHelper helper = new RouteDBHelper(this); - SQLiteDatabase db = helper.getWritableDatabase(); - - Cursor cursor = db.rawQuery(sql, null); - while (cursor.moveToNext()) { - RouteRecord point = new RouteRecord(); - point.setCycle_date(cursor.getString(cursor - .getColumnIndex("cycle_date"))); - point.setCycle_time(cursor.getString(cursor - .getColumnIndex("cycle_time"))); - point.setCycle_distance(cursor.getString(cursor - .getColumnIndex("cycle_distance"))); - point.setCycle_price(cursor.getString(cursor - .getColumnIndex("cycle_price"))); - point.setCycle_points(cursor.getString(cursor - .getColumnIndex("cycle_points"))); - routeList.add(point); - } - return routeList; - } - /* * 读取指定ID的分页数据 @@ -129,16 +101,19 @@ public List loadPage() { Cursor cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { RouteRecord point = new RouteRecord(); - point.setCycle_date(cursor.getString(cursor + point.setCycleDate(cursor.getString(cursor .getColumnIndex("cycle_date"))); - point.setCycle_time(cursor.getString(cursor + point.setCycleStartTime(cursor.getLong(cursor + .getColumnIndex("cycle_start_time"))); + point.setCycleEndTime(cursor.getLong(cursor + .getColumnIndex("cycle_end_time"))); + point.setCycleTime(cursor.getString(cursor .getColumnIndex("cycle_time"))); - point.setCycle_distance(cursor.getString(cursor + point.setCycleDistance(cursor.getString(cursor .getColumnIndex("cycle_distance"))); - point.setCycle_price(cursor.getString(cursor + point.setCyclePrice(cursor.getString(cursor .getColumnIndex("cycle_price"))); - point.setCycle_points(cursor.getString(cursor - .getColumnIndex("cycle_points"))); + routeList.add(point); } PageId++; diff --git a/BiuBike/app/src/main/java/com/biubike/activity/NavigationActivity.java b/BiuBike/app/src/main/java/com/biubike/activity/NavigationActivity.java index 0eb859a..aa0fc60 100644 --- a/BiuBike/app/src/main/java/com/biubike/activity/NavigationActivity.java +++ b/BiuBike/app/src/main/java/com/biubike/activity/NavigationActivity.java @@ -1,6 +1,7 @@ package com.biubike.activity; +import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; @@ -16,6 +17,12 @@ import android.widget.TextView; import android.widget.Toast; +import com.baidu.mapapi.bikenavi.BikeNavigateHelper; +import com.baidu.mapapi.bikenavi.adapter.IBEngineInitListener; +import com.baidu.mapapi.bikenavi.adapter.IBRoutePlanListener; +import com.baidu.mapapi.bikenavi.model.BikeRoutePlanError; +import com.baidu.mapapi.bikenavi.params.BikeNaviLaunchParam; +import com.baidu.mapapi.bikenavi.params.BikeRouteNodeInfo; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener; import com.baidu.mapapi.search.sug.SuggestionResult; @@ -26,15 +33,13 @@ import com.biubike.adapter.PoiSuggestionAdapter; import com.biubike.adapter.RecyclerViewDivider; import com.biubike.base.BaseActivity; +import com.biubike.map.LocationManager; import com.biubike.provider.PoiObject; import com.biubike.provider.ProviderUtil; -import com.biubike.util.LocationManager; -import com.biubike.util.NavUtil; import com.biubike.util.Utils; import java.util.List; -import static com.biubike.util.NavUtil.activityList; /** * Created by gaolei on 17/3/29. @@ -44,6 +49,7 @@ public class NavigationActivity extends BaseActivity implements OnGetSuggestionResultListener, PoiSuggestionAdapter.OnItemClickListener , PoiHostoryAdapter.OnHistoryItemClickListener { + private String TAG="NavigationActivity"; private LinearLayout place_search_layout; private RelativeLayout titleLayout; private EditText place_edit; @@ -60,19 +66,19 @@ public class NavigationActivity extends BaseActivity implements public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - activityList.add(this); setContentView(R.layout.activity_navigation); providerUtil = new ProviderUtil(this); //想使用内置导航,必须初始化导航 - NavUtil.initNavi(this); + mSuggestionSearch = SuggestionSearch.newInstance(); + currentAddress = LocationManager.getInstance().getAddress(); - place_search_layout = findViewById(R.id.place_search_layout); - titleLayout = findViewById(R.id.title_layout); + place_search_layout = findViewById(R.id.place_search_layout); + titleLayout = findViewById(R.id.title_layout); start_place_edit = findViewById(R.id.start_place_edit); destination_edit = findViewById(R.id.destination_edit); place_edit = findViewById(R.id.place_edit); - recyclerview_poi_history =findViewById(R.id.recyclerview_poi_history); - recyclerview_poi = findViewById(R.id.recyclerview_poi); + recyclerview_poi_history = findViewById(R.id.recyclerview_poi_history); + recyclerview_poi = findViewById(R.id.recyclerview_poi); recyclerview_poi.setLayoutManager(new LinearLayoutManager(this)); recyclerview_poi.addItemDecoration(new RecyclerViewDivider( this, LinearLayoutManager.HORIZONTAL, 1, @@ -180,7 +186,7 @@ public void onGetSuggestionResult(SuggestionResult res) { suggestionInfoList = res.getAllSuggestions(); if (firstSetAdapter) { String from = isStartPoi == true ? "start" : "detination"; - sugAdapter = new PoiSuggestionAdapter(this, suggestionInfoList, from); + sugAdapter = new PoiSuggestionAdapter(NavigationActivity.this, suggestionInfoList, from); recyclerview_poi.setAdapter(sugAdapter); sugAdapter.setOnClickListener(this); firstSetAdapter = false; @@ -217,11 +223,11 @@ public void startNavigation(View view) { String start = startAddr.equals(getString(R.string.my_position)) ? currentAddress : startAddr; String endAddr = destination_edit.getText().toString(); String end = endAddr.equals(getString(R.string.my_position)) ? currentAddress : endAddr; - NavUtil.showChoiceNaviWayDialog(this, startLL, endLL, start, end); +// NavUtil.showChoiceNaviWayDialog(this, startLL, endLL, start, end); + startBikeNavi(); } } - @Override public void onItemClick(View v, int position, String flag, SuggestionResult.SuggestionInfo info) { if (isStartPoi) { start_place_edit.setText(info.key); @@ -231,7 +237,7 @@ public void onItemClick(View v, int position, String flag, SuggestionResult.Sugg endLL = info.pt; } backFromSearchPlace(place_search_layout); - providerUtil.addData(info.key,info.district, info.pt.latitude + "", info.pt.longitude + ""); + providerUtil.addData(info.key, info.district, info.pt.latitude + "", info.pt.longitude + ""); } @Override @@ -247,4 +253,56 @@ public void onHistoryItemClick(View v, int position, PoiObject poiObject) { backFromSearchPlace(place_search_layout); } + /** + * 开始骑行导航 + */ + private void startBikeNavi() { + try { + BikeNavigateHelper.getInstance().initNaviEngine(this, new IBEngineInitListener() { + @Override + public void engineInitSuccess() { + routePlanWithBikeParam(); + } + + @Override + public void engineInitFail() { + BikeNavigateHelper.getInstance().unInitNaviEngine(); + } + }); + } catch (Exception e) { + Log.e(TAG,"e.getMessage():"+e.getMessage().toString()); + e.printStackTrace(); + } + } + /** + * 发起骑行导航算路 + */ + private void routePlanWithBikeParam() { + /*构造导航起终点参数对象*/ + BikeRouteNodeInfo bikeStartNode = new BikeRouteNodeInfo(); + bikeStartNode.setLocation(startLL); + BikeRouteNodeInfo bikeEndNode = new BikeRouteNodeInfo(); + bikeEndNode.setLocation(endLL); + BikeNaviLaunchParam bikeParam = new BikeNaviLaunchParam().startNodeInfo(bikeStartNode).endNodeInfo(bikeEndNode); + BikeNavigateHelper.getInstance().routePlanWithRouteNode(bikeParam, new IBRoutePlanListener() { + @Override + public void onRoutePlanStart() { + Log.d(TAG, "BikeNavi onRoutePlanStart"); + } + + @Override + public void onRoutePlanSuccess() { + Log.d(TAG, "BikeNavi onRoutePlanSuccess"); + Intent intent = new Intent(); + intent.setClass(NavigationActivity.this, BNaviGuideActivity.class); + startActivity(intent); + } + + @Override + public void onRoutePlanFail(BikeRoutePlanError error) { + Log.d(TAG, "BikeNavi onRoutePlanFail"); + } + + }); + } } diff --git a/BiuBike/app/src/main/java/com/biubike/activity/RouteDetailActivity.java b/BiuBike/app/src/main/java/com/biubike/activity/RouteDetailActivity.java index f9e2028..da02732 100644 --- a/BiuBike/app/src/main/java/com/biubike/activity/RouteDetailActivity.java +++ b/BiuBike/app/src/main/java/com/biubike/activity/RouteDetailActivity.java @@ -1,9 +1,11 @@ package com.biubike.activity; +import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; +import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; @@ -24,13 +26,17 @@ import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.map.PolylineOptions; import com.baidu.mapapi.model.LatLng; +import com.baidu.trace.api.track.HistoryTrackResponse; +import com.baidu.trace.api.track.OnTrackListener; +import com.baidu.trace.api.track.TrackPoint; import com.biubike.R; import com.biubike.base.BaseActivity; -import com.biubike.bean.RoutePoint; +import com.biubike.bean.RouteRecord; +import com.biubike.map.EagleEyeUtil; +import com.biubike.map.TraceUtil; import com.biubike.util.Utils; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; @@ -41,53 +47,62 @@ public class RouteDetailActivity extends BaseActivity { - private MapView routeDetailMapView; - private BaiduMap routeBaiduMap; + private String TAG = "RouteDetailActivity"; + private BaiduMap baiduMap; private BitmapDescriptor startBmp, endBmp, currentBmp; private TextView total_time, total_distance, total_price, tv_route_replay, tv_title; - public ArrayList routePoints; - private String routePointsStr; private RelativeLayout replay_progress_layout, route_mapview_layout; - private List points, subList; private int routePointsLength, currentIndex = 0, spanIndex = 0; private boolean isInReplay = false, pauseReplay = false; private ImageView img_replay; private SeekBar seekbar_progress; private TextView tv_current_time, tv_current_speed; private final int UPDATE_PROGRESS = 1; + private List routePoints; + private List points; + private List subList; + private RouteRecord routeRecord; + @SuppressLint("HandlerLeak") Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_PROGRESS: currentIndex = currentIndex + spanIndex; - - if (currentIndex < routePointsLength) - subList = points.subList(0, currentIndex); + Log.d(TAG, "currentIndex:" + currentIndex); + Log.d(TAG, "spanIndex:" + spanIndex); + Log.d(TAG, "points.size():" + routePoints.size()); + if (currentIndex < routePointsLength) { + subList = new ArrayList(points.subList(0, currentIndex)); + } + if (subList == null) return; if (subList.size() >= 1) { - setPolyline(subList); + playTraceHistory(subList); } if (currentIndex < routePointsLength) { - tv_current_time.setText(Utils.getDateFromMillisecond(routePoints.get(currentIndex).time)); - tv_current_speed.setText(routePoints.get(currentIndex).speed + "km/h"); + tv_current_time.setText(routePoints.get(currentIndex).getCreateTime()); + DecimalFormat df = new DecimalFormat("#.##"); + String showSpeed = df.format(routePoints.get(currentIndex).getSpeed()) + "千米"; +// String showSpeed =routePoints.get(currentIndex).getSpeed() + "千米"; + tv_current_speed.setText(showSpeed); int progress = currentIndex * 100 / routePointsLength; seekbar_progress.setProgress(progress); - handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 1000); + handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 500); } else { - setPolyline(points); + playTraceHistory(points); seekbar_progress.setProgress(100); handler.removeCallbacksAndMessages(null); Toast.makeText(RouteDetailActivity.this, "轨迹回放结束", Toast.LENGTH_LONG).show(); } } - } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_route_detail); + points = new ArrayList<>(); initMap(); total_time = findViewById(R.id.total_time); total_distance = findViewById(R.id.total_distance); @@ -107,95 +122,146 @@ public void onCreate(Bundle savedInstanceState) { currentBmp = BitmapDescriptorFactory.fromResource(R.mipmap.bike_icon); Intent intent = getIntent(); - String time = intent.getStringExtra("totalTime"); - String distance = intent.getStringExtra("totalDistance"); - String price = intent.getStringExtra("totalPrice"); - routePointsStr = intent.getStringExtra("routePoints"); - routePoints = new Gson().fromJson(routePointsStr, new TypeToken>() { - }.getType()); - routePointsLength = routePoints.size(); + routeRecord = intent.getParcelableExtra("routeRecord"); + long startTime = routeRecord.getCycleStartTime() / 1000; + long endTime = routeRecord.getCycleStartTime() / 1000; + + getTraceHistory(startTime, endTime); + + } + + + public void getTraceHistory(long startTime, long endTime) { + + OnTrackListener trackHistoryListener = new OnTrackListener() { + @Override + public void onHistoryTrackCallback(HistoryTrackResponse response) { + routePoints = response.getTrackPoints(); + routePointsLength = routePoints.size(); + + if (null != routePoints) { + for (TrackPoint trackPoint : routePoints) { + double lat = trackPoint.getLocation().getLatitude(); + double lng = trackPoint.getLocation().getLongitude(); + if (!TraceUtil.isZeroPoint(lat, lng)) { + points.add(new LatLng(lat, lng)); + } + } + } /* 每2s采集一个点,下面是实际行驶时间和轨迹回放时间的对应策略 */ - //实际2~100s-->播放1~25s - if (1 < routePointsLength && routePointsLength < 50) spanIndex = 2; - //实际100~200s-->播放12~25s - if (50 <= routePointsLength && routePointsLength < 100) spanIndex = 4; - //实际200~1000s-->播放16~83s - if (100 <= routePointsLength && routePointsLength < 500) spanIndex = 6; - //实际1000~4000s-->播放62~250s - if (500 <= routePointsLength && routePointsLength < 2000) spanIndex = 8; - //实际4000~20000s-->播放166~833s - if (2000 <= routePointsLength && routePointsLength < 10000) spanIndex = 12; - //实际10000~20000s-->播放156s - if (10000 <= routePointsLength) spanIndex = 64; - drawRoute(); - - total_time.setText("骑行时长:" + time); - total_distance.setText("骑行距离:" + distance); - total_price.setText("余额支付:" + price); - seekbar_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - /** - * 拖动条停止拖动的时候调用 - */ - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 1); - } + if (0 <= routePointsLength && routePointsLength < 20) { + spanIndex = 1; + } + //实际2~100s-->播放1~25s + if (20 <= routePointsLength && routePointsLength < 50) { + spanIndex = 2; + } + //实际100~200s-->播放12~25s + if (50 <= routePointsLength && routePointsLength < 100) { + spanIndex = 4; + } + //实际200~1000s-->播放16~83s + if (100 <= routePointsLength && routePointsLength < 500) { + spanIndex = 6; + } + //实际1000~4000s-->播放62~250s + if (500 <= routePointsLength && routePointsLength < 2000) { + spanIndex = 8; + } + //实际4000~20000s-->播放166~833s + if (2000 <= routePointsLength && routePointsLength < 10000) { + spanIndex = 12; + } + //实际10000~20000s-->播放156s + if (10000 <= routePointsLength) { + spanIndex = 64; + } + drawRoute(points); + + String time = routeRecord.getCycleTime(); + String distance = routeRecord.getCycleDistance(); + String price = routeRecord.getCyclePrice(); + total_time.setText("骑行时长:" + time); + total_distance.setText("骑行距离:" + distance); + total_price.setText("余额支付:" + price); + seekbar_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + /** + * 拖动条停止拖动的时候调用 + */ + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 500); + } - /** - * 拖动条开始拖动的时候调用 - */ - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - handler.removeCallbacksAndMessages(null); - } + /** + * 拖动条开始拖动的时候调用 + */ + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + handler.removeCallbacksAndMessages(null); + } - /** - * 拖动条进度改变的时候调用 - */ - @Override - public void onProgressChanged(SeekBar seekBar, int progress, - boolean fromUser) { - currentIndex = routePointsLength * progress / 100; + /** + * 拖动条进度改变的时候调用 + */ + @Override + public void onProgressChanged(SeekBar seekBar, int progress, + boolean fromUser) { + currentIndex = routePointsLength * progress / 100; + + } + }); } - }); + }; + EagleEyeUtil.get().getTraceHistory(trackHistoryListener, startTime, endTime); } private void initMap() { - routeDetailMapView = findViewById(R.id.route_detail_mapview); - routeDetailMapView.requestDisallowInterceptTouchEvent(true); - routeDetailMapView.showZoomControls(true); - routeBaiduMap = routeDetailMapView.getMap(); + MapView mapView = findViewById(R.id.route_detail_mapview); + mapView.requestDisallowInterceptTouchEvent(true); + mapView.showZoomControls(true); + baiduMap = mapView.getMap(); + } - public void drawRoute() { - points = new ArrayList<>(); + public void drawRoute(List points) { - for (int i = 0; i < routePoints.size(); i++) { - RoutePoint point = routePoints.get(i); - LatLng latLng = new LatLng(point.getRouteLat(), point.getRouteLng()); - points.add(latLng); - } if (points.size() > 2) { OverlayOptions ooPolyline = new PolylineOptions().width(10) .color(0xFF36D19D).points(points); - routeBaiduMap.addOverlay(ooPolyline); - RoutePoint startPoint = routePoints.get(0); - LatLng startPosition = new LatLng(startPoint.getRouteLat(), startPoint.getRouteLng()); + baiduMap.addOverlay(ooPolyline); + LatLng startPosition = points.get(0); MapStatus.Builder builder = new MapStatus.Builder(); builder.target(startPosition).zoom(18.0f); - routeBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); - RoutePoint endPoint = routePoints.get(routePoints.size() - 1); - LatLng endPosition = new LatLng(endPoint.getRouteLat(), endPoint.getRouteLng()); + baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); + LatLng endPosition = points.get(routePoints.size() - 1); addOverLayout(startPosition, endPosition); } } + + private void playTraceHistory(List list) { + if (list.size() < 2) return; + OverlayOptions ooPolyline = new PolylineOptions().width(10) + .color(0xFF36D19D).points(list); + baiduMap.clear(); + baiduMap.addOverlay(ooPolyline); + LatLng newLatLng = points.get(list.size() - 1); + MarkerOptions options = new MarkerOptions().position(newLatLng) + .icon(currentBmp); + // 在地图上添加Marker,并显示 + baiduMap.addOverlay(options); + MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(newLatLng); + // 移动到某经纬度 + baiduMap.animateMapStatus(update); + } + private void addOverLayout(LatLng startPosition, LatLng endPosition) { //先清除图层 // mBaiduMap.clear(); @@ -204,11 +270,11 @@ private void addOverLayout(LatLng startPosition, LatLng endPosition) { MarkerOptions options = new MarkerOptions().position(startPosition) .icon(startBmp); // 在地图上添加Marker,并显示 - routeBaiduMap.addOverlay(options); + baiduMap.addOverlay(options); MarkerOptions options2 = new MarkerOptions().position(endPosition) .icon(endBmp); // 在地图上添加Marker,并显示 - routeBaiduMap.addOverlay(options2); + baiduMap.addOverlay(options2); } @@ -240,44 +306,30 @@ public void startReplay(View view) { isInReplay = true; tv_title.setText(R.string.route_replay); tv_route_replay.setVisibility(View.GONE); - routeBaiduMap.clear(); + baiduMap.clear(); replay_progress_layout.setVisibility(View.VISIBLE); ViewGroup.LayoutParams params = route_mapview_layout.getLayoutParams(); params.height = ViewGroup.LayoutParams.MATCH_PARENT; route_mapview_layout.setLayoutParams(params); - handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 1000); + handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 500); } - private void setPolyline(List list) { - if (list.size() < 2) return; - OverlayOptions ooPolyline = new PolylineOptions().width(10) - .color(0xFF36D19D).points(list); - routeBaiduMap.clear(); - routeBaiduMap.addOverlay(ooPolyline); - LatLng newLatLng = points.get(list.size() - 1); - MarkerOptions options = new MarkerOptions().position(newLatLng) - .icon(currentBmp); - // 在地图上添加Marker,并显示 - routeBaiduMap.addOverlay(options); - MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(newLatLng); - // 移动到某经纬度 - routeBaiduMap.animateMapStatus(update); - } public void backFromReplay() { isInReplay = false; tv_title.setText(R.string.route_detail); tv_route_replay.setVisibility(View.VISIBLE); - routeBaiduMap.clear(); + baiduMap.clear(); subList.clear(); - currentIndex = 2; - drawRoute(); + currentIndex = 1; + drawRoute(points); replay_progress_layout.setVisibility(View.GONE); ViewGroup.LayoutParams params = route_mapview_layout.getLayoutParams(); params.height = Utils.dp2px(this, 240); route_mapview_layout.setLayoutParams(params); handler.removeCallbacksAndMessages(null); + seekbar_progress.setProgress(0); } public boolean onKeyDown(int keyCode, KeyEvent event) { @@ -291,4 +343,5 @@ public boolean onKeyDown(int keyCode, KeyEvent event) { } return super.onKeyDown(keyCode, event); } + } diff --git a/BiuBike/app/src/main/java/com/biubike/adapter/MyRouteAdapter.java b/BiuBike/app/src/main/java/com/biubike/adapter/MyRouteAdapter.java index c2743dc..6009cb2 100644 --- a/BiuBike/app/src/main/java/com/biubike/adapter/MyRouteAdapter.java +++ b/BiuBike/app/src/main/java/com/biubike/adapter/MyRouteAdapter.java @@ -46,10 +46,10 @@ public void onClick(View view) { public void onBindViewHolder(MyViewHolder holder, int position) { holder.itemView.setTag(position); RouteRecord routeRecord = list.get(position); - holder.bike_time.setText(routeRecord.getCycle_time()); - holder.bike_distance.setText(routeRecord.getCycle_distance()); - holder.bike_price.setText(routeRecord.getCycle_price()); - holder.bike_date.setText(routeRecord.getCycle_date()); + holder.bike_time.setText(routeRecord.getCycleTime()); + holder.bike_distance.setText(routeRecord.getCycleDistance()); + holder.bike_price.setText(routeRecord.getCyclePrice()); + holder.bike_date.setText(routeRecord.getCycleDate()); } @Override diff --git a/BiuBike/app/src/main/java/com/biubike/adapter/PoiSuggestionAdapter.java b/BiuBike/app/src/main/java/com/biubike/adapter/PoiSuggestionAdapter.java index fa64ebb..484dc85 100644 --- a/BiuBike/app/src/main/java/com/biubike/adapter/PoiSuggestionAdapter.java +++ b/BiuBike/app/src/main/java/com/biubike/adapter/PoiSuggestionAdapter.java @@ -1,5 +1,4 @@ package com.biubike.adapter; - import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; @@ -7,20 +6,18 @@ import android.view.ViewGroup; import android.widget.TextView; +import com.baidu.mapapi.search.sug.SuggestionResult; import com.baidu.mapapi.search.sug.SuggestionResult.SuggestionInfo; import com.biubike.R; import java.util.List; -/** - * Created by gaolei on 17/1/18. - */ public class PoiSuggestionAdapter extends RecyclerView.Adapter { public Context context; private OnItemClickListener listener; - private List list; + private List list; private String from; public PoiSuggestionAdapter(Context context, List list, String from) { diff --git a/BiuBike/app/src/main/java/com/biubike/application/DemoApplication.java b/BiuBike/app/src/main/java/com/biubike/application/DemoApplication.java index eb3e8ae..815e47e 100644 --- a/BiuBike/app/src/main/java/com/biubike/application/DemoApplication.java +++ b/BiuBike/app/src/main/java/com/biubike/application/DemoApplication.java @@ -4,8 +4,7 @@ import android.os.Environment; import com.baidu.mapapi.SDKInitializer; -import com.iflytek.cloud.SpeechConstant; -import com.iflytek.cloud.SpeechUtility; +import com.biubike.map.TraceUtil; import java.io.File; @@ -20,9 +19,12 @@ public class DemoApplication extends Application { public void onCreate() { super.onCreate(); + // 若为创建独立进程,则不初始化成员变量 + if ("com.baidu.track:remote".equals(TraceUtil.getCurProcessName(this))) { + return; + } SDKInitializer.initialize(getApplicationContext()); - SpeechUtility.createUtility(this, SpeechConstant.APPID +"=58f9ff61"); -// CrashHandler crashHandler=CrashHandler.getInstance(); +// CrashHandler crashHandler=CrashHandler.get(); // crashHandler.init(this); initDirs(); } diff --git a/BiuBike/app/src/main/java/com/biubike/bean/RouteRecord.java b/BiuBike/app/src/main/java/com/biubike/bean/RouteRecord.java index 865b42a..d1f040a 100644 --- a/BiuBike/app/src/main/java/com/biubike/bean/RouteRecord.java +++ b/BiuBike/app/src/main/java/com/biubike/bean/RouteRecord.java @@ -8,52 +8,70 @@ */ public class RouteRecord implements Parcelable { - public String cycle_date; - public String cycle_time; - public String cycle_distance; + private String cycleDate; + private String cycleTime; + private String cycleDistance; + private long cycleStartTime; + private long cycleEndTime; + private String cyclePrice; + private String cyclePoints; - public String getCycle_price() { - return cycle_price; + + public long getCycleStartTime() { + return cycleStartTime; + } + + public void setCycleStartTime(long cycleStartTime) { + this.cycleStartTime = cycleStartTime; + } + + public long getCycleEndTime() { + return cycleEndTime; + } + + public void setCycleEndTime(long cycleEndTime) { + this.cycleEndTime = cycleEndTime; } - public void setCycle_price(String cycle_price) { - this.cycle_price = cycle_price; + public String getCyclePrice() { + return cyclePrice; } - public String getCycle_points() { - return cycle_points; + public void setCyclePrice(String cyclePrice) { + this.cyclePrice = cyclePrice; } - public void setCycle_points(String cycle_points) { - this.cycle_points = cycle_points; + public String getCyclePoints() { + return cyclePoints; } - public String getCycle_distance() { - return cycle_distance; + public void setCyclePoints(String cyclePoints) { + this.cyclePoints = cyclePoints; } - public void setCycle_distance(String cycle_distance) { - this.cycle_distance = cycle_distance; + public String getCycleDistance() { + return cycleDistance; } - public String getCycle_date() { - return cycle_date; + public void setCycleDistance(String cycleDistance) { + this.cycleDistance = cycleDistance; } - public void setCycle_date(String cycle_date) { - this.cycle_date = cycle_date; + public String getCycleDate() { + return cycleDate; } - public String getCycle_time() { - return cycle_time; + public void setCycleDate(String cycleDate) { + this.cycleDate = cycleDate; } - public void setCycle_time(String cycle_time) { - this.cycle_time = cycle_time; + public String getCycleTime() { + return cycleTime; } - public String cycle_price; - public String cycle_points; + public void setCycleTime(String cycleTime) { + this.cycleTime = cycleTime; + } @Override public int describeContents() { @@ -62,11 +80,13 @@ public int describeContents() { @Override public void writeToParcel(Parcel parcel, int i) { - parcel.writeString(cycle_date); - parcel.writeString(cycle_time); - parcel.writeString(cycle_distance); - parcel.writeString(cycle_price); - parcel.writeString(cycle_points); + parcel.writeString(cycleDate); + parcel.writeString(cycleTime); + parcel.writeString(cycleDistance); + parcel.writeString(cyclePrice); + parcel.writeLong(cycleStartTime); + parcel.writeLong(cycleEndTime); + parcel.writeString(cyclePoints); } public static final Parcelable.Creator CREATOR = new Creator() { @@ -78,7 +98,7 @@ public RouteRecord createFromParcel(Parcel source) { @Override public RouteRecord[] newArray(int size) { -// TODO Auto-generated method stub + // TODO Auto-generated method stub return new RouteRecord[size]; } }; @@ -87,10 +107,12 @@ public RouteRecord() { } private RouteRecord(Parcel source) { - cycle_date = source.readString(); - cycle_time = source.readString(); - cycle_distance = source.readString(); - cycle_price = source.readString(); - cycle_points = source.readString(); + cycleDate = source.readString(); + cycleTime = source.readString(); + cycleDistance = source.readString(); + cyclePrice = source.readString(); + cycleStartTime = source.readLong(); + cycleEndTime = source.readLong(); + cyclePoints = source.readString(); } } diff --git a/BiuBike/app/src/main/java/com/biubike/database/RouteDBHelper.java b/BiuBike/app/src/main/java/com/biubike/database/RouteDBHelper.java index 4e5b1b8..521fcf1 100644 --- a/BiuBike/app/src/main/java/com/biubike/database/RouteDBHelper.java +++ b/BiuBike/app/src/main/java/com/biubike/database/RouteDBHelper.java @@ -19,10 +19,14 @@ public void onCreate(SQLiteDatabase db) { //创建一个数据库 db.execSQL("CREATE TABLE IF NOT EXISTS cycle_route (route_id integer primary key autoincrement ," + "cycle_date text not null ," + + "cycle_start_time long not null ," + + "cycle_end_time long not null ," + "cycle_time text not null ," + "cycle_distance text not null ," + "cycle_price text not null ," + - "cycle_points text not null )"); + "cycle_points text not null )" + + ); } @Override diff --git a/BiuBike/app/src/main/java/com/biubike/map/BitmapUtil.java b/BiuBike/app/src/main/java/com/biubike/map/BitmapUtil.java new file mode 100644 index 0000000..8a64e51 --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/map/BitmapUtil.java @@ -0,0 +1,57 @@ +package com.biubike.map; + +import android.content.Context; +import android.content.res.Resources; + +import com.baidu.mapapi.map.BitmapDescriptor; +import com.baidu.mapapi.map.BitmapDescriptorFactory; +import com.biubike.R; + +/** + * Created by baidu on 17/3/8. + */ + +public class BitmapUtil { + + public static BitmapDescriptor bmArrowPoint = null; + + public static BitmapDescriptor bmStart = null; + + public static BitmapDescriptor bmEnd = null; + + public static BitmapDescriptor bmGeo = null; + + public static BitmapDescriptor bmGcoding = null; + + /** + * 创建bitmap,在MainActivity onCreate()中调用 + */ + public static void init() { + bmArrowPoint = BitmapDescriptorFactory.fromResource(R.mipmap.icon_point); + bmStart = BitmapDescriptorFactory.fromResource(R.mipmap.route_start); + bmEnd = BitmapDescriptorFactory.fromResource(R.mipmap.route_end); + bmGeo = BitmapDescriptorFactory.fromResource(R.mipmap.icon_geo); + bmGcoding = BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding); + } + + /** + * 回收bitmap,在MainActivity onDestroy()中调用 + */ + public static void clear() { + bmArrowPoint.recycle(); + bmStart.recycle(); + bmEnd.recycle(); + bmGeo.recycle(); + } + + public static BitmapDescriptor getMark(Context context, int index) { + Resources res = context.getResources(); + int resourceId; + if (index <= 10) { + resourceId = res.getIdentifier("icon_mark" + index, "mipmap", context.getPackageName()); + } else { + resourceId = res.getIdentifier("icon_markx", "mipmap", context.getPackageName()); + } + return BitmapDescriptorFactory.fromResource(resourceId); + } +} diff --git a/BiuBike/app/src/main/java/com/biubike/map/Constants.java b/BiuBike/app/src/main/java/com/biubike/map/Constants.java new file mode 100644 index 0000000..ef656be --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/map/Constants.java @@ -0,0 +1,54 @@ +package com.biubike.map; + +/** + * Created by baidu on 17/1/12. + */ + +public final class Constants { + + public static final String TAG = "BaiduTraceSDK_V3"; + + public static final int REQUEST_CODE = 1; + + public static final int RESULT_CODE = 1; + + public static final int DEFAULT_RADIUS_THRESHOLD = 0; + + public static final int PAGE_SIZE = 5000; + + /** + * 轨迹分析查询间隔时间(1分钟) + */ + public static final int ANALYSIS_QUERY_INTERVAL = 60; + + /** + * 停留点默认停留时间(1分钟) + */ + public static final int STAY_TIME = 60; + + /** + * 启动停留时间 + */ + public static final int SPLASH_TIME = 3000; + + /** + * 默认采集周期 + */ + public static final int DEFAULT_GATHER_INTERVAL = 5; + + /** + * 默认打包周期 + */ + public static final int DEFAULT_PACK_INTERVAL = 30; + + /** + * 实时定位间隔(单位:秒) + */ + public static final int LOC_INTERVAL = 10; + + /** + * 最后一次定位信息 + */ + public static final String LAST_LOCATION = "last_location"; + +} diff --git a/BiuBike/app/src/main/java/com/biubike/map/CurrentLocation.java b/BiuBike/app/src/main/java/com/biubike/map/CurrentLocation.java new file mode 100644 index 0000000..41b0c16 --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/map/CurrentLocation.java @@ -0,0 +1,23 @@ +package com.biubike.map; + +/** + * 当前位置信息 + * Created by baidu on 17/2/8. + */ +public class CurrentLocation { + + /** + * 定位时间(单位:秒) + */ + public static long locTime; + + /** + * 纬度 + */ + public static double latitude; + + /** + * 经度 + */ + public static double longitude; +} diff --git a/BiuBike/app/src/main/java/com/biubike/map/EagleEyeUtil.java b/BiuBike/app/src/main/java/com/biubike/map/EagleEyeUtil.java new file mode 100644 index 0000000..dabd21b --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/map/EagleEyeUtil.java @@ -0,0 +1,253 @@ +package com.biubike.map; + +import android.app.Notification; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.PowerManager; + +import com.baidu.trace.LBSTraceClient; +import com.baidu.trace.Trace; +import com.baidu.trace.api.entity.LocRequest; +import com.baidu.trace.api.track.DistanceRequest; +import com.baidu.trace.api.track.HistoryTrackRequest; +import com.baidu.trace.api.track.OnTrackListener; +import com.baidu.trace.api.track.SupplementMode; +import com.baidu.trace.model.BaseRequest; +import com.baidu.trace.model.ProcessOption; +import com.baidu.trace.model.StatusCodes; +import com.baidu.trace.model.TransportMode; +import com.biubike.receiver.TrackReceiver; +import com.biubike.util.ContextUtil; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import static android.content.Context.MODE_PRIVATE; + +public class EagleEyeUtil { + + // 轨迹服务ID + public long serviceId = 217606; + // 设备标识 + public String entityName = "Android"+UUID.randomUUID(); + public AtomicInteger mSequenceGenerator = new AtomicInteger(); + public LocRequest locRequest = null; + public SharedPreferences trackConf = null; + private PowerManager powerManager = null; + + private PowerManager.WakeLock wakeLock = null; + // 定位周期(单位:秒) + public int gatherInterval = 2; + // 打包回传周期(单位:秒) + public int packInterval = 4; + /** + * 轨迹服务 + */ + public Trace mTrace = null; + private TrackReceiver trackReceiver = null; + /** + * 服务是否开启标识 + */ + public boolean isTraceStarted = false; + + /** + * 采集是否开启标识 + */ + public boolean isGatherStarted = false; + public boolean isRegisterReceiver = false; + + private EagleEyeUtil() { + locRequest = new LocRequest(serviceId); + powerManager = (PowerManager) ContextUtil.getAppContext().getSystemService(Context.POWER_SERVICE); + + trackConf = ContextUtil.getApp().getSharedPreferences("track_conf", MODE_PRIVATE); + } + + public static class InstanceHolder { + static EagleEyeUtil instance = new EagleEyeUtil(); + } + + public static EagleEyeUtil get() { + + return InstanceHolder.instance; + + } + + public LBSTraceClient mTraceClient; + + + /* + 简介 + + 鹰眼为每一个应用提供1000万终端以上轨迹管理能力,并且支持全球轨迹追踪。 + 鹰眼提供多种API和SDK供开发者从各种终端追踪轨迹,如:手机、GPS定位器、智能后视镜等硬件设备。此外,鹰眼也支持开发者从服务端上传轨迹。 + 鹰眼为开发者免费存储最近1年的轨迹数据。鹰眼采用多机房多实例分布式存储,并定期自动备份,保障数据存储安全。 + */ + + public void initTrace(Notification notification) { + + + // 是否需要对象存储服务,默认为:false,关闭对象存储服务。注:鹰眼 Android SDK v3.0以上版本支持随轨迹上传图像等对象数据,若需使用此功能,该参数需设为 true,且需导入bos-android-sdk-1.0.2.jar。 + boolean isNeedObjectStorage = false; + // 初始化轨迹服务 + mTrace = new Trace(serviceId, entityName, isNeedObjectStorage); + mTrace.setNotification(notification); + // 初始化轨迹服务客户端 + mTraceClient = new LBSTraceClient(ContextUtil.getAppContext()); + + // 设置定位和打包周期 + mTraceClient.setInterval(gatherInterval, packInterval); + + + } + + /* + 简介 + + 轨迹查询:利用鹰眼高性能轨迹查询服务,开发者实时查询任意时段的轨迹。 + 实时查询是指:轨迹点一旦成功上传到鹰眼云端,在小于100毫秒的时间内,即可通过接口查询到该轨迹点。 + 鹰眼还提供轨迹批量导出功能,供开发者下载历史轨迹数据。 + 轨迹纠偏:为纠正轨迹漂移,鹰眼提供专业的轨迹纠偏绑路。利用该服务,开发者可纠正轨迹漂移,展示平滑连贯的轨迹。 + 鹰眼分别针对驾车、骑行、步行提供了不同的轨迹纠偏绑路算法,适用于多种交通工具的轨迹校正。 + */ + + public void getTraceHistory(OnTrackListener mTrackListener, long startTime, long endTime) { + // 请求标识 + int tag = 1; + + // 创建历史轨迹请求实例 + HistoryTrackRequest historyTrackRequest = new HistoryTrackRequest(tag, serviceId, entityName); +// // 开始时间2017-4-17 0:0:0的UNIX 时间戳 +// long startTime = 1492358400; +// // 结束时间2017-4-17 23:59:59的UNIX 时间戳 +// long endTime = 1492444799; + // 设置开始时间 + historyTrackRequest.setStartTime(startTime); + // 设置结束时间 + historyTrackRequest.setEndTime(endTime); + // 设置需要纠偏 + historyTrackRequest.setProcessed(true); + // 创建纠偏选项实例 + ProcessOption processOption = new ProcessOption(); + // 设置需要去噪 + processOption.setNeedDenoise(true); + // 设置需要抽稀 + processOption.setNeedVacuate(true); + // 设置需要绑路 + processOption.setNeedMapMatch(true); + // 设置精度过滤值(定位精度大于100米的过滤掉) + processOption.setRadiusThreshold(100); + // 设置交通方式为驾车 + processOption.setTransportMode(TransportMode.riding); + // 设置纠偏选项 + historyTrackRequest.setProcessOption(processOption); + // 设置里程填充方式为驾车 + historyTrackRequest.setSupplementMode(SupplementMode.riding); + // 初始化轨迹监听器 + + // 查询轨迹 + mTraceClient.queryHistoryTrack(historyTrackRequest, mTrackListener); + } + + /* + 简介 + + 鹰眼Android SDK提供了queryDistance()方法,用于计算指定时间段内的轨迹里程, + 支持:计算纠偏后的里程,用路线规划补偿中断轨迹的里程。 + */ + public void getTraceDistance(OnTrackListener mTrackListener, long startTime, long endTime) { + // 请求标识 + int tag = 2; + + // 创建里程查询请求实例 + DistanceRequest distanceRequest = new DistanceRequest(tag, serviceId, entityName); +// // 开始时间(单位:秒) +// long startTime = System.currentTimeMillis() / 1000 - 12 * 60 * 60; +// // 结束时间(单位:秒) +// long endTime = System.currentTimeMillis() / 1000; + // 设置开始时间 + distanceRequest.setStartTime(startTime); + // 设置结束时间 + distanceRequest.setEndTime(endTime); + // 设置需要纠偏 + distanceRequest.setProcessed(true); + // 创建纠偏选项实例 + ProcessOption processOption = new ProcessOption(); + // 设置需要去噪 + processOption.setNeedDenoise(true); + // 设置需要绑路 + processOption.setNeedMapMatch(true); + // 设置交通方式为驾车 + processOption.setTransportMode(TransportMode.riding); + // 设置纠偏选项 + distanceRequest.setProcessOption(processOption); + // 设置里程填充方式为驾车 + distanceRequest.setSupplementMode(SupplementMode.riding); +// // 初始化轨迹监听器 +// OnTrackListener mTrackListener = new OnTrackListener() { +// @Override +// public void onDistanceCallback(DistanceResponse response) { +// // 里程回调 +// } +// }; + // 查询里程 + mTraceClient.queryDistance(distanceRequest, mTrackListener); + } + + + /** + * 初始化请求公共参数 + * + * @param request + */ + public void initRequest(BaseRequest request) { + request.setTag(getTag()); + request.setServiceId(serviceId); + } + + /** + * 获取请求标识 + * + * @return + */ + public int getTag() { + return mSequenceGenerator.incrementAndGet(); + } + + /** + * 注册广播(电源锁、GPS状态) + */ + public void registerReceiver() { + if (isRegisterReceiver) { + return; + } + + if (null == wakeLock) { + wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload"); + } + if (null == trackReceiver) { + trackReceiver = new TrackReceiver(wakeLock); + } + + IntentFilter filter = new IntentFilter(); + filter.addAction(Intent.ACTION_SCREEN_OFF); + filter.addAction(Intent.ACTION_SCREEN_ON); + filter.addAction(Intent.ACTION_USER_PRESENT); + filter.addAction(StatusCodes.GPS_STATUS_ACTION); + ContextUtil.getAppContext().registerReceiver(trackReceiver, filter); + isRegisterReceiver = true; + + } + + public void unregisterPowerReceiver() { + if (!isRegisterReceiver) { + return; + } + if (null != trackReceiver) { + ContextUtil.getAppContext().unregisterReceiver(trackReceiver); + } + isRegisterReceiver = false; + } +} diff --git a/BiuBike/app/src/main/java/com/biubike/util/LocationManager.java b/BiuBike/app/src/main/java/com/biubike/map/LocationManager.java similarity index 88% rename from BiuBike/app/src/main/java/com/biubike/util/LocationManager.java rename to BiuBike/app/src/main/java/com/biubike/map/LocationManager.java index ed284cd..2999256 100644 --- a/BiuBike/app/src/main/java/com/biubike/util/LocationManager.java +++ b/BiuBike/app/src/main/java/com/biubike/map/LocationManager.java @@ -1,4 +1,4 @@ -package com.biubike.util; +package com.biubike.map; import com.baidu.mapapi.model.LatLng; @@ -8,8 +8,8 @@ public class LocationManager { - LatLng currentLL; - String address; + private LatLng currentLL; + private String address; public String getAddress() { return address; diff --git a/BiuBike/app/src/main/java/com/biubike/map/LocationUtil.java b/BiuBike/app/src/main/java/com/biubike/map/LocationUtil.java new file mode 100644 index 0000000..3d79339 --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/map/LocationUtil.java @@ -0,0 +1,114 @@ +package com.biubike.map; + +import android.app.Notification; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; + +import com.baidu.location.BDAbstractLocationListener; +import com.baidu.location.BDLocation; +import com.baidu.location.LocationClient; +import com.baidu.location.LocationClientOption; +import com.biubike.MainActivity; +import com.biubike.R; + +public class LocationUtil { + + LocationClient locationClient; + + /** + * 初始化定位参数配置 + */ + + private void initLocationOption(Context context) { +//定位服务的客户端。宿主程序在客户端声明此类,并调用,目前只支持在主线程中启动 + locationClient = new LocationClient(context.getApplicationContext()); +//声明LocationClient类实例并配置定位参数 + LocationClientOption locationOption = new LocationClientOption(); + MyLocationListener myLocationListener = new MyLocationListener(); +//注册监听函数 + locationClient.registerLocationListener(myLocationListener); +//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 + locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); +//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll; + locationOption.setCoorType("gcj02"); +//可选,默认0,即仅定位一次,设置发起连续定位请求的间隔需要大于等于1000ms才是有效的 + locationOption.setScanSpan(1000); +//可选,设置是否需要地址信息,默认不需要 + locationOption.setIsNeedAddress(true); +//可选,设置是否需要地址描述 + locationOption.setIsNeedLocationDescribe(true); +//可选,设置是否需要设备方向结果 + locationOption.setNeedDeviceDirect(false); +//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 + locationOption.setLocationNotify(true); +//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 + locationOption.setIgnoreKillProcess(true); +//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” + locationOption.setIsNeedLocationDescribe(true); +//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 + locationOption.setIsNeedLocationPoiList(true); +//可选,默认false,设置是否收集CRASH信息,默认收集 + locationOption.SetIgnoreCacheException(false); +//可选,默认false,设置是否开启Gps定位 + locationOption.setOpenGps(true); +//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用 + locationOption.setIsNeedAltitude(false); +//设置打开自动回调位置模式,该开关打开后,期间只要定位SDK检测到位置变化就会主动回调给开发者,该模式下开发者无需再关心定位间隔是多少,定位SDK本身发现位置变化就会及时回调给开发者 + locationOption.setOpenAutoNotifyMode(); +//设置打开自动回调位置模式,该开关打开后,期间只要定位SDK检测到位置变化就会主动回调给开发者 + locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT); +//需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用 + locationClient.setLocOption(locationOption); +//开始定位 + locationClient.start(); + } + + /** + * 实现定位回调 + */ + public class MyLocationListener extends BDAbstractLocationListener { + @Override + public void onReceiveLocation(BDLocation location) { + //此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果 + //以下只列举部分获取经纬度相关(常用)的结果信息 + //更多结果信息获取说明,请参照类参考中BDLocation类中的说明 + + //获取纬度信息 + double latitude = location.getLatitude(); + //获取经度信息 + double longitude = location.getLongitude(); + //获取定位精度,默认值为0.0f + float radius = location.getRadius(); + //获取经纬度坐标类型,以LocationClientOption中设置过的坐标类型为准 + String coorType = location.getCoorType(); + //获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明 + int errorCode = location.getLocType(); + + } + } + + private void startBackgroundLocation(Context context) { + //核心实现代码如下,详细代码请参考官网Demo。 +//开启前台定位服务: + Notification.Builder builder = new Notification.Builder(context.getApplicationContext()); +//获取一个Notification构造器 + + Intent nfIntent = new Intent(context.getApplicationContext(), MainActivity.class); + builder.setContentIntent(PendingIntent.getActivity(context, 0, nfIntent, 0)) // 设置PendingIntent + .setContentTitle("正在进行后台定位") // 设置下拉列表里的标题 + .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标 + .setContentText("后台定位通知") // 设置上下文内容 + .setAutoCancel(true) + .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间 + Notification notification = null; + notification = builder.build(); + notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音 + locationClient.enableLocInForeground(1001, notification);// 调起前台定位 +//停止前台定位服务: + locationClient.disableLocInForeground(true);// 关闭前台定位,同时移除通知栏 + + + } + +} diff --git a/BiuBike/app/src/main/java/com/biubike/map/MapUtil.java b/BiuBike/app/src/main/java/com/biubike/map/MapUtil.java new file mode 100644 index 0000000..b74a67c --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/map/MapUtil.java @@ -0,0 +1,321 @@ +package com.biubike.map; + +import android.graphics.Color; +import android.graphics.Point; +import android.os.Bundle; + +import com.baidu.mapapi.map.BaiduMap; +import com.baidu.mapapi.map.BitmapDescriptor; +import com.baidu.mapapi.map.MapStatus; +import com.baidu.mapapi.map.MapStatusUpdateFactory; +import com.baidu.mapapi.map.MapView; +import com.baidu.mapapi.map.Marker; +import com.baidu.mapapi.map.MarkerOptions; +import com.baidu.mapapi.map.Overlay; +import com.baidu.mapapi.map.OverlayOptions; +import com.baidu.mapapi.map.PolylineOptions; +import com.baidu.mapapi.model.LatLng; +import com.baidu.mapapi.utils.CoordinateConverter; +import com.baidu.trace.model.CoordType; +import com.baidu.trace.model.SortType; +import com.baidu.trace.model.TraceLocation; +import com.biubike.util.ContextUtil; +import com.biubike.util.Utils; + +import java.util.List; + +import static com.biubike.map.BitmapUtil.bmArrowPoint; +import static com.biubike.map.BitmapUtil.bmStart; + +/** + * Created by baidu on 17/2/9. + */ + +public class MapUtil { + + private static MapUtil INSTANCE = new MapUtil(); + + private MapStatus mapStatus = null; + + private Marker mMoveMarker = null; + + public MapView mapView = null; + + public BaiduMap baiduMap = null; + + public LatLng lastPoint = null; + + /** + * 路线覆盖物 + */ + public Overlay polylineOverlay = null; + + private MapUtil() { + } + + public static MapUtil getInstance() { + return INSTANCE; + } + + public void init(MapView view) { + mapView = view; + baiduMap = mapView.getMap(); + } + + public void onPause() { + if (null != mapView) { + mapView.onPause(); + } + } + + public void onResume() { + if (null != mapView) { + mapView.onResume(); + } + } + + public void clear() { + lastPoint = null; + if (null != mMoveMarker) { + mMoveMarker.remove(); + mMoveMarker = null; + } + if (null != polylineOverlay) { + polylineOverlay.remove(); + polylineOverlay = null; + } + if (null != baiduMap) { + baiduMap.clear(); + baiduMap = null; + } + mapStatus = null; + if (null != mapView) { + mapView.onDestroy(); + mapView = null; + } + } + + /** + * 将轨迹实时定位点转换为地图坐标 + * + * @param location + * @return + */ + public static LatLng convertTraceLocation2Map(TraceLocation location) { + if (null == location) { + return null; + } + double latitude = location.getLatitude(); + double longitude = location.getLongitude(); + if (Math.abs(latitude - 0.0) < 0.000001 && Math.abs(longitude - 0.0) < 0.000001) { + return null; + } + LatLng currentLatLng = new LatLng(latitude, longitude); + if (CoordType.wgs84 == location.getCoordType()) { + LatLng sourceLatLng = currentLatLng; + CoordinateConverter converter = new CoordinateConverter(); + converter.from(CoordinateConverter.CoordType.GPS); + converter.coord(sourceLatLng); + currentLatLng = converter.convert(); + } + return currentLatLng; + } + + /** + * 将地图坐标转换轨迹坐标 + * + * @param latLng + * @return + */ + public static LatLng convertMap2Trace(LatLng latLng) { + return new LatLng(latLng.latitude, latLng.longitude); + } + + /** + * 将轨迹坐标对象转换为地图坐标对象 + * + * @param traceLatLng + * @return + */ + public static LatLng convertTrace2Map(com.baidu.trace.model.LatLng traceLatLng) { + return new LatLng(traceLatLng.latitude, traceLatLng.longitude); + } + + + public void updateStatus(LatLng currentPoint, boolean showMarker) { + if (null == baiduMap || null == currentPoint) { + return; + } + + if (null != baiduMap.getProjection()) { + Point screenPoint = baiduMap.getProjection().toScreenLocation(currentPoint); + // 点在屏幕上的坐标超过限制范围,则重新聚焦底图 + if (screenPoint.y < 200 || screenPoint.y > Utils.getScreenHeight(ContextUtil.getAppContext()) - 500 + || screenPoint.x < 200 || screenPoint.x > Utils.getScreenWidth(ContextUtil.getAppContext()) - 200 + || null == mapStatus) { + setMapZoomStatus(currentPoint, 19f); + } + } else if (null == mapStatus) { + // 第一次定位时,聚焦底图 + setMapZoomStatus(currentPoint, 19f); + } + + if (showMarker) { + addMarker(currentPoint); + } + + } + + public Marker addOverlay(LatLng currentPoint, BitmapDescriptor icon, Bundle bundle) { + OverlayOptions overlayOptions = new MarkerOptions().position(currentPoint) + .icon(icon).zIndex(9).draggable(true); + Marker marker = (Marker) baiduMap.addOverlay(overlayOptions); + if (null != bundle) { + marker.setExtraInfo(bundle); + } + return marker; + } + + /** + * 添加地图覆盖物 + */ + public void addMarker(LatLng currentPoint) { + if (null == mMoveMarker) { + mMoveMarker = addOverlay(currentPoint, bmArrowPoint, null); + return; + } + + if (null != lastPoint) { + moveLooper(currentPoint); + } else { + lastPoint = currentPoint; + mMoveMarker.setPosition(currentPoint); + } + } + + /** + * 移动逻辑 + */ + public void moveLooper(LatLng endPoint) { + + mMoveMarker.setPosition(lastPoint); + mMoveMarker.setRotate((float) TraceUtil.getAngle(lastPoint, endPoint)); + + double slope = TraceUtil.getSlope(lastPoint, endPoint); + // 是不是正向的标示(向上设为正向) + boolean isReverse = (lastPoint.latitude > endPoint.latitude); + double intercept = TraceUtil.getInterception(slope, lastPoint); + double xMoveDistance = isReverse ? TraceUtil.getXMoveDistance(slope) : -1 * TraceUtil.getXMoveDistance(slope); + + for (double latitude = lastPoint.latitude; latitude > endPoint.latitude == isReverse; latitude = + latitude - xMoveDistance) { + LatLng latLng; + if (slope != Double.MAX_VALUE) { + latLng = new LatLng(latitude, (latitude - intercept) / slope); + } else { + latLng = new LatLng(latitude, lastPoint.longitude); + } + mMoveMarker.setPosition(latLng); + } + } + + /** + * 绘制历史轨迹 + */ + public void drawHistoryTrack(List points, SortType sortType, boolean isClear) { + + if (isClear) { + baiduMap.clear(); + } + if (points == null || points.size() == 0) { + if (null != polylineOverlay) { + polylineOverlay.remove(); + polylineOverlay = null; + } + return; + } + + if (points.size() == 1) { + OverlayOptions startOptions = new MarkerOptions().position(points.get(0)).icon(bmStart) + .zIndex(9).draggable(true); + baiduMap.addOverlay(startOptions); + setMapZoomStatus(points.get(0), 20); + return; + } + + LatLng startPoint; + LatLng endPoint; + if (sortType == SortType.asc) { + startPoint = points.get(0); + endPoint = points.get(points.size() - 1); + } else { + startPoint = points.get(points.size() - 1); + endPoint = points.get(0); + } + +// // 添加起点图标 +// OverlayOptions startOptions = new MarkerOptions() +// .position(startPoint).icon(bmStart) +// .zIndex(9).draggable(true); +// // 添加终点图标 +// OverlayOptions endOptions = new MarkerOptions().position(endPoint) +// .icon(bmEnd).zIndex(9).draggable(true); + + // 添加路线(轨迹) + OverlayOptions polylineOptions = new PolylineOptions().width(10) + .color(Color.BLUE).points(points); + +// baiduMap.addOverlay(startOptions); +// baiduMap.addOverlay(endOptions); + polylineOverlay = baiduMap.addOverlay(polylineOptions); + + OverlayOptions markerOptions = + new MarkerOptions().flat(true).anchor(0.5f, 0.5f).icon(bmArrowPoint) + .position(points.get(points.size() - 1)); + mMoveMarker = (Marker) baiduMap.addOverlay(markerOptions); + +// animateMapStatus(points); + } + + + private void addOverLayout(LatLng startPosition, LatLng endPosition) { + //先清除图层 + // mBaiduMap.clear(); + // 定义Maker坐标点 + // 构建MarkerOption,用于在地图上添加Marker + MarkerOptions options = new MarkerOptions().position(startPosition) + .icon(bmStart); + // 在地图上添加Marker,并显示 + baiduMap.addOverlay(options); +// MarkerOptions options2 = new MarkerOptions().position(endPosition) +// .icon(endBmp); +// // 在地图上添加Marker,并显示 +// baiduMap.addOverlay(options2); + + } + + + public void setMapZoomStatus(LatLng point, float zoom) { + MapStatus.Builder builder = new MapStatus.Builder(); + mapStatus = builder.target(point).zoom(zoom).build(); + baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus)); + } + + + /** + * 设置地图中心:使用已有定位信息; + */ + public void setCenter(LatLng point) { + MapStatus.Builder builder = new MapStatus.Builder(); + mapStatus = builder.target(point).build(); + baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus)); + } + + public void refresh() { + LatLng mapCenter = baiduMap.getMapStatus().target; + float mapZoom = baiduMap.getMapStatus().zoom - 1.0f; + setMapZoomStatus(mapCenter, mapZoom); + } + +} + diff --git a/BiuBike/app/src/main/java/com/biubike/map/MyOrientationListener.java b/BiuBike/app/src/main/java/com/biubike/map/MyOrientationListener.java deleted file mode 100644 index 49d5be1..0000000 --- a/BiuBike/app/src/main/java/com/biubike/map/MyOrientationListener.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.biubike.map; - -import android.content.Context; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; - -public class MyOrientationListener implements SensorEventListener { - - private SensorManager mSensorManager; - private Sensor mSensor; - private Context mContext; - private float lastX; - private OnOrientationListener mOnOrientationListener; - - public MyOrientationListener(Context context) - { - this.mContext=context; - } - public void start() - { - mSensorManager= (SensorManager) mContext - .getSystemService(Context.SENSOR_SERVICE); - if(mSensorManager!= null) - { - //获得方向传感器 - mSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); - } - //判断是否有方向传感器 - if(mSensor!=null) - { - //注册监听器 - mSensorManager.registerListener(this,mSensor, SensorManager.SENSOR_DELAY_UI); - - } - - - } - public void stop() - { - mSensorManager.unregisterListener(this); - - } - //方向改变 - @Override - public void onSensorChanged(SensorEvent event) { - if(event.sensor.getType()== Sensor.TYPE_ORIENTATION) - { - float x=event.values[SensorManager.DATA_X]; - if(Math.abs(x-lastX)>1.0) - { - if(mOnOrientationListener!=null) - { - mOnOrientationListener.onOrientationChanged(x); - } - } - lastX=x; - - } - - } - public void setOnOrientationListener(OnOrientationListener listener) - { - mOnOrientationListener=listener; - } - - public interface OnOrientationListener - { - void onOrientationChanged(float x); - - } - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - - } -} diff --git a/BiuBike/app/src/main/java/com/biubike/map/RouteLineAdapter.java b/BiuBike/app/src/main/java/com/biubike/map/RouteLineAdapter.java deleted file mode 100644 index 9462372..0000000 --- a/BiuBike/app/src/main/java/com/biubike/map/RouteLineAdapter.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. - */ -package com.biubike.map; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.TextView; - -import com.baidu.mapapi.search.core.RouteLine; -import com.biubike.R; - -import java.util.List; - -public class RouteLineAdapter extends BaseAdapter { - - private List routeLines; - private LayoutInflater layoutInflater; - private Type mtype; - - public RouteLineAdapter(Context context, List routeLines, Type type) { - this.routeLines = routeLines; - layoutInflater = LayoutInflater.from( context); - mtype = type; - } - - @Override - public int getCount() { - return routeLines.size(); - } - - @Override - public Object getItem(int position) { - return position; - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - NodeViewHolder holder; - if (convertView == null) { - convertView = layoutInflater.inflate(R.layout.activity_transit_item, null); - holder = new NodeViewHolder(); - holder.name = (TextView) convertView.findViewById(R.id.transitName); - holder.lightNum = (TextView) convertView.findViewById(R.id.lightNum); - holder.dis = (TextView) convertView.findViewById(R.id.dis); - convertView.setTag(holder); - } else { - holder = (NodeViewHolder) convertView.getTag(); - } - - switch (mtype) { - case TRANSIT_ROUTE: - case WALKING_ROUTE: - case BIKING_ROUTE: - holder.name.setText("路线" + (position + 1)); - int time = routeLines.get(position).getDuration(); - if ( time / 3600 == 0 ) { - holder.lightNum.setText( "大约需要:" + time / 60 + "分钟" ); - } else { - holder.lightNum.setText( "大约需要:" + time / 3600 + "小时" + (time % 3600) / 60 + "分钟" ); - } - holder.dis.setText("距离大约是:" + routeLines.get(position).getDistance() + "米"); - break; - -// case DRIVING_ROUTE: -// DrivingRouteLine drivingRouteLine = (DrivingRouteLine) routeLines.get(position); -// holder.name.setText( "线路" + (position + 1)); -// holder.lightNum.setText( "红绿灯数:" + drivingRouteLine.getLightNum()); -// holder.dis.setText("拥堵距离为:" + drivingRouteLine.getCongestionDistance() + "米"); -// break; -// case MASS_TRANSIT_ROUTE: -// MassTransitRouteLine massTransitRouteLine = (MassTransitRouteLine) routeLines.get(position); -// holder.name.setText("线路" + (position + 1)); -// holder.lightNum.setText( "预计达到时间:" + massTransitRouteLine.getArriveTime() ); -// holder.dis.setText("总票价:" + massTransitRouteLine.getPrice() + "元"); -// break; - - default: - break; - - } - - return convertView; - } - - private class NodeViewHolder { - - private TextView name; - private TextView lightNum; - private TextView dis; - } - - public enum Type { - MASS_TRANSIT_ROUTE, // 综合交通 - TRANSIT_ROUTE, // 公交 - DRIVING_ROUTE, // 驾车 - WALKING_ROUTE, // 步行 - BIKING_ROUTE // 骑行 - - } -} diff --git a/BiuBike/app/src/main/java/com/biubike/map/TraceUtil.java b/BiuBike/app/src/main/java/com/biubike/map/TraceUtil.java new file mode 100644 index 0000000..74a7542 --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/map/TraceUtil.java @@ -0,0 +1,201 @@ +package com.biubike.map; + +import android.app.ActivityManager; +import android.content.Context; +import android.content.SharedPreferences; + +import com.baidu.mapapi.model.LatLng; + +import java.sql.Timestamp; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +/** + * Created by baidu on 17/1/23. + */ + +public class TraceUtil { + + private static DecimalFormat df = new DecimalFormat("######0.00"); + + private static final double DISTANCE = 0.0001; + + private static final String ENTITY_NAME = "myTrace"; + + public static String getCurProcessName(Context context) { + int pid = android.os.Process.myPid(); + ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); + for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) { + if (appProcess.pid == pid) { + return appProcess.processName; + } + } + return ""; + } + + /** + * 获取当前时间戳(单位:秒) + * + * @return + */ + public static long getCurrentTime() { + return System.currentTimeMillis() / 1000; + } + + /** + * 校验double数值是否为0 + * + * @param value + * + * @return + */ + public static boolean isEqualToZero(double value) { + return Math.abs(value - 0.0) < 0.01; + } + + /** + * 经纬度是否为(0,0)点 + * + * @return + */ + public static boolean isZeroPoint(double latitude, double longitude) { + return isEqualToZero(latitude) && isEqualToZero(longitude); + } + + /** + * 将字符串转为时间戳 + */ + public static long toTimeStamp(String time) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", + Locale.CHINA); + Date date; + try { + date = sdf.parse(time); + } catch (ParseException e) { + e.printStackTrace(); + return 0; + } + return date.getTime() / 1000; + } + + /** + * 获取时分秒 + * + * @param timestamp 时间戳(单位:毫秒) + * + * @return + */ + public static String getHMS(long timestamp) { + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); + try { + return sdf.format(new Timestamp(timestamp)); + } catch (Exception e) { + e.printStackTrace(); + } + return String.valueOf(timestamp); + } + + /** + * 获取年月日 时分秒 + * + * @param timestamp 时间戳(单位:毫秒) + * + * @return + */ + public static String formatTime(long timestamp) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); + try { + return sdf.format(new Timestamp(timestamp)); + } catch (Exception e) { + e.printStackTrace(); + } + return String.valueOf(timestamp); + } + + public static String formatSecond(int second) { + String format = "%1$,02d:%2$,02d:%3$,02d"; + int hours = second / (60 * 60); + int minutes = second / 60 - hours * 60; + int seconds = second - minutes * 60 - hours * 60 * 60; + Object[] array = new Object[] {hours, minutes, seconds}; + return String.format(format, array); + } + + public static String formatDouble(double doubleValue) { + return df.format(doubleValue); + } + + /** + * 计算x方向每次移动的距离 + */ + public static double getXMoveDistance(double slope) { + if (slope == Double.MAX_VALUE) { + return DISTANCE; + } + return Math.abs((DISTANCE * slope) / Math.sqrt(1 + slope * slope)); + } + + /** + * 根据点和斜率算取截距 + */ + public static double getInterception(double slope, LatLng point) { + return point.latitude - slope * point.longitude; + } + + /** + * 算斜率 + */ + public static double getSlope(LatLng fromPoint, LatLng toPoint) { + if (toPoint.longitude == fromPoint.longitude) { + return Double.MAX_VALUE; + } + return (toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude); + } + + /** + * 根据两点算取图标转的角度 + */ + public static double getAngle(LatLng fromPoint, LatLng toPoint) { + double slope = getSlope(fromPoint, toPoint); + if (slope == Double.MAX_VALUE) { + if (toPoint.latitude > fromPoint.latitude) { + return 0; + } else { + return 180; + } + } + float deltAngle = 0; + if ((toPoint.latitude - fromPoint.latitude) * slope < 0) { + deltAngle = 180; + } + double radio = Math.atan(slope); + return 180 * (radio / Math.PI) + deltAngle - 90; + } + + /** + * 保存当前定位点 + */ + public static void saveCurrentLocation() { + SharedPreferences.Editor editor = EagleEyeUtil.get().trackConf.edit(); + String locationInfo = CurrentLocation.locTime + + ";" + + CurrentLocation.latitude + + ";" + + CurrentLocation.longitude; + editor.putString(Constants.LAST_LOCATION, locationInfo); + editor.apply(); + } + + /** + * 获取EntityName + * + * @return EntityName + */ + public static String getEntityName() { + return ENTITY_NAME; + } + +} diff --git a/BiuBike/app/src/main/java/com/biubike/receiver/TrackReceiver.java b/BiuBike/app/src/main/java/com/biubike/receiver/TrackReceiver.java new file mode 100644 index 0000000..dd1a55b --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/receiver/TrackReceiver.java @@ -0,0 +1,42 @@ +package com.biubike.receiver; + +import android.annotation.SuppressLint; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.PowerManager.WakeLock; + +import com.baidu.trace.model.StatusCodes; + +public class TrackReceiver extends BroadcastReceiver { + + private WakeLock wakeLock = null; + + public TrackReceiver(WakeLock wakeLock) { + super(); + this.wakeLock = wakeLock; + } + + @SuppressLint("Wakelock") + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + + if (Intent.ACTION_SCREEN_OFF.equals(action)) { + if (null != wakeLock && !(wakeLock.isHeld())) { + wakeLock.acquire(); + } + } else if (Intent.ACTION_SCREEN_ON.equals(action) || Intent.ACTION_USER_PRESENT.equals(action)) { + if (null != wakeLock && wakeLock.isHeld()) { + wakeLock.release(); + } + } else if (StatusCodes.GPS_STATUS_ACTION.equals(action)) { + int statusCode = intent.getIntExtra("statusCode", 0); + String statusMessage = intent.getStringExtra("statusMessage"); + System.out.println(String.format("GPS status, statusCode:%d, statusMessage:%s", statusCode, + statusMessage)); + + } + } + +} diff --git a/BiuBike/app/src/main/java/com/biubike/service/JobSchedulerService.java b/BiuBike/app/src/main/java/com/biubike/service/JobSchedulerService.java deleted file mode 100644 index 5cd1b9b..0000000 --- a/BiuBike/app/src/main/java/com/biubike/service/JobSchedulerService.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.biubike.service; - -import android.annotation.TargetApi; -import android.app.job.JobParameters; -import android.app.job.JobService; -import android.os.Build; -import android.os.Handler; -import android.os.Message; -import android.widget.Toast; - -/** - * Created by gaolei on 2017/12/8. - */ -@TargetApi(Build.VERSION_CODES.LOLLIPOP) -public class JobSchedulerService extends JobService { - - private Handler mJobHandler = new Handler( new Handler.Callback() { - @Override - public boolean handleMessage( Message msg ) { - Toast.makeText( getApplicationContext(), "JobService task running", Toast.LENGTH_SHORT ).show(); - jobFinished( (JobParameters) msg.obj, false ); - return true; - } - } ); - - @Override - public boolean onStartJob(JobParameters params ) { - mJobHandler.sendMessage( Message.obtain( mJobHandler, 1, params ) ); - return true; - } - - @Override - public boolean onStopJob( JobParameters params ) { - mJobHandler.removeMessages( 1 ); - return false; - } - -} - diff --git a/BiuBike/app/src/main/java/com/biubike/service/RouteService.java b/BiuBike/app/src/main/java/com/biubike/service/RouteService.java deleted file mode 100644 index 059fddf..0000000 --- a/BiuBike/app/src/main/java/com/biubike/service/RouteService.java +++ /dev/null @@ -1,311 +0,0 @@ -package com.biubike.service; - -/** - * Created by gaolei on 17/2/4. - */ - -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.app.Service; -import android.content.BroadcastReceiver; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.database.sqlite.SQLiteDatabase; -import android.net.ConnectivityManager; -import android.os.Build; -import android.os.Bundle; -import android.os.IBinder; -import android.support.annotation.RequiresApi; -import android.support.v4.app.NotificationCompat; -import android.util.Log; -import android.widget.RemoteViews; - -import com.baidu.location.BDLocation; -import com.baidu.location.BDLocationListener; -import com.baidu.location.LocationClient; -import com.baidu.location.LocationClientOption; -import com.baidu.mapapi.map.MyLocationConfiguration; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.utils.DistanceUtil; -import com.biubike.MainActivity; -import com.biubike.R; -import com.biubike.activity.RouteDetailActivity; -import com.biubike.bean.RoutePoint; -import com.biubike.bean.RoutePoints; -import com.biubike.database.RouteDBHelper; -import com.biubike.util.Utils; -import com.google.gson.Gson; - -import org.greenrobot.eventbus.EventBus; - -import java.text.DecimalFormat; -import java.util.ArrayList; - -import static android.net.NetworkInfo.State; - - -// 记录轨迹思路: -// 用Service获取经纬度,onCreate中开始采集经纬度点,保存到到List -// 每隔2秒取样一次,若经纬度未发生变化,丢弃该次取样 -// 在onDestroy中,将List转成JSON格式,然后存储到sqlite -// -// 显示轨迹思路: -// 读取sqlite下所有轨迹文件,显示到recyclerview -// 在OnItemClick中将文件名称通过intent.putExtra传递给显示轨迹的Activity -// 根据文件名将对应的JSON内容转成ArrayList -// 然后将以上ArrayList的点集依次连线,并绘制到百度地图上 -// 设置起始点Marker,Zoom级别,中心点为起始点 -// 轨迹点小于2个无法绘制轨迹 - - -public class RouteService extends Service { - - private LocationClient mlocationClient = null; - private MylocationListener mlistener; - protected String rt_price; - public ArrayList routPointList = new ArrayList<>(); - public int totalDistance = 0; - public int totalPrice = 0; - public long beginTime = 0, totalTime = 0; - private String showDistance, showTime, showPrice; - private Notification notification; - private RemoteViews contentView; - - public void onCreate() { - super.onCreate(); - beginTime = System.currentTimeMillis(); - - totalTime = 0; - totalDistance = 0; - totalPrice = 0; - routPointList.clear(); - initLocation();//初始化LocationgClient - initNotification(); - Utils.acquireWakeLock(this); - } - - public int onStartCommand(Intent intent, int flags, int startId) { - return super.onStartCommand(intent, flags, startId); - } - - private void initNotification() { - int icon = R.mipmap.bike_icon2; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - createNotificationChannel("id_route", "route"); - } - contentView = new RemoteViews(getPackageName(), R.layout.notification_layout); - notification = new NotificationCompat.Builder(this, "id_route").setContent(contentView).setSmallIcon(icon).build(); - Intent notificationIntent = new Intent(this, MainActivity.class); - notificationIntent.putExtra("flag", "notification"); - notification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); - } - - @RequiresApi(Build.VERSION_CODES.O) - private void createNotificationChannel(String channelId, String channelName) { - NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - - if (notificationManager.getNotificationChannel(channelId) != null) return; - - NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW); - notificationChannel.enableVibration(false); - notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); - notificationChannel.setShowBadge(true); - notificationChannel.setBypassDnd(true); - - notificationManager.createNotificationChannel(notificationChannel); - } - - private void initLocation() { - - - //定位服务的客户端。宿主程序在客户端声明此类,并调用,目前只支持在主线程中启动 - mlocationClient = new LocationClient(this); - mlistener = new MylocationListener(); -// initMarkerClickEvent(); - //注册监听器 - mlocationClient.registerLocationListener(mlistener); - //配置定位SDK各配置参数,比如定位模式、定位时间间隔、坐标系类型等 - LocationClientOption mOption = new LocationClientOption(); - //设置坐标类型 - mOption.setCoorType("bd09ll"); - //设置是否需要地址信息,默认为无地址 - mOption.setIsNeedAddress(true); - //设置是否打开gps进行定位 - mOption.setOpenGps(true); - //设置扫描间隔,单位是毫秒 当<1000(1s)时,定时定位无效 - mOption.setScanSpan(2000); - //设置 LocationClientOptionƒ20 - mlocationClient.setLocOption(mOption); - - if (!mlocationClient.isStarted()) { - mlocationClient.start(); - } - } - - - public IBinder onBind(Intent intent) { - return null; - } - - public boolean onUnBind(Intent intent) { - return false; - } - - @Override - public void onDestroy() { - super.onDestroy(); - mlocationClient.stop(); - Gson gson = new Gson(); - String routeListStr = gson.toJson(routPointList); - Bundle bundle = new Bundle(); - bundle.putString("totalTime", showTime); - bundle.putString("totalDistance", showDistance); - bundle.putString("totalPrice", showPrice); - bundle.putString("routePoints", routeListStr); - Intent intent = new Intent(this, RouteDetailActivity.class); - intent.putExtras(bundle); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - if (routPointList.size() > 2) - insertData(routeListStr); - Utils.releaseWakeLock(); - stopForeground(true); - showTime = ""; - showDistance = ""; - showPrice = ""; - } - - - //所有的定位信息都通过接口回调来实现 - public class MylocationListener implements BDLocationListener { - - //定位请求回调函数,这里面会得到定位信息 - @Override - public void onReceiveLocation(BDLocation bdLocation) { - if (null == bdLocation) return; - - //"4.9E-324"表示目前所处的环境(室内或者是网络状况不佳)造成无法获取到经纬度 - if ("4.9E-324".equals(String.valueOf(bdLocation.getLatitude())) || "4.9E-324".equals(String.valueOf(bdLocation.getLongitude()))) { - return; - }//过滤百度定位失败 - - double routeLat = bdLocation.getLatitude(); - double routeLng = bdLocation.getLongitude(); - RoutePoint routePoint = new RoutePoint(); - routePoint.setRouteLat(routeLat); - routePoint.setRouteLng(routeLng); - if (routPointList.size() == 0) - routPointList.add(routePoint); - else { - RoutePoint lastPoint = routPointList.get(routPointList.size() - 1); - - if (routeLat == lastPoint.getRouteLat() && routeLng == lastPoint.getRouteLng()) { - - } else { - - LatLng lastLatLng = new LatLng(lastPoint.getRouteLat(), - lastPoint.getRouteLng()); - LatLng currentLatLng = new LatLng(routeLat, routeLng); - if (routeLat > 0 && routeLng > 0) { - double distantce = DistanceUtil.getDistance(lastLatLng, currentLatLng); -// 大于2米算作有效加入列表 - if (distantce > 2) { - //distance单位是米 转化为km/h - routePoint.speed = Double.parseDouble(String.format("%.1f", (distantce / 1000) * 30 * 60)); - routePoint.time = System.currentTimeMillis(); - routPointList.add(routePoint); - totalDistance += distantce; - } - } - } - } - - totalTime = (int) (System.currentTimeMillis() - beginTime) / 1000 / 60; - totalPrice = (int) (Math.floor(totalTime / 60) * 1 + 1); - - - if (totalDistance > 1000) { - DecimalFormat df = new DecimalFormat("#.00"); - showDistance = df.format((float) totalDistance / 1000) + "千米"; - } else showDistance = totalDistance + "米"; - if (totalTime > 60) { - showTime = totalTime / 60 + "时" + totalTime % 60 + "分"; - } else showTime = totalTime + "分钟"; - showPrice = totalPrice + "元"; - - showRouteInfo(showTime, showDistance, showPrice, routPointList); - - - } - } - - private void showRouteInfo(String time, String distance, String price, ArrayList routPointList) { - Log.d("gaolei", "totalTime---------post-----" + showTime); - Log.d("gaolei", "totalDistance-----post---------" + showDistance); - Log.d("gaolei", "totalPrice-------post-------" + showPrice); - Log.d("gaolei", "routPointList.size()-------post-------" + routPointList.size()); - EventBus.getDefault().post(new RoutePoints(routPointList, time, distance, price)); - startNotifi(time, distance, price); - } - - private void startNotifi(String time, String distance, String price) { - startForeground(1, notification); - contentView.setTextViewText(R.id.bike_time, time); - contentView.setTextViewText(R.id.bike_distance, distance); - contentView.setTextViewText(R.id.bike_price, price); - rt_price = price; - } - - public static class NetWorkReceiver extends BroadcastReceiver { - public NetWorkReceiver() { - } - - @Override - public void onReceive(Context context, Intent intent) { - State wifiState; - State mobileState = null; - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); - mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState(); - if (wifiState != null && mobileState != null - && State.CONNECTED != wifiState - && State.CONNECTED == mobileState) { -// Toast.makeText(context, context.getString(R.string.net_mobile), Toast.LENGTH_SHORT).show(); - // 手机网络连接成功 - } else if (wifiState != null && mobileState != null - && State.CONNECTED != wifiState - && State.CONNECTED != mobileState) { -// Toast.makeText(context, context.getString(R.string.net_none), Toast.LENGTH_SHORT).show(); - - // 手机没有任何的网络 - } else if (wifiState != null && State.CONNECTED == wifiState) { - // 无线网络连接成功 -// Toast.makeText(context, context.getString(R.string.net_wifi), Toast.LENGTH_SHORT).show(); - - } - } - } - - public void insertData(String routeListStr) { - ContentValues values = new ContentValues(); - // 向该对象中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须和数据当中的数据类型一致 - values.put("cycle_date", Utils.getDateFromMillisecond(beginTime)); - values.put("cycle_time", showTime); - values.put("cycle_distance", showDistance); - values.put("cycle_price", showPrice); - values.put("cycle_points", routeListStr); - // 创建DatabaseHelper对象 - RouteDBHelper dbHelper = new RouteDBHelper(this); - // 得到一个可写的SQLiteDatabase对象 - SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase(); - // 调用insert方法,就可以将数据插入到数据库当中 - // 第一个参数:表名称 - // 第二个参数:SQl不允许一个空列,如果ContentValues是空的,那么这一列被明确的指明为NULL值 - // 第三个参数:ContentValues对象 - sqliteDatabase.insert("cycle_route", null, values); - sqliteDatabase.close(); - } -} diff --git a/BiuBike/app/src/main/java/com/biubike/util/ContextUtil.java b/BiuBike/app/src/main/java/com/biubike/util/ContextUtil.java new file mode 100644 index 0000000..f1593f6 --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/util/ContextUtil.java @@ -0,0 +1,23 @@ +package com.biubike.util; + +import android.app.Application; +import android.content.Context; + +public class ContextUtil { + private static Application mApplication; + + public static Context getAppContext() { + return getApp().getApplicationContext(); + } + + public static synchronized Application getApp() { + if (mApplication == null) { + try { + mApplication = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null); + } catch (Exception e) { + e.printStackTrace(); + } + } + return mApplication; + } +} \ No newline at end of file diff --git a/BiuBike/app/src/main/java/com/biubike/util/NavUtil.java b/BiuBike/app/src/main/java/com/biubike/util/NavUtil.java deleted file mode 100644 index d9db2af..0000000 --- a/BiuBike/app/src/main/java/com/biubike/util/NavUtil.java +++ /dev/null @@ -1,354 +0,0 @@ -package com.biubike.util; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.util.Log; -import android.widget.Toast; - -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException; -import com.baidu.mapapi.navi.BaiduMapNavigation; -import com.baidu.mapapi.navi.NaviParaOption; -import com.baidu.mapapi.utils.DistanceUtil; -import com.baidu.mapapi.utils.OpenClientUtil; -import com.baidu.mapapi.utils.route.BaiduMapRoutePlan; -import com.baidu.mapapi.utils.route.RouteParaOption; -import com.baidu.navisdk.adapter.BNRoutePlanNode; -import com.baidu.navisdk.adapter.BNaviSettingManager; -import com.baidu.navisdk.adapter.BaiduNaviManager; -import com.biubike.R; -import com.biubike.activity.BDInnerNaviActivity; -import com.biubike.custom.NaviSelectDialog; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import static com.biubike.application.DemoApplication.APP_FOLDER_NAME; -import static com.biubike.application.DemoApplication.mSDCardPath; - -/** - * Created by GaoLei on 17/3/31. - * 这个工具类实现了调用内置导航和打开第三方App导航 - * 1.assets中的文件必须拷贝到项目 - * 2.想使用内置导航,必须初始化导航, NavUtil.initNavi(this); - */ -public class NavUtil { - public static final int BaiduNavi = 1, GaodeNavi = 2, InnerNavi = 0; - public static List activityList = new LinkedList(); - public static final String ROUTE_PLAN_NODE = "routePlanNode"; - static String authinfo = null; - /** - * 弹出导航选择dialog - */ - public static void showChoiceNaviWayDialog(final Activity activity, final LatLng startLL, final LatLng endLL, final String start_place, final String destination) { - - - final NaviSelectDialog rcd = new NaviSelectDialog(activity); - rcd.setCanceledOnTouchOutside(false); - rcd.setCancelable(false); - final ArrayList mapApps = new ArrayList(); - mapApps.add(activity.getString(R.string.inner_navi)); - if (Utils.hasApp(activity, Utils.APP_BAIDU_MAP)) { - mapApps.add(activity.getString(R.string.baidu_navi)); - } - if (Utils.hasApp(activity, Utils.APP_AMAP)) { - mapApps.add(activity.getString(R.string.gaode_navi)); - } - rcd.setItems(mapApps, new NaviSelectDialog.OnDlgItemClickListener() { - @Override - public void onEnsureClicked(Dialog dialog, String value, boolean isChecked) { - dialog.dismiss(); - if (activity.getString(R.string.inner_navi).equals(value)) { - launchNavigatorViaPoints(activity, startLL, endLL); - // startInnerNavi(activity, startLL, endLL); - } - if (activity.getString(R.string.baidu_navi).equals(value)) { -// startNative_Baidu(activity, startLL, endLL, start_place, destination); - startBikingNavi(activity, startLL, endLL); - } else if (activity.getString(R.string.gaode_navi).equals(value)) { - startGaodeNavi(activity, startLL, endLL, start_place); - } - if (isChecked) { - //记住我的选择 - } - } - - public void onCancleClicked(Dialog dialog) { - dialog.dismiss(); - } - }, true).show(); - } - - private static void launchNavigatorViaPoints(final Activity activity, LatLng startLL, LatLng endLL) { - //这里给出一个起终点示例,实际应用中可以通过POI检索、外部POI来源等方式获取起终点坐标 - - final BNRoutePlanNode sNode = new BNRoutePlanNode(startLL.longitude, startLL.latitude, null, "从这里开始", BNRoutePlanNode.CoordinateType.BD09LL); - final BNRoutePlanNode eNode = new BNRoutePlanNode(endLL.longitude, endLL.latitude, null, "到这里结束", BNRoutePlanNode.CoordinateType.BD09LL); - if (sNode != null && eNode != null) { - List points = new ArrayList(); - points.add(sNode); - points.add(eNode); - //距离太近toast提示(100米内) - double dis = DistanceUtil.getDistance(new LatLng(sNode.getLatitude(), sNode.getLongitude()), new LatLng(eNode.getLatitude(), eNode.getLongitude())); - if (dis <= 100) { - Toast.makeText(activity, "起点、途经点、终点距离太近", Toast.LENGTH_SHORT).show(); - return; - } - BaiduNaviManager.getInstance().launchNavigator(activity, points, 1, true, new BaiduNaviManager.RoutePlanListener() { - public void onJumpToNavigator() { - /* - * 设置途径点以及resetEndNode会回调该接口 - */ - for (Activity ac : activityList) { - if (ac.getClass().getName().endsWith("BNDemoGuideActivity")) { - return; - } - } - Intent intent = new Intent(activity, BDInnerNaviActivity.class); - Bundle bundle = new Bundle(); - bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) sNode); - intent.putExtras(bundle); - activity.startActivity(intent); - } - - public void onRoutePlanFailed() { - // TODO Auto-generated method stub - Toast.makeText(activity, "算路失败", Toast.LENGTH_SHORT).show(); - } - }); - } - } - - /** - * 启动百度地图骑行导航(Native) - */ - private static void startBikingNavi(Activity activity, LatLng startLL, LatLng endLL) { - //距离太近toast提示(100米内) - double dis = DistanceUtil.getDistance(new LatLng(startLL.latitude, startLL.longitude), new LatLng(endLL.latitude, endLL.longitude)); - if (dis <= 100) { - Toast.makeText(activity, "起点、途经点、终点距离太近", Toast.LENGTH_SHORT).show(); - return; - } - // 构建 导航参数 - NaviParaOption para = new NaviParaOption() - .startPoint(startLL).endPoint(endLL); - try { - BaiduMapNavigation.openBaiduMapBikeNavi(para, activity); - } catch (BaiduMapAppNotSupportNaviException e) { - e.printStackTrace(); - } - } - - /** - * 启动百度地图导航(Native) - */ - public void startNavi(Activity activity, LatLng pt1, LatLng pt2) { - // 构建 导航参数 - NaviParaOption para = new NaviParaOption() - .startPoint(pt1).endPoint(pt2) - .startName("天安门").endName("百度大厦"); - try { - BaiduMapNavigation.openBaiduMapNavi(para, activity); - } catch (BaiduMapAppNotSupportNaviException e) { - e.printStackTrace(); - showDialog(activity); - } - - } - - /** - * 启动百度地图驾车路线规划 - */ - public void startRoutePlanDriving(Activity activity, LatLng pt1, LatLng pt2) { - // 构建 route搜索参数 - RouteParaOption para = new RouteParaOption() - .startPoint(pt1) - .endPoint(pt2); - - try { - BaiduMapRoutePlan.openBaiduMapDrivingRoute(para, activity); - } catch (Exception e) { - e.printStackTrace(); - showDialog(activity); - } - - } - /** - * 通过Uri跳转到百度地图导航 - */ - public static void startNative_Baidu(Activity activity, LatLng pt1, LatLng pt2, String start_address, String end_address) { - try { - double dis = DistanceUtil.getDistance(new LatLng(pt1.latitude,pt1.longitude), new LatLng(pt2.latitude,pt2.longitude)); - if (dis <= 100) { - Toast.makeText(activity, "起点、途经点、终点距离太近", Toast.LENGTH_SHORT).show(); - return; - } - String start_latlng = pt1.latitude + "," + pt1.longitude; - String end_latlng = pt2.latitude + "," + pt2.longitude; - Intent intent = Intent.getIntent("intent://map/direction?origin=latlng:"+start_latlng+"|name:"+"Start"+"&destination=latlng:"+end_latlng+"|name:"+"End"+"&mode=riding&src=这里随便写#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"); - activity.startActivity(intent); - } catch (Exception e) { - e.printStackTrace(); - Toast.makeText(activity, "地址解析错误", Toast.LENGTH_SHORT).show(); - } - } - - /** - * 启动高德地图驾车路线规划 - */ - public static void startGaodeNavi(Activity activity, LatLng pt1, LatLng pt2, String start_place) { - try { - Intent intent = new Intent(); - double sLat = pt1.latitude, sLon = pt1.longitude, eLat = pt2.latitude, eLon = pt2.longitude; - String poiAddress = LocationManager.getInstance().getAddress(); - intent.setData(android.net.Uri - .parse("androidamap://navi?sourceApplication=yongche&poiname=" + start_place + "&lat=" - + eLat - + "&lon=" - + eLon + "&dev=0&style=2")); - intent.addCategory("android.intent.category.DEFAULT"); - intent.setPackage("com.autonavi.minimap"); - activity.startActivity(intent); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 路线规划监听器,规划成功后跳转至导航过程页面 - */ - private static class YCRoutePlanListener implements BaiduNaviManager.RoutePlanListener { - - private BNRoutePlanNode mBNRoutePlanNode = null; - private Activity activity; - - public YCRoutePlanListener(BNRoutePlanNode node, Activity act) { - mBNRoutePlanNode = node; - activity = act; - } - - @Override - public void onJumpToNavigator() { - Intent intent = new Intent(activity, BDInnerNaviActivity.class); - activity.startActivity(intent); - activity.startActivity(intent); - } - - @Override - public void onRoutePlanFailed() { - - } - } - - /** - * 提示未安装百度地图app或app版本过低 - */ - public void showDialog(final Activity activity) { - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setMessage("您尚未安装百度地图app或app版本过低,点击确认安装?"); - builder.setTitle("提示"); - builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - OpenClientUtil.getLatestBaiduMapApp(activity); - } - }); - - builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - - builder.create().show(); - - } - - public static void initNavi(final Activity activity) { - - BaiduNaviManager.getInstance().init(activity, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() { - public void onAuthResult(int status, String msg) { - if (0 == status) { -// authinfo = "key校验成功!"; - } else { -// authinfo = "key校验失败, " + msg; - } - activity.runOnUiThread(new Runnable() { - @Override - public void run() { -// Toast.makeText(activity, authinfo, Toast.LENGTH_LONG).show(); - } - }); - } - - public void initSuccess() { -// Toast.makeText(activity, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show(); - initSetting(); - } - - public void initStart() { -// Toast.makeText(activity, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show(); - } - - public void initFailed() { -// Toast.makeText(activity, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show(); - } - }, null, ttsHandler, ttsPlayStateListener); - - } - - private static void initSetting() { - // 设置是否双屏显示 - BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON); - // 设置导航播报模式 - BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran); - // 是否开启路况 - BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON); - } - - /** - * 内部TTS播报状态回传handler - */ - private static Handler ttsHandler = new Handler() { - public void handleMessage(Message msg) { - int type = msg.what; - switch (type) { - case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: { -// showToastMsg("Handler : TTS play start"); - break; - } - case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: { -// showToastMsg("Handler : TTS play end"); - break; - } - default: - break; - } - } - }; - /** - * 内部TTS播报状态回调接口 - */ - private static BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() { - - @Override - public void playEnd() { -// showToastMsg("TTSPlayStateListener : TTS play end"); - } - - @Override - public void playStart() { -// showToastMsg("TTSPlayStateListener : TTS play start"); - } - }; - -} diff --git a/BiuBike/app/src/main/java/com/biubike/util/NetUtil.java b/BiuBike/app/src/main/java/com/biubike/util/NetUtil.java new file mode 100644 index 0000000..106e249 --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/util/NetUtil.java @@ -0,0 +1,38 @@ +package com.biubike.util; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.Network; +import android.net.NetworkCapabilities; +import android.net.NetworkInfo; +import android.os.Build; +import android.util.Log; + +/** + * Created by baidu on 17/3/21. + */ + +public class NetUtil { + + /** + * 检测网络状态是否联通 + * + * @return + */ + public static boolean isNetworkAvailable(Context context) { + if (context != null) { + ConnectivityManager mConnectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); + if (mNetworkInfo != null) { + + //这种方法也可以 + //return mNetworkInfo .getState()== NetworkInfo.State.CONNECTED + + return mNetworkInfo.isAvailable(); + + } + } + return false; + } +} diff --git a/BiuBike/app/src/main/java/com/biubike/util/SpeechUtil.java b/BiuBike/app/src/main/java/com/biubike/util/SpeechUtil.java deleted file mode 100644 index 9d6e838..0000000 --- a/BiuBike/app/src/main/java/com/biubike/util/SpeechUtil.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.biubike.util; - -import android.content.Context; -import android.os.Bundle; -import android.os.Environment; -import android.util.Log; - -import com.iflytek.cloud.ErrorCode; -import com.iflytek.cloud.InitListener; -import com.iflytek.cloud.SpeechConstant; -import com.iflytek.cloud.SpeechError; -import com.iflytek.cloud.SpeechSynthesizer; -import com.iflytek.cloud.SynthesizerListener; - -/** - * Created by gaolei on 17/4/24. - */ - -public class SpeechUtil { - Context context; - SpeechSynthesizer mTts; - - public SpeechUtil(Context context) { - this.context = context; - //1.创建SpeechSynthesizer对象, 第二个参数:本地合成时传InitListener - mTts = SpeechSynthesizer.createSynthesizer(context, null); - setParams(); - } - - - public void setParams() { - // 清空参数 - mTts.setParameter(SpeechConstant.PARAMS, null); - // 根据合成引擎设置相应参数 - mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); - // 设置在线合成发音人 - mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoqi"); - //设置合成语速 - mTts.setParameter(SpeechConstant.SPEED, "50"); - //设置合成音调 - mTts.setParameter(SpeechConstant.PITCH, "50"); - //设置合成音量 - mTts.setParameter(SpeechConstant.VOLUME, "50"); - - //设置播放器音频流类型 - mTts.setParameter(SpeechConstant.STREAM_TYPE, "3"); - // 设置播放合成音频打断音乐播放,默认为true - mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); - - // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 - // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 - mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); - mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav"); - } - - public void startSpeech(String text) { - int code = mTts.startSpeaking(text, mTtsListener); - - } - - /** - * 初始化监听。 - */ - private InitListener mTtsInitListener = new InitListener() { - @Override - public void onInit(int code) { - if (code != ErrorCode.SUCCESS) { - } else { - // 初始化成功,之后可以调用startSpeaking方法 - // 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成, - // 正确的做法是将onCreate中的startSpeaking调用移至这里 - - } - } - }; - - /** - * 合成回调监听。 - */ - private SynthesizerListener mTtsListener = new SynthesizerListener() { - - @Override - public void onSpeakBegin() { - - } - - @Override - public void onSpeakPaused() { - - } - - @Override - public void onSpeakResumed() { - - } - - @Override - public void onBufferProgress(int percent, int beginPos, int endPos, - String info) { - // 合成进度 - } - - @Override - public void onSpeakProgress(int percent, int beginPos, int endPos) { - // 播放进度 - } - - @Override - public void onCompleted(SpeechError error) { - - } - - @Override - public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { - // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 - // 若使用本地能力,会话id为null - // if (SpeechEvent.EVENT_SESSION_ID == eventType) { - // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); - // } - } - }; -} - - diff --git a/BiuBike/app/src/main/java/com/biubike/util/ViewUtil.java b/BiuBike/app/src/main/java/com/biubike/util/ViewUtil.java new file mode 100644 index 0000000..98011bf --- /dev/null +++ b/BiuBike/app/src/main/java/com/biubike/util/ViewUtil.java @@ -0,0 +1,140 @@ +package com.biubike.util; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Build; +import android.text.Html; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.NumberPicker; +import android.widget.TextView; +import android.widget.Toast; + +import com.biubike.R; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by baidu on 16/7/21. + */ +public class ViewUtil { + + private Toast mToast = null; + + private TextView mTextView = null; + + public static void showToast(Activity activity, String message) { + Toast mToast=Toast.makeText(activity,message,Toast.LENGTH_LONG); + mToast.setGravity(Gravity.BOTTOM, 0, activity.getResources().getDisplayMetrics().heightPixels / 5); + mToast.show(); + } + + public static void setMargins(View view, int left, int top, int right, int bottom) { + if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { + ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); + p.setMargins(left, top, right, bottom); + view.requestLayout(); + } + } + + + /** + * 设置屏幕的背景透明度 + * + * @param bgAlpha + */ + public static void setBackgroundAlpha(Activity context, float bgAlpha) { + WindowManager.LayoutParams lp = context.getWindow().getAttributes(); + lp.alpha = bgAlpha; + context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); + context.getWindow().setAttributes(lp); + } + + @TargetApi(19) + private static void setTranslucentStatus(Activity activity, boolean on) { + Window win = activity.getWindow(); + WindowManager.LayoutParams winParams = win.getAttributes(); + + final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; + if (on) { + winParams.flags |= bits; + } else { + winParams.flags &= ~bits; + } + win.setAttributes(winParams); + } + + /** + * 根据手机的分辨率从 px(像素) 的单位 转成为 dp + */ + public static int px2dip(Context context, float pxValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (pxValue / scale + 0.5f); + } + + /** + * 根据手机的分辨率从 dp 的单位 转成为 px(像素) + */ + public static int dip2px(Context context, float dpValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (dpValue * scale + 0.5f); + } + + /** + * 调整Picker布局 + * + * @param frameLayout + */ + public static void resizePicker(FrameLayout frameLayout) { + List numberPickers = findNumberPicker(frameLayout); + for (NumberPicker numberPicker : numberPickers) { + resizeNumberPicker(numberPicker); + } + } + + /** + * 获取ViewGroup中的NumberPicker组件 + * + * @param viewGroup + * + * @return + */ + private static List findNumberPicker(ViewGroup viewGroup) { + List numberPickers = new ArrayList<>(); + View child; + if (null != viewGroup) { + for (int i = 0; i < viewGroup.getChildCount(); i++) { + child = viewGroup.getChildAt(i); + if (child instanceof NumberPicker) { + numberPickers.add((NumberPicker) child); + } else if (child instanceof LinearLayout) { + List result = findNumberPicker((ViewGroup) child); + if (result.size() > 0) { + return result; + } + } + } + } + return numberPickers; + } + + /** + * 调整NumberPicker大小 + * + * @param numberPicker + */ + private static void resizeNumberPicker(NumberPicker numberPicker) { + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(150, ViewGroup.LayoutParams.WRAP_CONTENT); + params.setMargins(15, 0, 15, 0); + numberPicker.setLayoutParams(params); + } + +} diff --git a/BiuBike/app/src/main/java/overlayutil/BikingRouteOverlay.java b/BiuBike/app/src/main/java/overlayutil/BikingRouteOverlay.java deleted file mode 100644 index 0a731e2..0000000 --- a/BiuBike/app/src/main/java/overlayutil/BikingRouteOverlay.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. - */ -package overlayutil; - -import android.graphics.Color; -import android.os.Bundle; -import android.util.Log; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.Overlay; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.map.PolylineOptions; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.search.route.BikingRouteLine; - -import java.util.ArrayList; -import java.util.List; - -/** - * 用于显示骑行路线的Overlay - */ -public class BikingRouteOverlay extends OverlayManager { - - private BikingRouteLine mRouteLine = null; - - public BikingRouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - /** - * 设置路线数据。 - * - * @param line - * 路线数据 - */ - public void setData(BikingRouteLine line) { - mRouteLine = line; - } - - @Override - public final List getOverlayOptions() { - if (mRouteLine == null) { - return null; - } - - List overlayList = new ArrayList(); - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - for (BikingRouteLine.BikingStep step : mRouteLine.getAllStep()) { - Bundle b = new Bundle(); - b.putInt("index", mRouteLine.getAllStep().indexOf(step)); - if (step.getEntrance() != null) { - overlayList.add((new MarkerOptions()) - .position(step.getEntrance().getLocation()) - .rotate((360 - step.getDirection())) - .zIndex(10) - .anchor(0.5f, 0.5f) - .extraInfo(b) - .icon(BitmapDescriptorFactory - .fromAssetWithDpi("Icon_line_node.png"))); - } - - // 最后路段绘制出口点 - if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine - .getAllStep().size() - 1) && step.getExit() != null) { - overlayList.add((new MarkerOptions()) - .position(step.getExit().getLocation()) - .anchor(0.5f, 0.5f) - .zIndex(10) - .icon(BitmapDescriptorFactory - .fromAssetWithDpi("Icon_line_node.png"))); - - } - } - } - // starting - if (mRouteLine.getStarting() != null) { - overlayList.add((new MarkerOptions()) - .position(mRouteLine.getStarting().getLocation()) - .icon(getStartMarker() != null ? getStartMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_start.png")).zIndex(10)); - } - // terminal - if (mRouteLine.getTerminal() != null) { - overlayList - .add((new MarkerOptions()) - .position(mRouteLine.getTerminal().getLocation()) - .icon(getTerminalMarker() != null ? getTerminalMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_end.png")) - .zIndex(10)); - } - - // poly line list - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - LatLng lastStepLastPoint = null; - for (BikingRouteLine.BikingStep step : mRouteLine.getAllStep()) { - List watPoints = step.getWayPoints(); - if (watPoints != null) { - List points = new ArrayList(); - if (lastStepLastPoint != null) { - points.add(lastStepLastPoint); - } - points.addAll(watPoints); - overlayList.add(new PolylineOptions().points(points).width(10) - .color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0)); - lastStepLastPoint = watPoints.get(watPoints.size() - 1); - } - } - - } - - return overlayList; - } - - /** - * 覆写此方法以改变默认起点图标 - * - * @return 起点图标 - */ - public BitmapDescriptor getStartMarker() { - return null; - } - public int getLineColor() { - return 0; - } - /** - * 覆写此方法以改变默认终点图标 - * - * @return 终点图标 - */ - public BitmapDescriptor getTerminalMarker() { - return null; - } - - /** - * 处理点击事件 - * - * @param i - * 被点击的step在 - * {@link com.baidu.mapapi.search.route.BikingRouteLine#getAllStep()} - * 中的索引 - * @return 是否处理了该点击事件 - */ - public boolean onRouteNodeClick(int i) { - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().get(i) != null) { - Log.i("baidumapsdk", "BikingRouteOverlay onRouteNodeClick"); - } - return false; - } - - @Override - public final boolean onMarkerClick(Marker marker) { - for (Overlay mMarker : mOverlayList) { - if (mMarker instanceof Marker && mMarker.equals(marker)) { - if (marker.getExtraInfo() != null) { - onRouteNodeClick(marker.getExtraInfo().getInt("index")); - } - } - } - return true; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - // TODO Auto-generated method stub - return false; - } -} \ No newline at end of file diff --git a/BiuBike/app/src/main/java/overlayutil/BusLineOverlay.java b/BiuBike/app/src/main/java/overlayutil/BusLineOverlay.java deleted file mode 100644 index cc57864..0000000 --- a/BiuBike/app/src/main/java/overlayutil/BusLineOverlay.java +++ /dev/null @@ -1,108 +0,0 @@ -package overlayutil; - -import android.graphics.Color; -import android.util.Log; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.map.PolylineOptions; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.search.busline.BusLineResult; - -import java.util.ArrayList; -import java.util.List; - -/** - * 用于显示一条公交详情结果的Overlay - */ -public class BusLineOverlay extends OverlayManager { - - private BusLineResult mBusLineResult = null; - - /** - * 构造函数 - * - * @param baiduMap - * 该BusLineOverlay所引用的 BaiduMap 对象 - */ - public BusLineOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - /** - * 设置公交线数据 - * - * @param result - * 公交线路结果数据 - */ - public void setData(BusLineResult result) { - this.mBusLineResult = result; - } - - @Override - public final List getOverlayOptions() { - - if (mBusLineResult == null || mBusLineResult.getStations() == null) { - return null; - } - List overlayOptionses = new ArrayList(); - for (BusLineResult.BusStation station : mBusLineResult.getStations()) { - overlayOptionses.add(new MarkerOptions() - .position(station.getLocation()) - .zIndex(10) - .anchor(0.5f, 0.5f) - .icon(BitmapDescriptorFactory - .fromAssetWithDpi("Icon_bus_station.png"))); - } - - List points = new ArrayList(); - for (BusLineResult.BusStep step : mBusLineResult.getSteps()) { - if (step.getWayPoints() != null) { - points.addAll(step.getWayPoints()); - } - } - if (points.size() > 0) { - overlayOptionses - .add(new PolylineOptions().width(10) - .color(Color.argb(178, 0, 78, 255)).zIndex(0) - .points(points)); - } - return overlayOptionses; - } - - /** - * 覆写此方法以改变默认点击行为 - * - * @param index - * 被点击的站点在 - * {@link com.baidu.mapapi.search.busline.BusLineResult#getStations()} - * 中的索引 - * @return 是否处理了该点击事件 - */ - public boolean onBusStationClick(int index) { - if (mBusLineResult.getStations() != null - && mBusLineResult.getStations().get(index) != null) { - Log.i("baidumapsdk", "BusLineOverlay onBusStationClick"); - } - return false; - } - - public final boolean onMarkerClick(Marker marker) { - if (mOverlayList != null && mOverlayList.contains(marker)) { - return onBusStationClick(mOverlayList.indexOf(marker)); - } else { - return false; - } - - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - // TODO Auto-generated method stub - return false; - } -} diff --git a/BiuBike/app/src/main/java/overlayutil/DrivingRouteOverlay.java b/BiuBike/app/src/main/java/overlayutil/DrivingRouteOverlay.java deleted file mode 100644 index bad5a6b..0000000 --- a/BiuBike/app/src/main/java/overlayutil/DrivingRouteOverlay.java +++ /dev/null @@ -1,244 +0,0 @@ -package overlayutil; - -import android.graphics.Color; -import android.os.Bundle; -import android.util.Log; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.Overlay; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.map.PolylineOptions; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.search.route.DrivingRouteLine; -import com.baidu.mapapi.search.route.DrivingRouteLine.DrivingStep; - -import java.util.ArrayList; -import java.util.List; - -/** - * 用于显示一条驾车路线的overlay,自3.4.0版本起可实例化多个添加在地图中显示,当数据中包含路况数据时,则默认使用路况纹理分段绘制 - */ -public class DrivingRouteOverlay extends OverlayManager { - - private DrivingRouteLine mRouteLine = null; - boolean focus = false; - - /** - * 构造函数 - * - * @param baiduMap - * 该DrivingRouteOvelray引用的 BaiduMap - */ - public DrivingRouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - @Override - public final List getOverlayOptions() { - if (mRouteLine == null) { - return null; - } - - List overlayOptionses = new ArrayList(); - // step node - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - - for (DrivingRouteLine.DrivingStep step : mRouteLine.getAllStep()) { - Bundle b = new Bundle(); - b.putInt("index", mRouteLine.getAllStep().indexOf(step)); - if (step.getEntrance() != null) { - overlayOptionses.add((new MarkerOptions()) - .position(step.getEntrance().getLocation()) - .anchor(0.5f, 0.5f) - .zIndex(10) - .rotate((360 - step.getDirection())) - .extraInfo(b) - .icon(BitmapDescriptorFactory - .fromAssetWithDpi("Icon_line_node.png"))); - } - // 最后路段绘制出口点 - if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine - .getAllStep().size() - 1) && step.getExit() != null) { - overlayOptionses.add((new MarkerOptions()) - .position(step.getExit().getLocation()) - .anchor(0.5f, 0.5f) - .zIndex(10) - .icon(BitmapDescriptorFactory - .fromAssetWithDpi("Icon_line_node.png"))); - - } - } - } - - if (mRouteLine.getStarting() != null) { - overlayOptionses.add((new MarkerOptions()) - .position(mRouteLine.getStarting().getLocation()) - .icon(getStartMarker() != null ? getStartMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_start.png")).zIndex(10)); - } - if (mRouteLine.getTerminal() != null) { - overlayOptionses - .add((new MarkerOptions()) - .position(mRouteLine.getTerminal().getLocation()) - .icon(getTerminalMarker() != null ? getTerminalMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_end.png")) - .zIndex(10)); - } - // poly line - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - - List steps = mRouteLine.getAllStep(); - int stepNum = steps.size(); - - - List points = new ArrayList(); - ArrayList traffics = new ArrayList(); - int totalTraffic = 0; - for (int i = 0; i < stepNum ; i++) { - if (i == stepNum - 1) { - points.addAll(steps.get(i).getWayPoints()); - } else { - points.addAll(steps.get(i).getWayPoints().subList(0, steps.get(i).getWayPoints().size() - 1)); - } - - totalTraffic += steps.get(i).getWayPoints().size() - 1; - if (steps.get(i).getTrafficList() != null && steps.get(i).getTrafficList().length > 0) { - for (int j = 0;j < steps.get(i).getTrafficList().length;j++) { - traffics.add(steps.get(i).getTrafficList()[j]); - } - } - } - -// Bundle indexList = new Bundle(); -// if (traffics.size() > 0) { -// int raffic[] = new int[traffics.size()]; -// int index = 0; -// for (Integer tempTraff : traffics) { -// raffic[index] = tempTraff.intValue(); -// index++; -// } -// indexList.putIntArray("indexs", raffic); -// } - boolean isDotLine = false; - - if (traffics != null && traffics.size() > 0) { - isDotLine = true; - } - PolylineOptions option = new PolylineOptions().points(points).textureIndex(traffics) - .width(7).dottedLine(isDotLine).focus(true) - .color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0); - if (isDotLine) { - option.customTextureList(getCustomTextureList()); - } - overlayOptionses.add(option); - } - return overlayOptionses; - } - - /** - * 设置路线数据 - * - * @param routeLine - * 路线数据 - */ - public void setData(DrivingRouteLine routeLine) { - this.mRouteLine = routeLine; - } - - /** - * 覆写此方法以改变默认起点图标 - * - * @return 起点图标 - */ - public BitmapDescriptor getStartMarker() { - return null; - } - - /** - * 覆写此方法以改变默认绘制颜色 - * @return 线颜色 - */ - public int getLineColor() { - return 0; - } - public List getCustomTextureList() { - ArrayList list = new ArrayList(); - list.add(BitmapDescriptorFactory.fromAsset("Icon_road_blue_arrow.png")); - list.add(BitmapDescriptorFactory.fromAsset("Icon_road_green_arrow.png")); - list.add(BitmapDescriptorFactory.fromAsset("Icon_road_yellow_arrow.png")); - list.add(BitmapDescriptorFactory.fromAsset("Icon_road_red_arrow.png")); - list.add(BitmapDescriptorFactory.fromAsset("Icon_road_nofocus.png")); - return list; - } - /** - * 覆写此方法以改变默认终点图标 - * - * @return 终点图标 - */ - public BitmapDescriptor getTerminalMarker() { - return null; - } - - /** - * 覆写此方法以改变默认点击处理 - * - * @param i - * 线路节点的 index - * @return 是否处理了该点击事件 - */ - public boolean onRouteNodeClick(int i) { - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().get(i) != null) { - Log.i("baidumapsdk", "DrivingRouteOverlay onRouteNodeClick"); - } - return false; - } - - @Override - public final boolean onMarkerClick(Marker marker) { - for (Overlay mMarker : mOverlayList) { - if (mMarker instanceof Marker && mMarker.equals(marker)) { - if (marker.getExtraInfo() != null) { - onRouteNodeClick(marker.getExtraInfo().getInt("index")); - } - } - } - return true; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - boolean flag = false; - for (Overlay mPolyline : mOverlayList) { - if (mPolyline instanceof Polyline && mPolyline.equals(polyline)) { - // 选中 - flag = true; - break; - } - } - setFocus(flag); - return true; - } - - public void setFocus(boolean flag) { - focus = flag; - for (Overlay mPolyline : mOverlayList) { - if (mPolyline instanceof Polyline) { - // 选中 - ((Polyline) mPolyline).setFocus(flag); - - break; - } - } - - } -} diff --git a/BiuBike/app/src/main/java/overlayutil/IndoorPoiOverlay.java b/BiuBike/app/src/main/java/overlayutil/IndoorPoiOverlay.java deleted file mode 100644 index ba5fddf..0000000 --- a/BiuBike/app/src/main/java/overlayutil/IndoorPoiOverlay.java +++ /dev/null @@ -1,108 +0,0 @@ -package overlayutil; - - -import android.os.Bundle; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.search.poi.PoiIndoorResult; - -import java.util.ArrayList; -import java.util.List; - -/** - * 用于显示indoorpoi的overly - */ -public class IndoorPoiOverlay extends OverlayManager { - - private static final int MAX_POI_SIZE = 10; - - private PoiIndoorResult mIndoorPoiResult = null; - - /** - * 构造函数 - * - * @param baiduMap - * 该 IndoorPoiOverlay 引用的 BaiduMap 对象 - */ - public IndoorPoiOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - /** - * 设置IndoorPoi数据 - * - * @param indoorpoiResult - * 设置indoorpoiResult数据 - */ - public void setData(PoiIndoorResult indoorpoiResult) { - this.mIndoorPoiResult = indoorpoiResult; - } - - @Override - public final List getOverlayOptions() { - if (mIndoorPoiResult == null || mIndoorPoiResult.getmArrayPoiInfo() == null) { - return null; - } - List markerList = new ArrayList(); - int markerSize = 0; - for (int i = 0; i < mIndoorPoiResult.getmArrayPoiInfo().size() - && markerSize < MAX_POI_SIZE; i++) { - if (mIndoorPoiResult.getmArrayPoiInfo().get(i).latLng == null) { - continue; - } - markerSize++; - Bundle bundle = new Bundle(); - bundle.putInt("index", i); - markerList.add(new MarkerOptions() - .icon(BitmapDescriptorFactory.fromAssetWithDpi("Icon_mark" - + markerSize + ".png")).extraInfo(bundle) - .position(mIndoorPoiResult.getmArrayPoiInfo().get(i).latLng)); - - } - return markerList; - } - - /** - * 获取该 IndoorPoiOverlay 的 indoorpoi数据 - * - * @return - */ - public PoiIndoorResult getIndoorPoiResult() { - return mIndoorPoiResult; - } - - /** - * 覆写此方法以改变默认点击行为 - * - * @param i - * 被点击的poi在 - * {@link com.baidu.mapapi.search.poi.PoiIndoorResult#getmArrayPoiInfo()} } 中的索引 - * @return - */ - public boolean onPoiClick(int i) { - return false; - } - - @Override - public final boolean onMarkerClick(Marker marker) { - if (!mOverlayList.contains(marker)) { - return false; - } - if (marker.getExtraInfo() != null) { - return onPoiClick(marker.getExtraInfo().getInt("index")); - } - return false; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - // TODO Auto-generated method stub - return false; - } -} - diff --git a/BiuBike/app/src/main/java/overlayutil/IndoorRouteOverlay.java b/BiuBike/app/src/main/java/overlayutil/IndoorRouteOverlay.java deleted file mode 100644 index 6fcaf08..0000000 --- a/BiuBike/app/src/main/java/overlayutil/IndoorRouteOverlay.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. - */ -package overlayutil; - -import android.graphics.Color; -import android.os.Bundle; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.map.PolylineOptions; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.search.route.IndoorRouteLine; - -import java.util.ArrayList; -import java.util.List; - -public class IndoorRouteOverlay extends OverlayManager { - - private IndoorRouteLine mRouteLine; - int[] colorInfo; - - /** - * 构造函数 - * - * @param baiduMap - * 该TransitRouteOverlay引用的 BaiduMap 对象 - */ - public IndoorRouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - colorInfo = new int[]{ Color.argb(178, 0, 78, 255), Color.argb(178, 88, 208, 0), Color.argb(178, 88, 78, - 255)}; - } - - - /** - * 设置路线数据 - * - * @param routeOverlay - * 路线数据 - */ - public void setData(IndoorRouteLine routeOverlay) { - this.mRouteLine = routeOverlay; - } - - /** - * 覆写此方法以改变默认起点图标 - * - * @return 起点图标 - */ - public BitmapDescriptor getStartMarker() { - return null; - } - - /** - * 覆写此方法以改变默认终点图标 - * - * @return 终点图标 - */ - public BitmapDescriptor getTerminalMarker() { - return null; - } - - public int getLineColor() { - return 0; - } - @Override - public List getOverlayOptions() { - if (mRouteLine == null) { - return null; - } - - List overlayList = new ArrayList(); - - - // 添加step的节点 - if (mRouteLine.getAllStep() != null && mRouteLine.getAllStep().size() > 0) { - for (IndoorRouteLine.IndoorRouteStep step : mRouteLine.getAllStep()) { - Bundle b = new Bundle(); - b.putInt("index", mRouteLine.getAllStep().indexOf(step)); - if (step.getEntrace() != null) { - overlayList.add((new MarkerOptions()).position(step.getEntrace().getLocation()) - .zIndex(10).anchor(0.5f, 0.5f).extraInfo(b) - .icon(BitmapDescriptorFactory.fromAssetWithDpi("Icon_walk_route.png"))); - } - - // 最后路段绘制出口点 - if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine.getAllStep().size() - 1) - && step.getExit() != null) { - overlayList.add((new MarkerOptions()).position(step.getExit().getLocation()).anchor(0.5f, 0.5f) - .zIndex(10).icon(BitmapDescriptorFactory.fromAssetWithDpi("Icon_walk_route.png"))); - - } - } - } - // 添加起点starting - if (mRouteLine.getStarting() != null) { - overlayList.add((new MarkerOptions()).position(mRouteLine.getStarting().getLocation()) - .icon(getStartMarker() != null ? getStartMarker() : - BitmapDescriptorFactory.fromAssetWithDpi("Icon_start.png")) - .zIndex(10)); - } - // 添加终点terminal - if (mRouteLine.getTerminal() != null) { - overlayList.add((new MarkerOptions()).position(mRouteLine.getTerminal().getLocation()) - .icon(getTerminalMarker() != null ? getTerminalMarker() : - BitmapDescriptorFactory.fromAssetWithDpi("Icon_end.png")) - .zIndex(10)); - } - - // 添加线poly line list - if (mRouteLine.getAllStep() != null && mRouteLine.getAllStep().size() > 0) { - LatLng lastStepLastPoint = null; - int idex = 0; - for (IndoorRouteLine.IndoorRouteStep step : mRouteLine.getAllStep()) { - List watPoints = step.getWayPoints(); - if (watPoints != null) { - List points = new ArrayList(); - if (lastStepLastPoint != null) { - points.add(lastStepLastPoint); - } - points.addAll(watPoints); - overlayList.add(new PolylineOptions().points(points).width(10) - .color(getLineColor() != 0 ? getLineColor() : colorInfo[idex++ % 3]).zIndex(0)); - lastStepLastPoint = watPoints.get(watPoints.size() - 1); - } - } - - } - - return overlayList; - - } - -// private BitmapDescriptor getIconForStep(IndoorRouteLine.TransitStep step) { -// switch(step.getVehileType()) { -// case ESTEP_WALK: -// return BitmapDescriptorFactory.fromAssetWithDpi("Icon_walk_route.png"); -// case ESTEP_TRAIN: -// return BitmapDescriptorFactory.fromAssetWithDpi("Icon_subway_station.png"); -// case ESTEP_DRIVING: -// case ESTEP_COACH: -// case ESTEP_PLANE: -// case ESTEP_BUS: -// return BitmapDescriptorFactory.fromAssetWithDpi("Icon_bus_station.png"); -// default: -// return null; -// } -// } - - @Override - public boolean onMarkerClick(Marker marker) { - return false; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - return false; - } -} - diff --git a/BiuBike/app/src/main/java/overlayutil/MassTransitRouteOverlay.java b/BiuBike/app/src/main/java/overlayutil/MassTransitRouteOverlay.java deleted file mode 100644 index d38343d..0000000 --- a/BiuBike/app/src/main/java/overlayutil/MassTransitRouteOverlay.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. - */ -package overlayutil; - -import android.graphics.Color; -import android.os.Bundle; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.map.PolylineOptions; -import com.baidu.mapapi.search.route.MassTransitRouteLine; - -import java.util.ArrayList; -import java.util.List; - -public class MassTransitRouteOverlay extends OverlayManager { - - private MassTransitRouteLine mRouteLine; - private boolean isSameCity; - - /** - * 构造函数 - * - * @param baiduMap - * 该TransitRouteOverlay引用的 BaiduMap 对象 - */ - public MassTransitRouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - - /** - * 设置路线数据 - * - * @param routeOverlay - * 路线数据 - */ - public void setData(MassTransitRouteLine routeOverlay) { - this.mRouteLine = routeOverlay; - } - - public void setSameCity( boolean sameCity ) { - isSameCity = sameCity; - } - /** - * 覆写此方法以改变默认起点图标 - * - * @return 起点图标 - */ - public BitmapDescriptor getStartMarker() { - return null; - } - - /** - * 覆写此方法以改变默认终点图标 - * - * @return 终点图标 - */ - public BitmapDescriptor getTerminalMarker() { - return null; - } - - public int getLineColor() { - return 0; - } - @Override - public List getOverlayOptions() { - if (mRouteLine == null) { - return null; - } - - List overlayOptionses = new ArrayList(); - List> steps = mRouteLine.getNewSteps(); - if (isSameCity ) { - // 同城 (同城时,每个steps的get(i)对应的List是一条step的不同方案,此处都选第一条进行绘制,即get(0)) - - // step node - for ( int i = 0; i < steps.size(); i++ ) { - - MassTransitRouteLine.TransitStep step = steps.get(i).get(0); - Bundle b = new Bundle(); - b.putInt("index", i + 1); - - if (step.getStartLocation() != null) { - overlayOptionses.add((new MarkerOptions()).position(step.getStartLocation()) - .anchor(0.5f, 0.5f).zIndex(10).extraInfo(b).icon(getIconForStep(step))); - } - - // 最后一个终点 - if ( (i == steps.size() - 1) && (step.getEndLocation() != null)) { - overlayOptionses.add((new MarkerOptions()).position(step.getEndLocation()) - .anchor(0.5f, 0.5f).zIndex(10) - .icon(getIconForStep(step)) - ); - } - - } - - // polyline - for ( int i = 0; i < steps.size(); i++ ) { - MassTransitRouteLine.TransitStep step = steps.get(i).get(0); - int color = 0; - if (step.getVehileType() != MassTransitRouteLine.TransitStep - .StepVehicleInfoType.ESTEP_WALK) { - // color = Color.argb(178, 0, 78, 255); - color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255); - } else { - // color = Color.argb(178, 88, 208, 0); - color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 88, 208, 0); - } - overlayOptionses.add(new PolylineOptions() - .points(step.getWayPoints()).width(10).color(color) - .zIndex(0)); - } - - } else { - // 跨城 (跨城时,每个steps的get(i)对应的List是一条step的子路线sub_step,需要将它们全部拼接才是一条完整路线) - int stepSum = 0; - for (int i = 0; i < steps.size(); i++ ) { - stepSum += steps.get(i).size(); - } - - // step node - int k = 1; - for ( int i = 0; i < steps.size(); i++ ) { - - for (int j = 0; j < steps.get(i).size(); j++ ) { - MassTransitRouteLine.TransitStep step = steps.get(i).get(j); - Bundle b = new Bundle(); - b.putInt("index", k); - - if (step.getStartLocation() != null) { - overlayOptionses.add((new MarkerOptions()).position(step.getStartLocation()) - .anchor(0.5f, 0.5f).zIndex(10).extraInfo(b).icon(getIconForStep(step))); - } - - // 最后一个终点 - if ( (k == stepSum ) && (step.getEndLocation() != null)) { - overlayOptionses.add((new MarkerOptions()).position(step.getEndLocation()) - .anchor(0.5f, 0.5f).zIndex(10).icon(getIconForStep(step))); - } - - k++; - } - } - - - // polyline - for ( int i = 0; i < steps.size(); i++ ) { - - for (int j = 0; j < steps.get(i).size(); j++ ) { - MassTransitRouteLine.TransitStep step = steps.get(i).get(j); - int color = 0; - if (step.getVehileType() != MassTransitRouteLine.TransitStep - .StepVehicleInfoType.ESTEP_WALK) { - // color = Color.argb(178, 0, 78, 255); - color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255); - } else { - // color = Color.argb(178, 88, 208, 0); - color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 88, 208, 0); - } - if (step.getWayPoints() != null ) { - overlayOptionses.add(new PolylineOptions() - .points(step.getWayPoints()).width(10).color(color) - .zIndex(0)); - } - } - } - - } - - // 起点 - if (mRouteLine.getStarting() != null && mRouteLine.getStarting().getLocation() != null) { - overlayOptionses.add((new MarkerOptions()).position(mRouteLine.getStarting().getLocation()) - .icon(getStartMarker() != null - ? getStartMarker() : BitmapDescriptorFactory.fromAssetWithDpi("Icon_start.png")) - .zIndex(10)); - } - // 终点 - if (mRouteLine.getTerminal() != null && mRouteLine.getTerminal().getLocation() != null) { - overlayOptionses - .add((new MarkerOptions()) - .position(mRouteLine.getTerminal().getLocation()) - .icon(getTerminalMarker() != null ? getTerminalMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_end.png")) - .zIndex(10)); - } - - return overlayOptionses; - - } - - private BitmapDescriptor getIconForStep(MassTransitRouteLine.TransitStep step) { - switch (step.getVehileType()) { - case ESTEP_WALK: - return BitmapDescriptorFactory.fromAssetWithDpi("Icon_walk_route.png"); - case ESTEP_TRAIN: - return BitmapDescriptorFactory.fromAssetWithDpi("Icon_subway_station.png"); - case ESTEP_DRIVING: - case ESTEP_COACH: - case ESTEP_PLANE: - case ESTEP_BUS: - return BitmapDescriptorFactory.fromAssetWithDpi("Icon_bus_station.png"); - default: - return null; - } - } - - @Override - public boolean onMarkerClick(Marker marker) { - return false; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - return false; - } -} diff --git a/BiuBike/app/src/main/java/overlayutil/OverlayManager.java b/BiuBike/app/src/main/java/overlayutil/OverlayManager.java deleted file mode 100644 index a7f8a97..0000000 --- a/BiuBike/app/src/main/java/overlayutil/OverlayManager.java +++ /dev/null @@ -1,117 +0,0 @@ -package overlayutil; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BaiduMap.OnPolylineClickListener; -import com.baidu.mapapi.map.MapStatusUpdateFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.Overlay; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.model.LatLngBounds; - -import java.util.ArrayList; -import java.util.List; - -import static com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener; - -/** - * 该类提供一个能够显示和管理多个Overlay的基类 - *

- * 复写{@link #getOverlayOptions()} 设置欲显示和管理的Overlay列表 - *

- *

- * 通过 - * {@link com.baidu.mapapi.map.BaiduMap#setOnMarkerClickListener(com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener)} - * 将覆盖物点击事件传递给OverlayManager后,OverlayManager才能响应点击事件。 - *

- * 复写{@link #onMarkerClick(com.baidu.mapapi.map.Marker)} 处理Marker点击事件 - *

- */ -public abstract class OverlayManager implements OnMarkerClickListener, OnPolylineClickListener { - - BaiduMap mBaiduMap = null; - private List mOverlayOptionList = null; - - List mOverlayList = null; - - /** - * 通过一个BaiduMap 对象构造 - * - * @param baiduMap - */ - public OverlayManager(BaiduMap baiduMap) { - mBaiduMap = baiduMap; - // mBaiduMap.setOnMarkerClickListener(this); - if (mOverlayOptionList == null) { - mOverlayOptionList = new ArrayList(); - } - if (mOverlayList == null) { - mOverlayList = new ArrayList(); - } - } - - /** - * 覆写此方法设置要管理的Overlay列表 - * - * @return 管理的Overlay列表 - */ - public abstract List getOverlayOptions(); - - /** - * 将所有Overlay 添加到地图上 - */ - public final void addToMap() { - if (mBaiduMap == null) { - return; - } - - removeFromMap(); - List overlayOptions = getOverlayOptions(); - if (overlayOptions != null) { - mOverlayOptionList.addAll(getOverlayOptions()); - } - - for (OverlayOptions option : mOverlayOptionList) { - mOverlayList.add(mBaiduMap.addOverlay(option)); - } - } - - /** - * 将所有Overlay 从 地图上消除 - */ - public final void removeFromMap() { - if (mBaiduMap == null) { - return; - } - for (Overlay marker : mOverlayList) { - marker.remove(); - } - mOverlayOptionList.clear(); - mOverlayList.clear(); - - } - - /** - * 缩放地图,使所有Overlay都在合适的视野内 - *

- * 注: 该方法只对Marker类型的overlay有效 - *

- * - */ - public void zoomToSpan() { - if (mBaiduMap == null) { - return; - } - if (mOverlayList.size() > 0) { - LatLngBounds.Builder builder = new LatLngBounds.Builder(); - for (Overlay overlay : mOverlayList) { - // polyline 中的点可能太多,只按marker 缩放 - if (overlay instanceof Marker) { - builder.include(((Marker) overlay).getPosition()); - } - } - mBaiduMap.setMapStatus(MapStatusUpdateFactory - .newLatLngBounds(builder.build())); - } - } - -} diff --git a/BiuBike/app/src/main/java/overlayutil/PoiOverlay.java b/BiuBike/app/src/main/java/overlayutil/PoiOverlay.java deleted file mode 100644 index c815c7c..0000000 --- a/BiuBike/app/src/main/java/overlayutil/PoiOverlay.java +++ /dev/null @@ -1,112 +0,0 @@ -package overlayutil; - -import android.os.Bundle; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.search.poi.PoiResult; - -import java.util.ArrayList; -import java.util.List; - -/** - * 用于显示poi的overly - */ -public class PoiOverlay extends OverlayManager { - - private static final int MAX_POI_SIZE = 10; - - private PoiResult mPoiResult = null; - - /** - * 构造函数 - * - * @param baiduMap - * 该 PoiOverlay 引用的 BaiduMap 对象 - */ - public PoiOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - /** - * 设置POI数据 - * - * @param poiResult - * 设置POI数据 - */ - public void setData(PoiResult poiResult) { - this.mPoiResult = poiResult; - } - - @Override - public final List getOverlayOptions() { - if (mPoiResult == null || mPoiResult.getAllPoi() == null) { - return null; - } - List markerList = new ArrayList(); - int markerSize = 0; - for (int i = 0; i < mPoiResult.getAllPoi().size() - && markerSize < MAX_POI_SIZE; i++) { - if (mPoiResult.getAllPoi().get(i).location == null) { - continue; - } - markerSize++; - Bundle bundle = new Bundle(); - bundle.putInt("index", i); - markerList.add(new MarkerOptions() - .icon(BitmapDescriptorFactory.fromAssetWithDpi("Icon_mark" - + markerSize + ".png")).extraInfo(bundle) - .position(mPoiResult.getAllPoi().get(i).location)); - - } - return markerList; - } - - /** - * 获取该 PoiOverlay 的 poi数据 - * - * @return - */ - public PoiResult getPoiResult() { - return mPoiResult; - } - - /** - * 覆写此方法以改变默认点击行为 - * - * @param i - * 被点击的poi在 - * {@link com.baidu.mapapi.search.poi.PoiResult#getAllPoi()} 中的索引 - * @return - */ - public boolean onPoiClick(int i) { -// if (mPoiResult.getAllPoi() != null -// && mPoiResult.getAllPoi().get(i) != null) { -// Toast.makeText(BMapManager.getInstance().getContext(), -// mPoiResult.getAllPoi().get(i).name, Toast.LENGTH_LONG) -// .show(); -// } - return false; - } - - @Override - public final boolean onMarkerClick(Marker marker) { - if (!mOverlayList.contains(marker)) { - return false; - } - if (marker.getExtraInfo() != null) { - return onPoiClick(marker.getExtraInfo().getInt("index")); - } - return false; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - // TODO Auto-generated method stub - return false; - } -} diff --git a/BiuBike/app/src/main/java/overlayutil/TransitRouteOverlay.java b/BiuBike/app/src/main/java/overlayutil/TransitRouteOverlay.java deleted file mode 100644 index c8197ca..0000000 --- a/BiuBike/app/src/main/java/overlayutil/TransitRouteOverlay.java +++ /dev/null @@ -1,189 +0,0 @@ -package overlayutil; - -import android.graphics.Color; -import android.os.Bundle; -import android.util.Log; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.Overlay; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.map.PolylineOptions; -import com.baidu.mapapi.search.route.TransitRouteLine; - -import java.util.ArrayList; -import java.util.List; - -/** - * 用于显示换乘路线的Overlay,自3.4.0版本起可实例化多个添加在地图中显示 - */ -public class TransitRouteOverlay extends OverlayManager { - - private TransitRouteLine mRouteLine = null; - - /** - * 构造函数 - * - * @param baiduMap - * 该TransitRouteOverlay引用的 BaiduMap 对象 - */ - public TransitRouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - @Override - public final List getOverlayOptions() { - - if (mRouteLine == null) { - return null; - } - - List overlayOptionses = new ArrayList(); - // step node - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - - for (TransitRouteLine.TransitStep step : mRouteLine.getAllStep()) { - Bundle b = new Bundle(); - b.putInt("index", mRouteLine.getAllStep().indexOf(step)); - if (step.getEntrance() != null) { - overlayOptionses.add((new MarkerOptions()) - .position(step.getEntrance().getLocation()) - .anchor(0.5f, 0.5f).zIndex(10).extraInfo(b) - .icon(getIconForStep(step))); - } - // 最后路段绘制出口点 - if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine - .getAllStep().size() - 1) && step.getExit() != null) { - overlayOptionses.add((new MarkerOptions()) - .position(step.getExit().getLocation()) - .anchor(0.5f, 0.5f).zIndex(10) - .icon(getIconForStep(step))); - } - } - } - - if (mRouteLine.getStarting() != null) { - overlayOptionses.add((new MarkerOptions()) - .position(mRouteLine.getStarting().getLocation()) - .icon(getStartMarker() != null ? getStartMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_start.png")).zIndex(10)); - } - if (mRouteLine.getTerminal() != null) { - overlayOptionses - .add((new MarkerOptions()) - .position(mRouteLine.getTerminal().getLocation()) - .icon(getTerminalMarker() != null ? getTerminalMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_end.png")) - .zIndex(10)); - } - // polyline - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - - for (TransitRouteLine.TransitStep step : mRouteLine.getAllStep()) { - if (step.getWayPoints() == null) { - continue; - } - int color = 0; - if (step.getStepType() != TransitRouteLine.TransitStep.TransitRouteStepType.WAKLING) { -// color = Color.argb(178, 0, 78, 255); - color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255); - } else { -// color = Color.argb(178, 88, 208, 0); - color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 88, 208, 0); - } - overlayOptionses.add(new PolylineOptions() - .points(step.getWayPoints()).width(10).color(color) - .zIndex(0)); - } - } - return overlayOptionses; - } - - private BitmapDescriptor getIconForStep(TransitRouteLine.TransitStep step) { - switch (step.getStepType()) { - case BUSLINE: - return BitmapDescriptorFactory.fromAssetWithDpi("Icon_bus_station.png"); - case SUBWAY: - return BitmapDescriptorFactory.fromAssetWithDpi("Icon_subway_station.png"); - case WAKLING: - return BitmapDescriptorFactory.fromAssetWithDpi("Icon_walk_route.png"); - default: - return null; - } - } - - /** - * 设置路线数据 - * - * @param routeOverlay - * 路线数据 - */ - public void setData(TransitRouteLine routeOverlay) { - this.mRouteLine = routeOverlay; - } - - /** - * 覆写此方法以改变默认起点图标 - * - * @return 起点图标 - */ - public BitmapDescriptor getStartMarker() { - return null; - } - - /** - * 覆写此方法以改变默认终点图标 - * - * @return 终点图标 - */ - public BitmapDescriptor getTerminalMarker() { - return null; - } - - public int getLineColor() { - return 0; - } - /** - * 覆写此方法以改变起默认点击行为 - * - * @param i - * 被点击的step在 - * {@link com.baidu.mapapi.search.route.TransitRouteLine#getAllStep()} - * 中的索引 - * @return 是否处理了该点击事件 - */ - public boolean onRouteNodeClick(int i) { - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().get(i) != null) { - Log.i("baidumapsdk", "TransitRouteOverlay onRouteNodeClick"); - } - return false; - } - - @Override - public final boolean onMarkerClick(Marker marker) { - for (Overlay mMarker : mOverlayList) { - if (mMarker instanceof Marker && mMarker.equals(marker)) { - if (marker.getExtraInfo() != null) { - onRouteNodeClick(marker.getExtraInfo().getInt("index")); - } - } - } - return true; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/BiuBike/app/src/main/java/overlayutil/WalkingRouteOverlay.java b/BiuBike/app/src/main/java/overlayutil/WalkingRouteOverlay.java deleted file mode 100644 index ba716da..0000000 --- a/BiuBike/app/src/main/java/overlayutil/WalkingRouteOverlay.java +++ /dev/null @@ -1,175 +0,0 @@ -package overlayutil; - -import android.graphics.Color; -import android.os.Bundle; -import android.util.Log; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.Marker; -import com.baidu.mapapi.map.MarkerOptions; -import com.baidu.mapapi.map.Overlay; -import com.baidu.mapapi.map.OverlayOptions; -import com.baidu.mapapi.map.Polyline; -import com.baidu.mapapi.map.PolylineOptions; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.search.route.WalkingRouteLine; - -import java.util.ArrayList; -import java.util.List; - -/** - * 用于显示步行路线的overlay,自3.4.0版本起可实例化多个添加在地图中显示 - */ -public class WalkingRouteOverlay extends OverlayManager { - - private WalkingRouteLine mRouteLine = null; - - public WalkingRouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - /** - * 设置路线数据。 - * - * @param line - * 路线数据 - */ - public void setData(WalkingRouteLine line) { - mRouteLine = line; - } - - @Override - public final List getOverlayOptions() { - if (mRouteLine == null) { - return null; - } - - List overlayList = new ArrayList(); - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - for (WalkingRouteLine.WalkingStep step : mRouteLine.getAllStep()) { - Bundle b = new Bundle(); - b.putInt("index", mRouteLine.getAllStep().indexOf(step)); - if (step.getEntrance() != null) { - overlayList.add((new MarkerOptions()) - .position(step.getEntrance().getLocation()) - .rotate((360 - step.getDirection())) - .zIndex(10) - .anchor(0.5f, 0.5f) - .extraInfo(b) - .icon(BitmapDescriptorFactory - .fromAssetWithDpi("Icon_line_node.png"))); - } - - // 最后路段绘制出口点 - if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine - .getAllStep().size() - 1) && step.getExit() != null) { - overlayList.add((new MarkerOptions()) - .position(step.getExit().getLocation()) - .anchor(0.5f, 0.5f) - .zIndex(10) - .icon(BitmapDescriptorFactory - .fromAssetWithDpi("Icon_line_node.png"))); - - } - } - } - // starting - if (mRouteLine.getStarting() != null) { - overlayList.add((new MarkerOptions()) - .position(mRouteLine.getStarting().getLocation()) - .icon(getStartMarker() != null ? getStartMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_start.png")).zIndex(10)); - } - // terminal - if (mRouteLine.getTerminal() != null) { - overlayList - .add((new MarkerOptions()) - .position(mRouteLine.getTerminal().getLocation()) - .icon(getTerminalMarker() != null ? getTerminalMarker() : - BitmapDescriptorFactory - .fromAssetWithDpi("Icon_end.png")) - .zIndex(10)); - } - - // poly line list - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().size() > 0) { - LatLng lastStepLastPoint = null; - for (WalkingRouteLine.WalkingStep step : mRouteLine.getAllStep()) { - List watPoints = step.getWayPoints(); - if (watPoints != null) { - List points = new ArrayList(); - if (lastStepLastPoint != null) { - points.add(lastStepLastPoint); - } - points.addAll(watPoints); - overlayList.add(new PolylineOptions().points(points).width(10) - .color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0)); - lastStepLastPoint = watPoints.get(watPoints.size() - 1); - } - } - - } - - return overlayList; - } - - /** - * 覆写此方法以改变默认起点图标 - * - * @return 起点图标 - */ - public BitmapDescriptor getStartMarker() { - return null; - } - public int getLineColor() { - return 0; - } - /** - * 覆写此方法以改变默认终点图标 - * - * @return 终点图标 - */ - public BitmapDescriptor getTerminalMarker() { - return null; - } - - /** - * 处理点击事件 - * - * @param i - * 被点击的step在 - * {@link com.baidu.mapapi.search.route.WalkingRouteLine#getAllStep()} - * 中的索引 - * @return 是否处理了该点击事件 - */ - public boolean onRouteNodeClick(int i) { - if (mRouteLine.getAllStep() != null - && mRouteLine.getAllStep().get(i) != null) { - Log.i("baidumapsdk", "WalkingRouteOverlay onRouteNodeClick"); - } - return false; - } - - @Override - public final boolean onMarkerClick(Marker marker) { - for (Overlay mMarker : mOverlayList) { - if (mMarker instanceof Marker && mMarker.equals(marker)) { - if (marker.getExtraInfo() != null) { - onRouteNodeClick(marker.getExtraInfo().getInt("index")); - } - } - } - return true; - } - - @Override - public boolean onPolylineClick(Polyline polyline) { - // TODO Auto-generated method stub - return false; - } -} diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBDSpeechDecoder_V1.so b/BiuBike/app/src/main/jniLibs/armeabi/libBDSpeechDecoder_V1.so deleted file mode 100644 index f438fea..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libBDSpeechDecoder_V1.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v4_1_1.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v4_1_1.so deleted file mode 100644 index 94c1612..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v4_1_1.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v5_4_4.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v5_4_4.so new file mode 100644 index 0000000..8ca6a28 Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v5_4_4.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v6_1_0.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v6_1_0.so new file mode 100644 index 0000000..5c38811 Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v6_1_0.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_bikenavi_v6_1_0.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_bikenavi_v6_1_0.so new file mode 100644 index 0000000..2c11d53 Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_bikenavi_v6_1_0.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_cloud_v4_1_1.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_cloud_v4_1_1.so deleted file mode 100644 index 21a9db6..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_cloud_v4_1_1.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_for_bikenavi_v6_1_0.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_for_bikenavi_v6_1_0.so new file mode 100644 index 0000000..1c6c273 Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_for_bikenavi_v6_1_0.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v4_1_1.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v4_1_1.so deleted file mode 100644 index ffc2360..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v4_1_1.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v5_4_4.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v5_4_4.so new file mode 100644 index 0000000..195d906 Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v5_4_4.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v6_1_0.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v6_1_0.so new file mode 100644 index 0000000..b986b1f Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_map_v6_1_0.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_radar_v4_1_1.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_radar_v4_1_1.so deleted file mode 100644 index 00196f1..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_radar_v4_1_1.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_search_v4_1_1.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_search_v4_1_1.so deleted file mode 100644 index ce265d4..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_search_v4_1_1.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_util_v4_1_1.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_util_v4_1_1.so deleted file mode 100644 index fff6786..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduMapSDK_util_v4_1_1.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libBaiduTraceSDK_v3_1_3.so b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduTraceSDK_v3_1_3.so new file mode 100755 index 0000000..932ee8e Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libBaiduTraceSDK_v3_1_3.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libapp_BaiduNaviApplib.so b/BiuBike/app/src/main/jniLibs/armeabi/libapp_BaiduNaviApplib.so deleted file mode 100644 index 3edb1d0..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libapp_BaiduNaviApplib.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libapp_BaiduVIlib.so b/BiuBike/app/src/main/jniLibs/armeabi/libapp_BaiduVIlib.so deleted file mode 100644 index e927389..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libapp_BaiduVIlib.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libaudiomessage-jni.so b/BiuBike/app/src/main/jniLibs/armeabi/libaudiomessage-jni.so deleted file mode 100644 index 05ced27..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libaudiomessage-jni.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libbd_etts.so b/BiuBike/app/src/main/jniLibs/armeabi/libbd_etts.so deleted file mode 100644 index 4ff80e2..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libbd_etts.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libbds.so b/BiuBike/app/src/main/jniLibs/armeabi/libbds.so deleted file mode 100644 index 3c1ed9b..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libbds.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libbdtts.so b/BiuBike/app/src/main/jniLibs/armeabi/libbdtts.so deleted file mode 100644 index cb02769..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libbdtts.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libcurl.so b/BiuBike/app/src/main/jniLibs/armeabi/libcurl.so deleted file mode 100644 index a500e7b..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libcurl.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libetts_domain_data_builder.so b/BiuBike/app/src/main/jniLibs/armeabi/libetts_domain_data_builder.so deleted file mode 100644 index 66e566a..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libetts_domain_data_builder.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libgnustl_shared.so b/BiuBike/app/src/main/jniLibs/armeabi/libgnustl_shared.so deleted file mode 100644 index ab4b3bf..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libgnustl_shared.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libindoor.so b/BiuBike/app/src/main/jniLibs/armeabi/libindoor.so new file mode 100644 index 0000000..a0879cf Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/libindoor.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/liblocSDK6a.so b/BiuBike/app/src/main/jniLibs/armeabi/liblocSDK6a.so deleted file mode 100755 index 83f7f12..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/liblocSDK6a.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/liblocSDK8a.so b/BiuBike/app/src/main/jniLibs/armeabi/liblocSDK8a.so new file mode 100644 index 0000000..5286996 Binary files /dev/null and b/BiuBike/app/src/main/jniLibs/armeabi/liblocSDK8a.so differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/liblocnaviSDK.so b/BiuBike/app/src/main/jniLibs/armeabi/liblocnaviSDK.so deleted file mode 100644 index 2538224..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/liblocnaviSDK.so and /dev/null differ diff --git a/BiuBike/app/src/main/jniLibs/armeabi/libmsc.so b/BiuBike/app/src/main/jniLibs/armeabi/libmsc.so deleted file mode 100644 index 52e9f47..0000000 Binary files a/BiuBike/app/src/main/jniLibs/armeabi/libmsc.so and /dev/null differ diff --git a/BiuBike/app/src/main/res/mipmap-xhdpi/icon_end.png b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_end.png new file mode 100644 index 0000000..48933b4 Binary files /dev/null and b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_end.png differ diff --git a/BiuBike/app/src/main/res/mipmap-xhdpi/icon_gcoding.png b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_gcoding.png new file mode 100755 index 0000000..16adf26 Binary files /dev/null and b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_gcoding.png differ diff --git a/BiuBike/app/src/main/res/mipmap-xhdpi/icon_geo.png b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_geo.png old mode 100755 new mode 100644 diff --git a/BiuBike/app/src/main/res/mipmap-xhdpi/icon_point.png b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_point.png new file mode 100644 index 0000000..1f8567b Binary files /dev/null and b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_point.png differ diff --git a/BiuBike/app/src/main/res/mipmap-xhdpi/icon_start.png b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_start.png new file mode 100644 index 0000000..680d135 Binary files /dev/null and b/BiuBike/app/src/main/res/mipmap-xhdpi/icon_start.png differ