diff --git a/.idea/libraries/Gradle__android_arch_core_runtime_1_1_1_aar.xml b/.idea/libraries/Gradle__android_arch_core_runtime_1_1_1_aar.xml index 8fedfc1..fff6510 100644 --- a/.idea/libraries/Gradle__android_arch_core_runtime_1_1_1_aar.xml +++ b/.idea/libraries/Gradle__android_arch_core_runtime_1_1_1_aar.xml @@ -1,12 +1,12 @@ - - + + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__android_arch_lifecycle_livedata_1_1_1_aar.xml b/.idea/libraries/Gradle__android_arch_lifecycle_livedata_1_1_1_aar.xml index e7d88a8..b8f7b5a 100644 --- a/.idea/libraries/Gradle__android_arch_lifecycle_livedata_1_1_1_aar.xml +++ b/.idea/libraries/Gradle__android_arch_lifecycle_livedata_1_1_1_aar.xml @@ -1,12 +1,12 @@ - - + + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__android_arch_lifecycle_livedata_core_1_1_1_aar.xml b/.idea/libraries/Gradle__android_arch_lifecycle_livedata_core_1_1_1_aar.xml index 92ba370..cf6669a 100644 --- a/.idea/libraries/Gradle__android_arch_lifecycle_livedata_core_1_1_1_aar.xml +++ b/.idea/libraries/Gradle__android_arch_lifecycle_livedata_core_1_1_1_aar.xml @@ -1,12 +1,12 @@ - - + + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__android_arch_lifecycle_runtime_1_1_1_aar.xml b/.idea/libraries/Gradle__android_arch_lifecycle_runtime_1_1_1_aar.xml index 38e4a81..a405af1 100644 --- a/.idea/libraries/Gradle__android_arch_lifecycle_runtime_1_1_1_aar.xml +++ b/.idea/libraries/Gradle__android_arch_lifecycle_runtime_1_1_1_aar.xml @@ -1,12 +1,12 @@ - - + + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__android_arch_lifecycle_viewmodel_1_1_1_aar.xml b/.idea/libraries/Gradle__android_arch_lifecycle_viewmodel_1_1_1_aar.xml index 0f80764..3dc576a 100644 --- a/.idea/libraries/Gradle__android_arch_lifecycle_viewmodel_1_1_1_aar.xml +++ b/.idea/libraries/Gradle__android_arch_lifecycle_viewmodel_1_1_1_aar.xml @@ -1,12 +1,12 @@ - - + + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_android_support_animated_vector_drawable_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_animated_vector_drawable_28_0_0_aar.xml index 3f6c31e..f423dd9 100644 --- a/.idea/libraries/Gradle__com_android_support_animated_vector_drawable_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_animated_vector_drawable_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_appcompat_v7_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_appcompat_v7_28_0_0_aar.xml index 8a30f8d..1901078 100644 --- a/.idea/libraries/Gradle__com_android_support_appcompat_v7_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_appcompat_v7_28_0_0_aar.xml @@ -1,12 +1,12 @@ - + - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_asynclayoutinflater_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_asynclayoutinflater_28_0_0_aar.xml index e25b13c..d351596 100644 --- a/.idea/libraries/Gradle__com_android_support_asynclayoutinflater_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_asynclayoutinflater_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_cardview_v7_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_cardview_v7_28_0_0_aar.xml index ed1e3ba..7efaafb 100644 --- a/.idea/libraries/Gradle__com_android_support_cardview_v7_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_cardview_v7_28_0_0_aar.xml @@ -1,9 +1,9 @@ - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_constraint_constraint_layout_1_1_3_aar.xml b/.idea/libraries/Gradle__com_android_support_constraint_constraint_layout_1_1_3_aar.xml index 1882b97..43a6562 100644 --- a/.idea/libraries/Gradle__com_android_support_constraint_constraint_layout_1_1_3_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_constraint_constraint_layout_1_1_3_aar.xml @@ -1,9 +1,9 @@ - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_coordinatorlayout_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_coordinatorlayout_28_0_0_aar.xml index a7a1131..b7e3088 100644 --- a/.idea/libraries/Gradle__com_android_support_coordinatorlayout_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_coordinatorlayout_28_0_0_aar.xml @@ -1,12 +1,12 @@ - + - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_cursoradapter_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_cursoradapter_28_0_0_aar.xml index 8752124..d19af07 100644 --- a/.idea/libraries/Gradle__com_android_support_cursoradapter_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_cursoradapter_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_customview_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_customview_28_0_0_aar.xml index 9832879..f7cb6aa 100644 --- a/.idea/libraries/Gradle__com_android_support_customview_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_customview_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_design_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_design_28_0_0_aar.xml index c524a31..0138cf4 100644 --- a/.idea/libraries/Gradle__com_android_support_design_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_design_28_0_0_aar.xml @@ -1,12 +1,12 @@ - + - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_documentfile_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_documentfile_28_0_0_aar.xml index da6bf98..44a3806 100644 --- a/.idea/libraries/Gradle__com_android_support_documentfile_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_documentfile_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_drawerlayout_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_drawerlayout_28_0_0_aar.xml index d4edbdc..d8a5305 100644 --- a/.idea/libraries/Gradle__com_android_support_drawerlayout_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_drawerlayout_28_0_0_aar.xml @@ -1,11 +1,11 @@ - + - - + + diff --git a/.idea/libraries/Gradle__com_android_support_interpolator_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_interpolator_28_0_0_aar.xml index 137d9e3..90ee831 100644 --- a/.idea/libraries/Gradle__com_android_support_interpolator_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_interpolator_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_loader_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_loader_28_0_0_aar.xml index 207fb9f..2806bee 100644 --- a/.idea/libraries/Gradle__com_android_support_loader_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_loader_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_localbroadcastmanager_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_localbroadcastmanager_28_0_0_aar.xml index cc18c8c..ea4460e 100644 --- a/.idea/libraries/Gradle__com_android_support_localbroadcastmanager_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_localbroadcastmanager_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_print_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_print_28_0_0_aar.xml index 84a984b..e6d2608 100644 --- a/.idea/libraries/Gradle__com_android_support_print_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_print_28_0_0_aar.xml @@ -1,11 +1,11 @@ - + - - + + diff --git a/.idea/libraries/Gradle__com_android_support_recyclerview_v7_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_recyclerview_v7_28_0_0_aar.xml index 29c1886..3fd6171 100644 --- a/.idea/libraries/Gradle__com_android_support_recyclerview_v7_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_recyclerview_v7_28_0_0_aar.xml @@ -1,12 +1,12 @@ - + - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_slidingpanelayout_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_slidingpanelayout_28_0_0_aar.xml index 7bb602b..ebbcd4a 100644 --- a/.idea/libraries/Gradle__com_android_support_slidingpanelayout_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_slidingpanelayout_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_support_compat_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_support_compat_28_0_0_aar.xml index bc89bf5..6769277 100644 --- a/.idea/libraries/Gradle__com_android_support_support_compat_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_support_compat_28_0_0_aar.xml @@ -1,12 +1,12 @@ - + - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_support_core_ui_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_support_core_ui_28_0_0_aar.xml index 2134767..a161624 100644 --- a/.idea/libraries/Gradle__com_android_support_support_core_ui_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_support_core_ui_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_support_core_utils_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_support_core_utils_28_0_0_aar.xml index 7470423..194df41 100644 --- a/.idea/libraries/Gradle__com_android_support_support_core_utils_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_support_core_utils_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_support_fragment_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_support_fragment_28_0_0_aar.xml index d339719..ba2112f 100644 --- a/.idea/libraries/Gradle__com_android_support_support_fragment_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_support_fragment_28_0_0_aar.xml @@ -1,11 +1,11 @@ - + - - + + diff --git a/.idea/libraries/Gradle__com_android_support_support_media_compat_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_support_media_compat_28_0_0_aar.xml index 2f82817..4a4f4d2 100644 --- a/.idea/libraries/Gradle__com_android_support_support_media_compat_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_support_media_compat_28_0_0_aar.xml @@ -1,12 +1,12 @@ - + - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_support_v4_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_support_v4_28_0_0_aar.xml index c3f4190..9f2e9e8 100644 --- a/.idea/libraries/Gradle__com_android_support_support_v4_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_support_v4_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_support_vector_drawable_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_support_vector_drawable_28_0_0_aar.xml index 0a40fde..b4e96b3 100644 --- a/.idea/libraries/Gradle__com_android_support_support_vector_drawable_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_support_vector_drawable_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_swiperefreshlayout_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_swiperefreshlayout_28_0_0_aar.xml index e1d9f04..ecdc129 100644 --- a/.idea/libraries/Gradle__com_android_support_swiperefreshlayout_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_swiperefreshlayout_28_0_0_aar.xml @@ -1,11 +1,11 @@ - + - - + + diff --git a/.idea/libraries/Gradle__com_android_support_transition_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_transition_28_0_0_aar.xml index 43b840d..31bc8ff 100644 --- a/.idea/libraries/Gradle__com_android_support_transition_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_transition_28_0_0_aar.xml @@ -1,12 +1,12 @@ - + - - - + + + diff --git a/.idea/libraries/Gradle__com_android_support_versionedparcelable_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_versionedparcelable_28_0_0_aar.xml index e760832..b7e5b02 100644 --- a/.idea/libraries/Gradle__com_android_support_versionedparcelable_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_versionedparcelable_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_android_support_viewpager_28_0_0_aar.xml b/.idea/libraries/Gradle__com_android_support_viewpager_28_0_0_aar.xml index fac6e27..821e853 100644 --- a/.idea/libraries/Gradle__com_android_support_viewpager_28_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_android_support_viewpager_28_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_astuetz_pagerslidingtabstrip_1_0_1_aar.xml b/.idea/libraries/Gradle__com_astuetz_pagerslidingtabstrip_1_0_1_aar.xml index 14ad471..b7f868c 100644 --- a/.idea/libraries/Gradle__com_astuetz_pagerslidingtabstrip_1_0_1_aar.xml +++ b/.idea/libraries/Gradle__com_astuetz_pagerslidingtabstrip_1_0_1_aar.xml @@ -1,15 +1,15 @@ - - - + + + - + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_flyco_tablayout_FlycoTabLayout_Lib_2_1_2_aar.xml b/.idea/libraries/Gradle__com_flyco_tablayout_FlycoTabLayout_Lib_2_1_2_aar.xml index a48bca7..406ebe1 100644 --- a/.idea/libraries/Gradle__com_flyco_tablayout_FlycoTabLayout_Lib_2_1_2_aar.xml +++ b/.idea/libraries/Gradle__com_flyco_tablayout_FlycoTabLayout_Lib_2_1_2_aar.xml @@ -1,15 +1,15 @@ - - - + + + - + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_google_android_gms_play_services_audience_16_0_0_aar.xml b/.idea/libraries/Gradle__com_google_android_gms_play_services_audience_16_0_0_aar.xml index b65c3b0..0ed2683 100644 --- a/.idea/libraries/Gradle__com_google_android_gms_play_services_audience_16_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_google_android_gms_play_services_audience_16_0_0_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_google_android_gms_play_services_base_16_0_1_aar.xml b/.idea/libraries/Gradle__com_google_android_gms_play_services_base_16_0_1_aar.xml index f3a74f4..c6ec94f 100644 --- a/.idea/libraries/Gradle__com_google_android_gms_play_services_base_16_0_1_aar.xml +++ b/.idea/libraries/Gradle__com_google_android_gms_play_services_base_16_0_1_aar.xml @@ -1,9 +1,9 @@ - - - + + + diff --git a/.idea/libraries/Gradle__com_google_android_gms_play_services_basement_16_0_1_aar.xml b/.idea/libraries/Gradle__com_google_android_gms_play_services_basement_16_0_1_aar.xml index 0ff8cb7..ac67104 100644 --- a/.idea/libraries/Gradle__com_google_android_gms_play_services_basement_16_0_1_aar.xml +++ b/.idea/libraries/Gradle__com_google_android_gms_play_services_basement_16_0_1_aar.xml @@ -1,9 +1,9 @@ - - - + + + diff --git a/.idea/libraries/Gradle__com_google_android_gms_play_services_plus_16_0_0_aar.xml b/.idea/libraries/Gradle__com_google_android_gms_play_services_plus_16_0_0_aar.xml index 0a5274c..7221368 100644 --- a/.idea/libraries/Gradle__com_google_android_gms_play_services_plus_16_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_google_android_gms_play_services_plus_16_0_0_aar.xml @@ -1,9 +1,9 @@ - - - + + + diff --git a/.idea/libraries/Gradle__com_google_android_gms_play_services_tasks_16_0_1_aar.xml b/.idea/libraries/Gradle__com_google_android_gms_play_services_tasks_16_0_1_aar.xml index 013a1e5..7ccdf81 100644 --- a/.idea/libraries/Gradle__com_google_android_gms_play_services_tasks_16_0_1_aar.xml +++ b/.idea/libraries/Gradle__com_google_android_gms_play_services_tasks_16_0_1_aar.xml @@ -1,8 +1,8 @@ - - + + diff --git a/.idea/libraries/Gradle__com_jakewharton_butterknife_9_0_0_aar.xml b/.idea/libraries/Gradle__com_jakewharton_butterknife_9_0_0_aar.xml index 69ae0a0..bbb756e 100644 --- a/.idea/libraries/Gradle__com_jakewharton_butterknife_9_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_jakewharton_butterknife_9_0_0_aar.xml @@ -1,14 +1,14 @@ - - + + - + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_jakewharton_butterknife_runtime_9_0_0_aar.xml b/.idea/libraries/Gradle__com_jakewharton_butterknife_runtime_9_0_0_aar.xml index 4d18571..ea508ad 100644 --- a/.idea/libraries/Gradle__com_jakewharton_butterknife_runtime_9_0_0_aar.xml +++ b/.idea/libraries/Gradle__com_jakewharton_butterknife_runtime_9_0_0_aar.xml @@ -1,14 +1,14 @@ - - + + - + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_youth_banner_banner_1_4_10_aar.xml b/.idea/libraries/Gradle__com_youth_banner_banner_1_4_10_aar.xml index 16677fb..5046b50 100644 --- a/.idea/libraries/Gradle__com_youth_banner_banner_1_4_10_aar.xml +++ b/.idea/libraries/Gradle__com_youth_banner_banner_1_4_10_aar.xml @@ -1,13 +1,13 @@ - - - + + + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_litepal_android_core_3_0_0_aar.xml b/.idea/libraries/Gradle__org_litepal_android_core_3_0_0_aar.xml index 56fac09..643ed9a 100644 --- a/.idea/libraries/Gradle__org_litepal_android_core_3_0_0_aar.xml +++ b/.idea/libraries/Gradle__org_litepal_android_core_3_0_0_aar.xml @@ -1,13 +1,13 @@ - - - + + + - + \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_litepal_android_java_3_0_0_aar.xml b/.idea/libraries/Gradle__org_litepal_android_java_3_0_0_aar.xml index 34d1274..5efaf42 100644 --- a/.idea/libraries/Gradle__org_litepal_android_java_3_0_0_aar.xml +++ b/.idea/libraries/Gradle__org_litepal_android_java_3_0_0_aar.xml @@ -1,13 +1,13 @@ - - - + + + - + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_dashboard_black_24dp.xml b/app/src/main/res/drawable/ic_dashboard_black_24dp.xml deleted file mode 100644 index 46fc8de..0000000 --- a/app/src/main/res/drawable/ic_dashboard_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_home_black_24dp.xml b/app/src/main/res/drawable/ic_home_black_24dp.xml deleted file mode 100644 index f8bb0b5..0000000 --- a/app/src/main/res/drawable/ic_home_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml deleted file mode 100644 index 0d025f9..0000000 --- a/app/src/main/res/drawable/ic_launcher_background.xml +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml deleted file mode 100644 index 1f6bb29..0000000 --- a/app/src/main/res/drawable/ic_launcher_foreground.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - diff --git a/app/src/main/res/drawable/ic_notifications_black_24dp.xml b/app/src/main/res/drawable/ic_notifications_black_24dp.xml deleted file mode 100644 index 6efc167..0000000 --- a/app/src/main/res/drawable/ic_notifications_black_24dp.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - diff --git a/app/src/main/res/menu/navigation.xml b/app/src/main/res/menu/navigation.xml deleted file mode 100644 index f4de4f8..0000000 --- a/app/src/main/res/menu/navigation.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - diff --git a/qy/.gitignore b/qy/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/qy/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/qy/build.gradle b/qy/build.gradle deleted file mode 100644 index 8f6d795..0000000 --- a/qy/build.gradle +++ /dev/null @@ -1,61 +0,0 @@ -apply plugin: 'com.android.application' - -android { - compileSdkVersion 26 - buildToolsVersion "28.0.3" - useLibrary 'org.apache.http.legacy' - defaultConfig { - applicationId "com.qiyou.mb.android" - minSdkVersion 15 - targetSdkVersion 26 - - testApplicationId "com.qiyou.mb.android.test" - testInstrumentationRunner "android.test.InstrumentationTestRunner" - } - - buildTypes { - release { - minifyEnabled true - proguardFiles 'proguard.cfg' - } - } -} - -dependencies { - api project(':listviewlibrary') - api 'com.android.support:support-v4:26.+' - api 'com.android.support:gridlayout-v7:26.+' - api files('libs/BaiduLBS_Android.jar') - api files('libs/SocialSDK_QQZone_1.jar') - api files('libs/SocialSDK_QQZone_2.jar') - api files('libs/SocialSDK_QQZone_3.jar') - api files('libs/SocialSDK_Sina.jar') - api files('libs/SocialSDK_WeiXin_1.jar') - api files('libs/SocialSDK_WeiXin_2.jar') - api files('libs/SocialSDK_tencentWB_1.jar') - api files('libs/SocialSDK_tencentWB_2.jar') - api files('libs/SocialSDK_tencentWB_3.jar') - // compile files('libs/SpeechApi.jar') - api files('libs/achartengine-1.1.0.jar') - api files('libs/android-async-http-1.4.6.jar') - api files('libs/conceal_android.jar') - api files('libs/httpmime-4.1.3.jar') - api files('libs/libconceal.jar') - api files('libs/locSDK_6.13.jar') - api files('libs/nineoldandroids-2.4.0.jar') - api files('libs/swipelistview-1.0-20130701.103547-12-jar-with-dependencies.jar') - api files('libs/umeng-analytics-v6.0.3.jar') - api files('libs/umeng-update-v2.6.0.1.jar') - api files('libs/umeng_social_sdk.jar') - api files('libs/universal-image-loader-1.9.2.jar') - // compile files('libs/utdid4all-1.0.4.jar') - api 'com.google.code.gson:gson:2.8.0' - api project(':PushSDK') - api 'me.dm7.barcodescanner:zxing:1.9' - // api files('libs/core-3.2.0.jar') - api files('libs/javase-2.3-SNAPSHOT.jar') - api files('libs/com.baidu.tts_2.3.0.jar') -} -//tasks.withType(JavaCompile) { -// options.encoding = "GBK" -//} \ No newline at end of file diff --git a/qy/libs/BaiduLBS_Android.jar b/qy/libs/BaiduLBS_Android.jar deleted file mode 100644 index ca60ed4..0000000 Binary files a/qy/libs/BaiduLBS_Android.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_QQZone_1.jar b/qy/libs/SocialSDK_QQZone_1.jar deleted file mode 100644 index 49b7787..0000000 Binary files a/qy/libs/SocialSDK_QQZone_1.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_QQZone_2.jar b/qy/libs/SocialSDK_QQZone_2.jar deleted file mode 100644 index 86a4c59..0000000 Binary files a/qy/libs/SocialSDK_QQZone_2.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_QQZone_3.jar b/qy/libs/SocialSDK_QQZone_3.jar deleted file mode 100644 index 792c8ed..0000000 Binary files a/qy/libs/SocialSDK_QQZone_3.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_Sina.jar b/qy/libs/SocialSDK_Sina.jar deleted file mode 100644 index e2d6e5f..0000000 Binary files a/qy/libs/SocialSDK_Sina.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_WeiXin_1.jar b/qy/libs/SocialSDK_WeiXin_1.jar deleted file mode 100644 index 5e925ac..0000000 Binary files a/qy/libs/SocialSDK_WeiXin_1.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_WeiXin_2.jar b/qy/libs/SocialSDK_WeiXin_2.jar deleted file mode 100644 index 3f50057..0000000 Binary files a/qy/libs/SocialSDK_WeiXin_2.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_tencentWB_1.jar b/qy/libs/SocialSDK_tencentWB_1.jar deleted file mode 100644 index 24ff7e4..0000000 Binary files a/qy/libs/SocialSDK_tencentWB_1.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_tencentWB_2.jar b/qy/libs/SocialSDK_tencentWB_2.jar deleted file mode 100644 index e1dc103..0000000 Binary files a/qy/libs/SocialSDK_tencentWB_2.jar and /dev/null differ diff --git a/qy/libs/SocialSDK_tencentWB_3.jar b/qy/libs/SocialSDK_tencentWB_3.jar deleted file mode 100644 index e47b83d..0000000 Binary files a/qy/libs/SocialSDK_tencentWB_3.jar and /dev/null differ diff --git a/qy/libs/SpeechApi.jar b/qy/libs/SpeechApi.jar deleted file mode 100644 index ac62086..0000000 Binary files a/qy/libs/SpeechApi.jar and /dev/null differ diff --git a/qy/libs/achartengine-1.1.0.jar b/qy/libs/achartengine-1.1.0.jar deleted file mode 100644 index 9320318..0000000 Binary files a/qy/libs/achartengine-1.1.0.jar and /dev/null differ diff --git a/qy/libs/android-async-http-1.4.6.jar b/qy/libs/android-async-http-1.4.6.jar deleted file mode 100644 index 70391cb..0000000 Binary files a/qy/libs/android-async-http-1.4.6.jar and /dev/null differ diff --git a/qy/libs/com.baidu.tts_2.3.0.jar b/qy/libs/com.baidu.tts_2.3.0.jar deleted file mode 100644 index 761ca7e..0000000 Binary files a/qy/libs/com.baidu.tts_2.3.0.jar and /dev/null differ diff --git a/qy/libs/conceal_android.jar b/qy/libs/conceal_android.jar deleted file mode 100644 index 5f94c06..0000000 Binary files a/qy/libs/conceal_android.jar and /dev/null differ diff --git a/qy/libs/core-3.2.0.jar b/qy/libs/core-3.2.0.jar deleted file mode 100644 index 6af9c62..0000000 Binary files a/qy/libs/core-3.2.0.jar and /dev/null differ diff --git a/qy/libs/httpmime-4.1.3.jar b/qy/libs/httpmime-4.1.3.jar deleted file mode 100644 index ff2014f..0000000 Binary files a/qy/libs/httpmime-4.1.3.jar and /dev/null differ diff --git a/qy/libs/javase-2.3-SNAPSHOT.jar b/qy/libs/javase-2.3-SNAPSHOT.jar deleted file mode 100644 index b7b7357..0000000 Binary files a/qy/libs/javase-2.3-SNAPSHOT.jar and /dev/null differ diff --git a/qy/libs/libconceal.jar b/qy/libs/libconceal.jar deleted file mode 100644 index 1163be9..0000000 Binary files a/qy/libs/libconceal.jar and /dev/null differ diff --git a/qy/libs/locSDK_6.13.jar b/qy/libs/locSDK_6.13.jar deleted file mode 100644 index fa7dc1b..0000000 Binary files a/qy/libs/locSDK_6.13.jar and /dev/null differ diff --git a/qy/libs/nineoldandroids-2.4.0.jar b/qy/libs/nineoldandroids-2.4.0.jar deleted file mode 100644 index 43ee45f..0000000 Binary files a/qy/libs/nineoldandroids-2.4.0.jar and /dev/null differ diff --git a/qy/libs/swipelistview-1.0-20130701.103547-12-jar-with-dependencies.jar b/qy/libs/swipelistview-1.0-20130701.103547-12-jar-with-dependencies.jar deleted file mode 100644 index 4a360d2..0000000 Binary files a/qy/libs/swipelistview-1.0-20130701.103547-12-jar-with-dependencies.jar and /dev/null differ diff --git a/qy/libs/umeng-analytics-v6.0.3.jar b/qy/libs/umeng-analytics-v6.0.3.jar deleted file mode 100644 index 89268c9..0000000 Binary files a/qy/libs/umeng-analytics-v6.0.3.jar and /dev/null differ diff --git a/qy/libs/umeng-update-v2.6.0.1.jar b/qy/libs/umeng-update-v2.6.0.1.jar deleted file mode 100644 index b38dacc..0000000 Binary files a/qy/libs/umeng-update-v2.6.0.1.jar and /dev/null differ diff --git a/qy/libs/umeng_social_sdk.jar b/qy/libs/umeng_social_sdk.jar deleted file mode 100644 index 1d9af78..0000000 Binary files a/qy/libs/umeng_social_sdk.jar and /dev/null differ diff --git a/qy/libs/universal-image-loader-1.9.2.jar b/qy/libs/universal-image-loader-1.9.2.jar deleted file mode 100644 index c1c7550..0000000 Binary files a/qy/libs/universal-image-loader-1.9.2.jar and /dev/null differ diff --git a/qy/libs/utdid4all-1.0.4.jar--toremove.jar b/qy/libs/utdid4all-1.0.4.jar--toremove.jar deleted file mode 100644 index 34815c3..0000000 Binary files a/qy/libs/utdid4all-1.0.4.jar--toremove.jar and /dev/null differ diff --git a/qy/lint.xml b/qy/lint.xml deleted file mode 100644 index cd55cd6..0000000 --- a/qy/lint.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/qy/proguard.cfg b/qy/proguard.cfg deleted file mode 100644 index 1000658..0000000 --- a/qy/proguard.cfg +++ /dev/null @@ -1,272 +0,0 @@ -# ------------------------------------- -# android 原始混淆模板 -# ------------------------------------- - -# ---------------------------------- -# 通过指定数量的优化能执行 -# -optimizationpasses n -# ---------------------------------- --optimizationpasses 5 - -# ---------------------------------- -# 混淆时不会产生形形色色的类名 -# -dontusemixedcaseclassnames -# ---------------------------------- -#-dontusemixedcaseclassnames -# ---------------------------------- -# 指定不去忽略非公共的库类 -# -dontskipnonpubliclibraryclasses -# ---------------------------------- -#-dontskipnonpubliclibraryclasses - -# ---------------------------------- -# 不预校验 -# -dontpreverify -# ---------------------------------- -# -dontpreverify - -# ---------------------------------- -# 输出生成信息 -# -verbose -# ---------------------------------- --verbose - -# ---------------------------------- -# 优化选项 -# optimizations {optimization_filter} -# ---------------------------------- --optimizations !code/simplification/arithmetic,!field/*,!class/merging/* - --keep public class * extends android.app.Activity --keep public class * extends android.app.Application --keep public class * extends android.app.Service --keep public class * extends android.content.BroadcastReceiver --keep public class * extends android.content.ContentProvider --keep public class * extends android.app.backup.BackupAgentHelper --keep public class * extends android.preference.Preference --keep public class com.android.vending.licensing.ILicensingService - --keepclasseswithmembernames class * { - native ; -} -# ----------------- -# modify 修改合并 -# ----------------- --keep public class * extends android.view.View { - public (android.content.Context); - public (android.content.Context, android.util.AttributeSet); - public (android.content.Context, android.util.AttributeSet, int); - public void set*(...); -} - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keep class * implements android.os.Parcelable { - public static final android.os.Parcelable$Creator *; -} - -#-------------------------- -# 保护类型 -keepattributes 说明 -# Exceptions, Signature, Deprecated, SourceFile, SourceDir, LineNumberTable, LocalVariableTable, -# LocalVariableTypeTable, Synthetic, EnclosingMethod, RuntimeVisibleAnnotations, RuntimeInvisibleAnnotations, -# RuntimeVisibleParameterAnnotations, RuntimeInvisibleParameterAnnotations, and AnnotationDefault -# -------------------- --keepattributes ** -#-libraryjars /lib/rt.jar -#for Gson --keepattributes Signature --keepattributes *Annotation* -# Application classes that will be serialized/deserialized over Gson --keep class com.qiyou.mb.android.beans.basic.** { *; } --keep class com.qiyou.mb.android.utils.server.** { *; } - ##---------------End: proguard configuration for Gson ---------- - - - -# ---------------------- -# 不压缩指定的文件 -# -dontshrink -# ---------------------- -#-dontshrink - -# 不优化指定的文件 -# -dontoptimize -# ----------------------- --dontoptimize - -# 不混淆指定的文件 -# -dontobfuscate -# ----------------------- - -# ----- 混淆包路径 ------- --repackageclasses '' --flattenpackagehierarchy '' --target 1.6 - -# -------- 以下是使用了 roboguice-1.1.2.jar 以及 guice-2.0-no_app.jar 功能需要保护的字段及类相关 -------- --keep class com.google.inject.Binder -# ----------------------- --keepclassmembers class * { - @com.google.inject.Inject (...); -} --keepclassmembers class * { - void *(**On*Event); -} --keepclassmembers class **.R$* { - public static ; -} - -# ------ 编译时需要用到的 jar 包 -# -libraryjars libs/baidumapapi_v2_3_0.jar -# -libraryjars libs/baidumapapi_v2_4_2.jar -# -libraryjars libs/locSDK_3.1.jar -# -libraryjars libs/BaiduLBS_Android.jar -# ------ 保护 谷歌第三方 jar 包,界面特效 ---------- --keep class com.google.** { *; } --keep class android.support.v4.** --dontwarn android.support.v4.** -#zxing scan --keep class me.dm7.barcodescanner.** { *; } --dontwarn com.google.zxing.** -# ------ 保护百度地址jar包 -------- --keep class com.baidu.** { *; } --keep class vi.com.gdi.bgl.android.**{*;} --dontwarn com.baidu.** - -# imgage load --keep class com.nostra13.universalimageloader.** { *; } - -# --- 打包时忽略以下类的警告 -- --dontwarn com.classpackage.AA - -#-keepnames class * implements java.io.Serializable -# ---------保护所有实体中的字段名称---------- --keepclassmembers class * implements java.io.Serializable { - ; -} - -# --------- 保护类中的所有方法名 ------------ --keepclassmembers class * { - public ; -} - --assumenosideeffects class android.util.Log { - public static *** d(...); - public static *** v(...); -} - --dontwarn com.iflytek.** --keepattributes Signature -#-keep public class * extends android.app.Activity -#-keep public class * extends android.app.Application -#-keep public class * extends android.app.Service -#-keep public class * extends android.content.BroadcastReceiver -#-keep public class * extends android.content.ContentProvider --keep class com.iflytek.**{*;} - --keep class * extends java.util.ListResourceBundle { - protected Object[][] getContents(); -} - --keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable { - public static final *** NULL; -} - --keepnames @com.google.android.gms.common.annotation.KeepName class * --keepclassmembernames class * { - @com.google.android.gms.common.annotation.KeepName *; -} - --keepnames class * implements android.os.Parcelable { - public static final ** CREATOR; -} - - --dontshrink --dontoptimize --dontwarn com.google.android.maps.** --dontwarn android.webkit.WebView --dontwarn com.umeng.** --dontwarn com.tencent.weibo.sdk.** --dontwarn com.facebook.** - - -dontwarn com.taobao.** - -dontwarn anet.channel.** - -dontwarn anetwork.channel.** - -dontwarn org.android.** - -dontwarn org.apache.thrift.** - -dontwarn com.xiaomi.** - -dontwarn com.huawei.** - -keep class com.taobao.** {*;} - -keep class org.android.** {*;} - -keep class anet.channel.** {*;} - -keep class com.umeng.** {*;} - -keep class com.xiaomi.** {*;} - -keep class com.huawei.** {*;} - -keep class org.apache.thrift.** {*;} - - -keep class com.alibaba.sdk.android.**{*;} - -keep class com.ut.**{*;} - -keep class com.ta.**{*;} - -keep public class **.R$*{ - public static final int *; - } -#-libraryjars libs/SocialSDK_QQZone_2.jar - --keep enum com.facebook.** --keepattributes Exceptions,InnerClasses,Signature --keepattributes *Annotation* --keepattributes SourceFile,LineNumberTable - --keep public interface com.facebook.** --keep public interface com.tencent.** --keep public interface com.umeng.socialize.** --keep public interface com.umeng.socialize.sensor.** --keep public interface com.umeng.scrshot.** - --keep public class com.umeng.socialize.* {*;} --keep public class javax.** --keep public class android.webkit.** - --keep class com.facebook.** --keep class com.umeng.scrshot.** --keep public class com.tencent.** {*;} --keep class com.umeng.socialize.sensor.** - --keep class com.tencent.mm.sdk.modelmsg.WXMediaMessage {*;} - --keep class com.tencent.mm.sdk.modelmsg.** implements com.tencent.mm.sdk.modelmsg.WXMediaMessage$IMediaObject {*;} - --keep class im.yixin.sdk.api.YXMessage {*;} --keep class im.yixin.sdk.api.** implements im.yixin.sdk.api.YXMessage$YXMessageData{*;} - --keep public class [com.qiyou.mb.android].R$*{ - public static final int *; -} --keepclassmembers class * { - public (org.json.JSONObject); -} -# 以下类过滤不混淆 --keep public class * extends com.umeng.** -# 以下包不进行过滤 --keep class com.umeng.** { *; } - -# Keep our interfaces so they can be used by other ProGuard rules. -# See http://sourceforge.net/p/proguard/bugs/466/ --keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip --keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters - -# Do not strip any method/class that is annotated with @DoNotStrip --keep @com.facebook.proguard.annotations.DoNotStrip class * --keepclassmembers class * { - @com.facebook.proguard.annotations.DoNotStrip *; -} - --keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { - void set*(***); - *** get*(); -} - diff --git a/qy/src/androidTest/res/drawable-hdpi/ic_launcher.png b/qy/src/androidTest/res/drawable-hdpi/ic_launcher.png deleted file mode 100644 index 96a442e..0000000 Binary files a/qy/src/androidTest/res/drawable-hdpi/ic_launcher.png and /dev/null differ diff --git a/qy/src/androidTest/res/drawable-ldpi/ic_launcher.png b/qy/src/androidTest/res/drawable-ldpi/ic_launcher.png deleted file mode 100644 index 9923872..0000000 Binary files a/qy/src/androidTest/res/drawable-ldpi/ic_launcher.png and /dev/null differ diff --git a/qy/src/androidTest/res/drawable-mdpi/ic_launcher.png b/qy/src/androidTest/res/drawable-mdpi/ic_launcher.png deleted file mode 100644 index 359047d..0000000 Binary files a/qy/src/androidTest/res/drawable-mdpi/ic_launcher.png and /dev/null differ diff --git a/qy/src/androidTest/res/drawable-xhdpi/ic_launcher.png b/qy/src/androidTest/res/drawable-xhdpi/ic_launcher.png deleted file mode 100644 index 71c6d76..0000000 Binary files a/qy/src/androidTest/res/drawable-xhdpi/ic_launcher.png and /dev/null differ diff --git a/qy/src/androidTest/res/values/strings.xml b/qy/src/androidTest/res/values/strings.xml deleted file mode 100644 index 5c27338..0000000 --- a/qy/src/androidTest/res/values/strings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - TestQyTest - - diff --git a/qy/src/main/AndroidManifest.xml b/qy/src/main/AndroidManifest.xml deleted file mode 100644 index c20f80f..0000000 --- a/qy/src/main/AndroidManifest.xml +++ /dev/null @@ -1,315 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/assets/bd_etts_speech_female.dat b/qy/src/main/assets/bd_etts_speech_female.dat deleted file mode 100644 index 4101538..0000000 Binary files a/qy/src/main/assets/bd_etts_speech_female.dat and /dev/null differ diff --git a/qy/src/main/assets/bd_etts_speech_male.dat b/qy/src/main/assets/bd_etts_speech_male.dat deleted file mode 100644 index f36c3a1..0000000 Binary files a/qy/src/main/assets/bd_etts_speech_male.dat and /dev/null differ diff --git a/qy/src/main/assets/bd_etts_text.dat b/qy/src/main/assets/bd_etts_text.dat deleted file mode 100644 index 2bc7a59..0000000 Binary files a/qy/src/main/assets/bd_etts_text.dat and /dev/null differ diff --git a/qy/src/main/assets/temp_license b/qy/src/main/assets/temp_license deleted file mode 100644 index 4384c02..0000000 --- a/qy/src/main/assets/temp_license +++ /dev/null @@ -1 +0,0 @@ -949467009b6b49774e1965ce072d44ea334807d53dc2636f95ede27592a95390b0440aafedf2db86feece98f39ac7f2fc10db985fd0e8598ec023116b93abdd77bd7ac7a1e83157e2c45151c61c47e3e22fde3f1f87d2e678418305e066de25b3fc5876c0acd3755cb9ec7ffb1d9c7ed94634215fd80ce6e0bc646e9f6a42ff954bafd3c9ebe2edf612bb536f28b9a771db519e0843155b388f69afa91be62472cf1005339868d5e1af244a137707aa588af1ba03d908a69320d449e38329dede1a0770e6a725a04d4190545b120a9902340c1255c73a6ec08ad731c3f601c4e2efbeccd660c53497009522a94566a14da63bdc6fab1e51e25a7fc6f403bbf39 \ No newline at end of file diff --git a/qy/src/main/java/com/baidu/mapapi/overlayutil/BikingRouteOverlay.java b/qy/src/main/java/com/baidu/mapapi/overlayutil/BikingRouteOverlay.java deleted file mode 100644 index 268a8f9..0000000 --- a/qy/src/main/java/com/baidu/mapapi/overlayutil/BikingRouteOverlay.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. - */ -package com.baidu.mapapi.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; - -/** - * 鐢ㄤ簬鏄剧ず楠戣璺嚎鐨凮verlay - */ -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"))); - } - - // 鏈�鍚庤矾娈电粯鍒跺嚭鍙g偣 - 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/qy/src/main/java/com/baidu/mapapi/overlayutil/BusLineOverlay.java b/qy/src/main/java/com/baidu/mapapi/overlayutil/BusLineOverlay.java deleted file mode 100644 index 0ee14dc..0000000 --- a/qy/src/main/java/com/baidu/mapapi/overlayutil/BusLineOverlay.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.baidu.mapapi.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 - * 璇usLineOverlay鎵�寮曠敤鐨� 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/qy/src/main/java/com/baidu/mapapi/overlayutil/DrivingRouteOverlay.java b/qy/src/main/java/com/baidu/mapapi/overlayutil/DrivingRouteOverlay.java deleted file mode 100644 index 97e898a..0000000 --- a/qy/src/main/java/com/baidu/mapapi/overlayutil/DrivingRouteOverlay.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.baidu.mapapi.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 - * 璇rivingRouteOvelray寮曠敤鐨� 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"))); - } - // 鏈�鍚庤矾娈电粯鍒跺嚭鍙g偣 - 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/qy/src/main/java/com/baidu/mapapi/overlayutil/OverlayManager.java b/qy/src/main/java/com/baidu/mapapi/overlayutil/OverlayManager.java deleted file mode 100644 index 5f7fded..0000000 --- a/qy/src/main/java/com/baidu/mapapi/overlayutil/OverlayManager.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.baidu.mapapi.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.ConcurrentModificationException; -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; - - protected 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(); - - public List getOverlayMarkers(){ - return mOverlayList; - } - - /** - * 将所有Overlay 添加到地图上 - */ - public final void addToMap() { - if (mBaiduMap == null) { - return; - } - try{ - removeFromMap(); - List overlayOptions = getOverlayOptions(); - if (overlayOptions != null) { - mOverlayOptionList.addAll(overlayOptions);//getOverlayOptions()); - } - - for (OverlayOptions option : mOverlayOptionList) { - if(option==null)continue; - try{ - mOverlayList.add(mBaiduMap.addOverlay(option)); - }catch(Exception e){ -// Log.e("com.qiyou", e.getStackTrace().toString()); - } - } - }catch(ConcurrentModificationException e){ -// Log.e("com.qiyou", e.getMessage()); - }catch(Exception e){ -// Log.e("com.qiyou", e.getMessage()); - } -// addLines(); - } - - /** - * add lines - */ - /* public void addLines(){ - - }*/ - /** - * 将所有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(); - synchronized(mOverlayList) { - for (Overlay overlay : mOverlayList) { - // polyline 中的点可能太多,只按marker 缩放 - if (overlay instanceof Marker) { - builder.include(((Marker) overlay).getPosition()); - } - } - } - mBaiduMap.setMapStatus(MapStatusUpdateFactory - .newLatLngBounds(builder.build())); - } - } - -} diff --git a/qy/src/main/java/com/baidu/mapapi/overlayutil/PoiOverlay.java b/qy/src/main/java/com/baidu/mapapi/overlayutil/PoiOverlay.java deleted file mode 100644 index 4caafab..0000000 --- a/qy/src/main/java/com/baidu/mapapi/overlayutil/PoiOverlay.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.baidu.mapapi.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鐨刼verly - */ -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/qy/src/main/java/com/baidu/mapapi/overlayutil/TransitRouteOverlay.java b/qy/src/main/java/com/baidu/mapapi/overlayutil/TransitRouteOverlay.java deleted file mode 100644 index 74e20ff..0000000 --- a/qy/src/main/java/com/baidu/mapapi/overlayutil/TransitRouteOverlay.java +++ /dev/null @@ -1,189 +0,0 @@ -package com.baidu.mapapi.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; - -/** - * 鐢ㄤ簬鏄剧ず鎹箻璺嚎鐨凮verlay锛岃嚜3.4.0鐗堟湰璧峰彲瀹炰緥鍖栧涓坊鍔犲湪鍦板浘涓樉绀� - */ -public class TransitRouteOverlay extends OverlayManager { - - private TransitRouteLine mRouteLine = null; - - /** - * 鏋勯�犲嚱鏁� - * - * @param baiduMap - * 璇ransitRouteOverlay寮曠敤鐨� 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))); - } - // 鏈�鍚庤矾娈电粯鍒跺嚭鍙g偣 - 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/qy/src/main/java/com/baidu/mapapi/overlayutil/WalkingRouteOverlay.java b/qy/src/main/java/com/baidu/mapapi/overlayutil/WalkingRouteOverlay.java deleted file mode 100644 index cab2db2..0000000 --- a/qy/src/main/java/com/baidu/mapapi/overlayutil/WalkingRouteOverlay.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.baidu.mapapi.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; - -/** - * 鐢ㄤ簬鏄剧ず姝ヨ璺嚎鐨刼verlay锛岃嚜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"))); - } - - // 鏈�鍚庤矾娈电粯鍒跺嚭鍙g偣 - 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/qy/src/main/java/com/qiyou/mb/android/Activity_qiyouBase.java b/qy/src/main/java/com/qiyou/mb/android/Activity_qiyouBase.java deleted file mode 100644 index 3babd52..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/Activity_qiyouBase.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.qiyou.mb.android; - -import com.qiyou.mb.android.upgrade.UpdateManager; - -import android.os.Bundle; -import android.support.v4.app.FragmentActivity; - -public class Activity_qiyouBase extends FragmentActivity{ - - public QiYouApplication app ; - - public Activity_qiyouBase() { - // TODO Auto-generated constructor stub - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - app = (QiYouApplication) getApplication(); - } - - public void checkUpdate(boolean isSilence){ - UpdateManager manager = new UpdateManager(this); - if(isSilence) - manager.checkUpdateSilence(); - else - manager.checkUpdate(); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/QiYouApplication.java b/qy/src/main/java/com/qiyou/mb/android/QiYouApplication.java deleted file mode 100644 index 6eff1b7..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/QiYouApplication.java +++ /dev/null @@ -1,3671 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android; - -import android.app.AlarmManager; -import android.app.Application; -import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; -import android.graphics.Bitmap; -import android.graphics.Point; -import android.location.Location; -import android.location.LocationManager; -import android.os.Environment; -import android.os.Handler; -import android.os.Message; -import android.os.PowerManager; -import android.os.SystemClock; -import android.preference.PreferenceManager; -import android.telephony.TelephonyManager; -import android.text.TextUtils; -import android.util.Log; - -import com.baidu.location.BDLocationListener; -import com.baidu.location.LocationClient; -import com.baidu.mapapi.BMapManager; -import com.baidu.mapapi.SDKInitializer; -import com.baidu.mapapi.search.geocode.GeoCoder; -import com.baidu.tts.auth.AuthInfo; -import com.baidu.tts.client.SpeechError; -import com.baidu.tts.client.SpeechSynthesizer; -import com.baidu.tts.client.SpeechSynthesizerListener; -import com.baidu.tts.client.SynthesizerTool; -import com.baidu.tts.client.TtsMode; -import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain; -import com.facebook.crypto.Crypto; -import com.facebook.crypto.Entity; -import com.facebook.crypto.util.SystemNativeCryptoLibrary; -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.AsyncHttpClient; -import com.loopj.android.http.AsyncHttpResponseHandler; -import com.loopj.android.http.RequestParams; -import com.loopj.android.http.ResponseHandlerInterface; -import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache; -import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; -import com.nostra13.universalimageloader.core.DisplayImageOptions; -import com.nostra13.universalimageloader.core.ImageLoader; -import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; -import com.nostra13.universalimageloader.core.assist.ImageScaleType; -import com.nostra13.universalimageloader.core.assist.QueueProcessingType; -import com.qiyou.mb.android.beans.Statistics; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.User; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.beans.basic.GEOs; -import com.qiyou.mb.android.beans.basic.GPItem; -import com.qiyou.mb.android.beans.basic.StatTrack; -import com.qiyou.mb.android.beans.basic.Statics_bean; -import com.qiyou.mb.android.beans.basic.TypeStatistics; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.service.BDLocationSvc; -import com.qiyou.mb.android.service.LocationService2; -import com.qiyou.mb.android.service.QNaviSvc; -import com.qiyou.mb.android.service.TimtickService; -import com.qiyou.mb.android.service.TrackDbServiceBackground; -import com.qiyou.mb.android.service.TrackGEOService; -import com.qiyou.mb.android.service.TrackPlaybackService; -import com.qiyou.mb.android.service.sync; -import com.qiyou.mb.android.utils.FileUtil; -import com.qiyou.mb.android.utils.TrackCache; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.log.QLog; -import com.umeng.analytics.MobclickAgent; -import com.umeng.message.IUmengRegisterCallback; -import com.umeng.message.PushAgent; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CookieStore; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.params.ConnManagerParams; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.cookie.Cookie; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.UnknownHostException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -//import com.iflytek.speech.ErrorCode; -//import com.iflytek.speech.ISpeechModule; -//import com.iflytek.speech.InitListener; -//import com.iflytek.speech.SpeechConstant; -//import com.iflytek.speech.SpeechSynthesizer; -//import com.iflytek.speech.SpeechUtility; -//import com.iflytek.speech.SynthesizerListener; -//import com.qiyou.mb.android.service.TrackDbService; - - public class QiYouApplication extends Application { - public static String TAG="com.qiyou.QiYouApplication"; - public static final String dTAG ="com.qiyou"; - - public User user=new User(); - private static QiYouApplication mInstance = null; - public boolean m_bKeyRight = true; - /* - * when UI is active, send, else not send - */ - public boolean canSendLocation2UI; - public boolean isUIactive; - public String currentActiveFragment; - public boolean isStaticsticsDone=true; - // public HashMap StatisticsTracks; -// public SparseArray StatisticsTracks; -// public List typeUsedLst; - public boolean statTrackLoading=false; - - public Statistics mStatistics; - -// public boolean isGetingStatistics=false; -// public ConcurrentHashMap tracks_cached; -// public HashMap tracks_cached; - public ConcurrentHashMap tracks_json_cached; - public ConcurrentHashMap location_cached; - public GEOs geos = new GEOs(); - public Track currentTrack; - public Track recordingTrack; - public Track gpxTrack; -// public Track naviTrack; - public int naviTrackId; - public boolean isNaving=false; - public boolean isNavPaused=false; - private ArrayList importedGpx; - public ArrayList toDecideLocations; -// public Track copyTrack; -// private StatTrack statTrack; -// public double sumDiff=0; //TODO: remove -// public double sumDiff2=0; //TODO: remove - public Location lastSavedLocation; - public Location lastNaviLocation; - public Location lastLocation; - public Location lastBearLoc; - public HashMap bearLocs = new HashMap(); - public HashMap sumBearLocs = new HashMap(); -// public long lastBearLoc; - public float sumBear; - public float sumBear2; - public int cntBear; - public int cntBeared; - public long lastSumbear; - public float bearDist; - public float targetBear; -// private int cntKm; - public long timeKm; - public long lastPaused; - public long sumPaused; - public long lastOfftime; - - //---share location - public long lastSharedTime; - - public float rd =1000f; //used in route_fragment for checkWps - - public boolean isNewLogin=false; -public boolean isRouting; - - /* - * offtime will be reset to 0 after each forceupdate - */ - public long offtime; - /* - * total sum offtime since the time when lost gps, recorded in the waypoint. it will not be reset by forceupdate. - */ - public long sumOfftimeWp; - public double sumDist; - public double sumNavDist; -// public double sumDist2; - public float SpDist; - public float locDist; -// public float sumSpeed; -// public int spdCnt=0; - public float lastEle=QiYouConstant.MAX_ELE; - public ArrayList eles =new ArrayList (); - /* - * 坡度数据 - */ - public float maxEle = QiYouConstant.MAX_ELE*-1; - public float minEle =QiYouConstant.MAX_ELE ; - public float upDist; - public float downDist; - - - - /* - * when gps code start,wp count to skip for ele calculation. - */ - public int skipCnt=0; - public boolean plCanRecord= false; - public boolean playBack= false; - public boolean playBackStopped= false; - public boolean playbackPaused= false; - public int playBackTrackId =0; - public int playProgressTarget =-1; - - -// public String userName; - public boolean isOneRequestForceUpdate; - public boolean isGPSstopped =false; - public long minTime= 0; - public long gpsStartTime; - public long lastGpsStartTime; - public long lastGpsStopTime; - public long lastLocationTime; - - public int GPS_SPAN_FACTOR=1; -// public long lastGPStime; //last gps locaiton time that showing in updateUI function. -// public String City; - SharedPreferences pref; - Editor pe; - Editor pEditor ; - -/* MKSearch*/ GeoCoder mSearch ; - -// public Point screenSize; - -// public SensorManager sm = null; -// public Sensor mAccelerometer = null; - -// public boolean isProcessingGEO =false; //last time receiving an new connected wifi network. -/* - * 是不是正在记录骑行/运动轨迹数据 - */ - public static boolean isRecording =false; - private BMapManager mBMapManager = null; -public SharedPreferences settings ; - //preference -public long startTime; - -public LocationManager lm; -PendingIntent locationListenerPendingIntent; -//PendingIntent netwrokLocationListenerPendingIntent; -//public MapView mMapview; -public LocationClient mLocClient; -public BDLocationListener bdListener; -private GEOaddress GEOinfo; -//TimeTickReceiver timeTickReceiver; -Intent timeTickIntent; -private HttpClient mHttpClient = null; -private static final String CHARSET = HTTP.UTF_8; - - -private HashMap> newCategoryList; -private HashMap> delCategoryList; -private ArrayList queryCategoryList; - -private TrackCache trackCache = new TrackCache(); - -//public long lastCheckNaviPoint=0; -//public boolean isWrongWayAlert; - -private ConcurrentHashMap webObjcache; - - - public QiYouApplication() { - // TODO Auto-generated constructor stub - -// initSdPath(); - } - /* - * - */ - @Override - public final void onCreate() - { - - //TODO: as the Application.onCreate() called muiti times during the application running, - //so need review the functions it espected to call for create only once. - if(mInstance!=null){ - Log.d(dTAG, TAG+"The Application OnCreate was called already."); -// Utils.logStackTrace(new Exception("The Application OnCreate was called already."),dTAG); - return; - } -// initSdPath(); why it is after the trackprovider? - super.onCreate(); - startTime =System.currentTimeMillis(); - -// Utils.logStackTrace(new Exception("The Application OnCreate."),dTAG); -// Utils.logStackTrace(new Exception("Log.e test on onCreate(),Application Started. time: " + startTime),dTAG); -// Log.v(dTAG, TAG+" is developer model? " +QiYouConstant.DEVELOPER_MODE); - initialApplication(); -// QLog.getLogger().d(dTAG,TAG+" onCreate(),Application Started. cost time: " + (System.currentTimeMillis() - startTime)); - -// getCurrentCity(); - } - - void initialApplication() - { - - Intent locIntent = new Intent(QiYouConstant.ACTION_NEW_LOCATION_CHANGED); - locationListenerPendingIntent = PendingIntent.getBroadcast(this, 0, locIntent, PendingIntent.FLAG_UPDATE_CURRENT); -// GPSwarmup(); - -// Intent networkLocIntent = new Intent(QiYouConstant.ACTION_NEW_COARSE_LOCATION); -// netwrokLocationListenerPendingIntent = PendingIntent.getBroadcast(this, 0, networkLocIntent, PendingIntent.FLAG_UPDATE_CURRENT); - -// tracks_cached = new ConcurrentHashMap(); - settings = PreferenceManager.getDefaultSharedPreferences(this); - pEditor =settings.edit(); - getPreferences(); - initClient(this); - setAuth(); - QiYouConstant.NETWORK_CONNECTED =Utils.isNetworkConnected(this); - initialShowingGpxs(); - worksOnLine(0); - - setPreferences(false,true); - locationAm=(AlarmManager)getSystemService(ALARM_SERVICE); - lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); - - - mInstance = this; - initEngineManager(this); - - pref = getSharedPreferences(QiYouConstant.SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE); - pe= pref.edit(); - - - //check last track status -// QLog.getLogger().d(dTAG,TAG+" start to check last track status,it may at Andorid's startup. " ); -// Intent serviceIntent = new Intent(this, LocationService.class); -// serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_BOOT, "True"); -// this.startService(serviceIntent); - - if (QiYouConstant.DEVELOPER_MODE) { -// IStrictMode strictMode = PlatformSpecificImplementationFactory.getStrictMode(); -// if (strictMode != null) -// strictMode.enableStrictMode(); - } - -// timeTickReceiver =new TimeTickReceiver(); - timeTickIntent = new Intent(this, TimtickService.class); - regTimeTick(); -// sm = (SensorManager)getSystemService(SENSOR_SERVICE); -// mAccelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); - initialSpeech(); - - initCryto(); - - setPhoneId(); - QLog.getLogger().d(dTAG, "mobileid is"+ getPhoneId()); - getStaticsTracks(); - - initialPushSDK(); - - } - - void initialPushSDK(){ - PushAgent mPushAgent = PushAgent.getInstance(this); -//注册推送服务,每次调用register方法都会回调该接口 - mPushAgent.register(new IUmengRegisterCallback() { - - @Override - public void onSuccess(String deviceToken) { - //注册成功会返回device token - QLog.getLogger().d(dTAG, " deviceToken of push is "+ deviceToken); - } - - @Override - public void onFailure(String s, String s1) { - QLog.getLogger().d(dTAG, " push agent regist failed "); - } - }); - - } - public Crypto crypto; - public Entity entity; - private void initCryto(){ - crypto = new Crypto( - new SharedPrefsBackedKeyChain(this), - new SystemNativeCryptoLibrary()); - entity = new Entity("TEST"); - } - - -/* private void initSdPath(){ - Utils.initSdPath(this); - }*/ - public void initEngineManager(Context context) { - /* if (getmBMapManager() == null) { - setmBMapManager(new BMapManager(context)); - } - -// if (!getmBMapManager().init(QiYouConstant.BAIDU_API_KEY,new MyGeneralListener())) { - if (!getmBMapManager().init(new MyGeneralListener())) { //v3.4.1 - - Toast.makeText(QiYouApplication.getInstance().getApplicationContext(), - "BMapManager 初始化错误!", Toast.LENGTH_LONG).show(); - }*/ - /* if(mSearch ==null){ - mSearch= GeoCoder.newInstance(); - mSearch.setOnGetGeoCodeResultListener(new MySearchListener()); - }*/ - - SDKInitializer.initialize(this); - - - // 注册 SDK 广播监听者 - IntentFilter iFilter = new IntentFilter(); - iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK); - iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR); - iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR); - mReceiver = new SDKReceiver(); - registerReceiver(mReceiver, iFilter); - - } - - public static QiYouApplication getInstance() { - return mInstance; - } - - - public BMapManager getmBMapManager() { - return mBMapManager; - } - public void setmBMapManager(BMapManager mBMapManager) { - this.mBMapManager = mBMapManager; - } - - /** - * 构造广播监听类,监听 SDK key 验证以及网络异常广播 - */ - public class SDKReceiver extends BroadcastReceiver { - public void onReceive(Context context, Intent intent) { - String s = intent.getAction(); - - if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) { - QLog.getLogger().d(dTAG,"key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置"); - } else if (s - .equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) { - QLog.getLogger().d(dTAG,"key 验证成功! 功能可以正常使用"); - - } - else if (s - .equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) { - QLog.getLogger().d(dTAG,"网络出错"); - } - } - } - - private SDKReceiver mReceiver; - - public Track getCurrentTrack() { - if(null == currentTrack) currentTrack = new Track(); - return currentTrack; - } - - /* - *set the gloable current track object, usually it is from db query. - *put it into the track cache too. - */ - public void setCurrentTrack(Track _currentTrack) { - setCurrentTrack(_currentTrack,false); - } - - public void setCurrentTrack(Track _currentTrack,boolean isWebQuery) { - currentTrack = _currentTrack; - if(_currentTrack==null)return; - currentTrackId =isWebQuery?_currentTrack.getTrackBean().getSvrNumber():_currentTrack.getTrackBean().getTrackId(); - //check if the track object has been in the cache,if yes, then update the cache, if not then add it into the cache. - if(currentTrackId <=0) return; - getTrackCache().put(currentTrackId,_currentTrack); -// getTrackCache().putIfAbsent(_currentTrack.getTrackBean().getTrackId(),_currentTrack); -// getTrackJsoncache().put(_currentTrack.getTrackBean().getTrackId(), _currentTrack.getJsonWps().toString()); -// if(tracks_cached.size()>10) -// { -//// getTrackCache() -//// getTrackJsoncache() -// //TODO: remove old values for the size limit to save memory. -// } - } - public long getGPS_REQUEST_SPAN(){ - return GPS_SPAN_FACTOR*QiYouConstant.MAX_GPS_SPAN; - } - - /* - * is lost gps signal or not for a tracking record - */ - public boolean isLostGps(){ -// if(pref!=null){ -// lastOfftime =lastOfftime>0?lastOfftime: pref.getLong(QiYouConstant.PK_LAST_OFFTIME, 0); -//// lastLocationTime = lastLocationTime>0?lastLocationTime: pref.getLong("lastLocationTime", 0); -// } -// lastLocationTime =lastLocation!=null?lastLocation.getTime():lastLocationTime; - lastLocationTime=lastLocationTime >0?lastLocationTime: - lastLocation!=null?lastLocation.getTime():0; - -// QLog.getLogger().dLog( TAG, " isLostGps(), System.currentTimeMillis() - app.lastLocationTime:" + String.valueOf(System.currentTimeMillis() - lastLocationTime ) + -// ",MAX_GPS_OFF_TIME*3 is "+ QiYouConstant.MAX_GPS_OFF_TIME*3 +",lastOfftime:" +lastOfftime); - - - - return lastOfftime > 0 - || System.currentTimeMillis()-lastLocationTime > QiYouConstant.MAX_GPS_OFF_TIME*3; //no gps or speed is zeo for long time - } - - public boolean isNotMoving(){ - - /* if(lastSavedLocation!=null) - QLog.getLogger().dLog( TAG," check if it isNotMoving(), System.currentTimeMillis() - app.lastSavedLocation:" - + String.valueOf(System.currentTimeMillis() - lastSavedLocation.getTime() ) + - ",get_updatedb_invterval is "+ Utils.get_updatedb_invterval(TrackType.valueOf(getLastTracktype()) ));*/ - boolean isNotMoving = - lastSavedLocation!=null &&(System.currentTimeMillis() - lastSavedLocation.getTime()) - >Utils.get_updatedb_invterval(TrackType.valueOf(getLastTracktype()))*2; - - if(isNotMoving){ -/* if((GPS_SPAN_FACTOR+1)*QiYouConstant.MAX_GPS_SPAN<30*1000) //gps interval should small than 1 minute. //changed to 20 seconds 2015.06.26 -// if((GPS_SPAN_FACTOR+1)*QiYouConstant.MAX_GPS_SPAN<10*1000) - GPS_SPAN_FACTOR++;*/ - // QLog.getLogger().dLog(dTAG, TAG + " >>>>>>>>>>>>>>>>>it is not moving..............................."); - - GPS_SPAN_FACTOR++; - - if(isLostGps()){ - - if((GPS_SPAN_FACTOR+1)*QiYouConstant.MAX_GPS_SPAN>20*1000){ - GPS_SPAN_FACTOR=1; - } - - }else{ - - if((GPS_SPAN_FACTOR+1)*QiYouConstant.MAX_GPS_SPAN>8*1000){ - GPS_SPAN_FACTOR=1; - } - } - /* - if((GPS_SPAN_FACTOR+1)*QiYouConstant.MAX_GPS_SPAN>15*1000){ - GPS_SPAN_FACTOR=1; - }*/ - }else{ - GPS_SPAN_FACTOR=1; - } - - // QLog.getLogger().dLog( TAG , " TimtickService GPS_SPAN_FACTOR*gps_span is "+GPS_SPAN_FACTOR*QiYouConstant.MAX_GPS_SPAN ); - - return isNotMoving; - - } - - -// public ConcurrentHashMap getTrackCache() { -// if (tracks_cached == null) tracks_cached = new ConcurrentHashMap(); -// return tracks_cached; -// } - - - public TrackCache getTrackCache() { - return trackCache; -} - - /*public void initMapview(Activity activity){ - mMapview =new MapView(activity); - - }*/ -// -// public HashMap getTrackCache() { -// if (tracks_cached == null) tracks_cached = new HashMap(); -// return tracks_cached; -// } - - - // trackId,wpsJson - - public ConcurrentHashMap getTrackJsoncache() { - if(tracks_json_cached == null) tracks_json_cached = new ConcurrentHashMap(); - return tracks_json_cached; - } - public Track getRecordingTrack() { - if(null == recordingTrack) recordingTrack = new Track(); - return recordingTrack; - } - - public void setRecordingTrack(Track recordingTrack) { - this.recordingTrack = recordingTrack; - } - - public Track getGpxTrack() { - if(null == gpxTrack){ - gpxTrack = new Track(); - gpxTrack.getTrackBean().setType(TrackType.GPX); - } - - return gpxTrack; - } - - public void setGpxTrack(Track track) { - gpxTrack = track; - } - public ArrayList getImportedGpx() { - if(importedGpx==null)importedGpx =new ArrayList(); - return importedGpx; - } - public void initialImportedGpx() { - importedGpx =new ArrayList(); - } - - public ArrayList getImportedGpxFileList(){ - - TypeStatistics st = getTracksStat(TrackType.GPX.toInt(),0,0); - ArrayList srcs = new ArrayList(); - ConcurrentHashMap sbs =st.getSbs(); - for(Integer key :sbs.keySet()) { - if(!srcs.contains(sbs.get(key).getSrc())) - srcs.add(sbs.get(key).getSrc()); - // QLog.getLogger().d(TAG," get imported SRC list:" +sbs.get(key).getSrc()); - } - return srcs; - } - -// public boolean impGpx(String gpxfileName){ - public boolean impGpx(){ - -/* importedGpx =getImportedGpx(); -// importedGpx =new ArrayList();// initial the imported list for each import. so that the list contains the latest imported gpx tracks. - importedGpx.add(Track.newInstance(gpxfileName)); */ - - if (importedGpx.size()==0) return false; - - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.NEW_GPX_TRACK,""); - startService(serviceIntent); - return true; - } - - -// public Track getCopyTrack() { -// if(null == copyTrack) copyTrack = new Track(); -// return copyTrack; -// } -// public void setCopyTrack(Track copyTrack) { -// this.copyTrack = copyTrack; -// } - public ConcurrentHashMap getLocationCached() { - if(location_cached == null) location_cached = new ConcurrentHashMap(); - return location_cached; - } - public void setLocationCached(ConcurrentHashMap location_cached) { - this.location_cached = location_cached; - } - - - public void GPSwarmup() - { - Intent testIntent = new Intent("testAction"); - PendingIntent testpIntent = PendingIntent.getBroadcast(this, 0, testIntent, PendingIntent.FLAG_UPDATE_CURRENT); - if(lm==null){ - lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); - } - //lm.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListenerPendingIntent) ; - lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, testpIntent); -// lm.requestSingleUpdate(LocationManager.GPS_PROVIDER, testpIntent); -// lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,0, locationListenerPendingIntent); - lm.removeUpdates(testpIntent); -// QLog.getLogger().d(dTAG,TAG+" "+ "ggGPSwarmup."); - - } - - - - public void startAndroidGPSRequest() - { -/* if(getRecordingTrack().getTrackBean().getStatus() == QiYouConstant.TRACK_STATUS_PAUSED) return; - - startNetworkLocationRequest(false);//先开启网络定位,收到gps信号后姜自动关闭网络定位 - -// if(!getGpsState(this)); -// { -// //TODO: let user to toggle the GPS on. -// } - if(lm==null)lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); -// canRecord =true; - lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, QiYouConstant.MAX_GPS_SPAN*GPS_SPAN_FACTOR,0, locationListenerPendingIntent); - isGPSstopped =false; - lastGpsStopTime=0; - lastGpsStartTime = System.currentTimeMillis(); - QLog.getLogger().d(dTAG,TAG+" TimtickService startAndroidGPSRequest"); */ - - - if(getRecordingTrack().getTrackBean().getStatus() == TrackStatus.PAUSED) return; - String key = QiYouConstant.EXTRA_KEY_START_GPS; - Intent serviceIntent = new Intent(this, TimtickService.class); - serviceIntent.putExtra(key, true); - startService(serviceIntent); - } - - - public void stopAndroidGPSRequest(){ - -/* if(lm!=null){ - lm.removeUpdates(locationListenerPendingIntent); -// Log.i(dTAG,TAG + " stopped gps request "); - } - isGPSstopped =true; - lastGpsStartTime =0; - lastGpsStopTime =System.currentTimeMillis(); -// this.canRecord =!this.playBack; - if(!canRecord())cancelForceDbAlarm(); - QLog.getLogger().d(dTAG,TAG+" TimtickService stopAndroidGPSRequest"); - */ - - String key = QiYouConstant.EXTRA_KEY_STOP_GPS; - Intent serviceIntent = new Intent(this, TimtickService.class); - serviceIntent.putExtra(key, true); - startService(serviceIntent); - } - - public boolean canRecord(){ - - boolean canrec =this.getRecordingTrack().getTrackBean().getStatus() == TrackStatus.RECORDING; - canrec = canrec || getRecordingTrack().getTrackBean().getStatus() == TrackStatus.PAUSED; - canrec =canrec && !playBack ; - canrec = canrec -// && this.getRecordingTrack().getTrackBean().getType()!=QiYouConstant.TRACK_TYPE_COPY; - && getRecordingTrack().getTrackBean().getType()!=TrackType.COPY; - -// canrec = canrec || QiYouConstant.PLAYBACK_CAN_RECORD; -// canrec = canrec || QiYouConstant.DEVELOPER_MODE; -// canrec = canrec && isLastTrackExist(); - return canrec; - } - - public boolean canExit(){ - - return recordingTrack ==null || recordingTrack.getTrackBean().getStatus()!= TrackStatus.RECORDING - ||recordingTrack.getTrackBean().getType() ==TrackType.COPY; - - } - - AlarmManager locationAm; - PendingIntent amSender; - public void forceDbUpdate(boolean isOneRequest){ - // Intent amIntent =new Intent( this, LocationService.class); - Intent amIntent = new Intent(QiYouConstant.ACTION_NEW_FORCE_UPDATE); -// amIntent.setClassName("com.qiyou.mb.android.receivers", LocationChangesReceiver.class.getName()); - // intent.setAction("repeating"); - amIntent.putExtra(QiYouConstant.EXTRA_KEY_FORCE_UPDATE, true); - amSender=PendingIntent.getBroadcast( this, 0,amIntent, PendingIntent.FLAG_UPDATE_CURRENT); - //开始时间 - long firstime=SystemClock.elapsedRealtime(); - - -// if(locationAm ==null) -// locationAm=(AlarmManager)getSystemService(ALARM_SERVICE);//60秒一个周期,不停的发送广播 -// else locationAm.cancel(amSender); - locationAm.cancel(amSender); - -// locationAm.setRepeating( AlarmManager.RTC_WAKEUP,System.currentTimeMillis() +QiYouConstant.MAX_TIME_FORCE_UDATE, QiYouConstant.MAX_TIME_FORCE_UDATE, amSender); -// locationAm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP , firstime+QiYouConstant.MAX_TIME_FORCE_UDATE, QiYouConstant.MAX_TIME_FORCE_UDATE, amSender); - locationAm.setRepeating(AlarmManager.RTC_WAKEUP , firstime+QiYouConstant.MAX_TIME_FORCE_UDATE, QiYouConstant.MAX_TIME_FORCE_UDATE, amSender); -// locationAm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP , firstime+5000, 30*1000, amSender);\ -// QLog.getLogger().d(dTAG,TAG + String.format(" interval is %d, next time the forceupdate will be triggered is ",QiYouConstant.MAX_TIME_FORCE_UDATE)+ Utils.getTimeCnt((long) QiYouConstant.MAX_TIME_FORCE_UDATE , true) ); - // QLog.getLogger().dLog(TAG, " forceDbUpdate(), started, frequence is" +QiYouConstant.MAX_TIME_FORCE_UDATE); -// QLog.getLogger().d("Force_update", TAG + " forceDbUpdate(), started."); - if(isOneRequest) { - isOneRequestForceUpdate = isOneRequest; - cancelForceDbAlarm();//locationAm.cancel(amSender); - } - - } - - public void cancelForceDbAlarm() - { - if(locationAm!=null && amSender!=null) - locationAm.cancel(amSender); -// QLog.getLogger().d(dTAG,TAG+" "+ "cancelForceDbAlarm(), cancelled."); - QLog.getLogger().dLog( TAG , " cancelForceDbAlarm(), cancelled."); - } - - - - /* - * - * @param context - * @return true if enabled. - */ -// private boolean getGpsState(Context context) { -// return lm.isProviderEnabled(LocationManager.GPS_PROVIDER); -// } - - /** - * Toggles the state of GPS. - * - * @param - */ -// private void toggleGps(Context context) { -// ContentResolver resolver = context.getContentResolver(); -// boolean enabled = getGpsState(context); -// Settings.Secure.putInt(resolver, LocationManager.GPS_PROVIDER,1 ) ; -// } - - public ArrayList getEles() { - if(eles ==null) eles = new ArrayList(); - return eles; - } - -public void initialPlayBack(Integer trackId){ - playBack =true; - playBackStopped =false; - if(QiYouConstant.PLAYBACK_CAN_RECORD){ - unregTimeTick(); - stopAndroidGPSRequest(); - } - - int currentId = currentTrack ==null?0:currentTrack.getTrackBean().getTrackId(); - - if(currentId >0 && currentId != trackId){ - /*if( !tracks_cached.containsKey(trackId) || - tracks_cached.get(trackId).getTrackBean().getLastdbTime() - < currentTrack.getTrackBean().getLastdbTime() - ){ - tracks_cached.put(currentId, currentTrack); - }*/ - Track tr=trackCache.get(Integer.valueOf(trackId)); - if( tr==null|| - tr.getTrackBean().getLastdbTime() - < currentTrack.getTrackBean().getLastdbTime() - ){ - trackCache.put(currentId, currentTrack); - } - - this.currentTrack =null; //current track is not the playback one, then set it to null. - } - - startPlayBackService(trackId); - - - } -public void startPlayBackService(Integer trackId) -{ - Intent serviceIntent; - if(currentTrack == null){ - serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID, trackId); - startService(serviceIntent); - } - - serviceIntent = new Intent(this, TrackPlaybackService.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID, trackId); - startService(serviceIntent); - playBackTrackId = trackId ; - // QLog.getLogger().d(dTAG,TAG+" "+ " playBackTrackId,trackId "+ trackId ); -} - - -public void getTrackById(Integer id){ - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_TRACK_BY_ID, id); - startService(serviceIntent); -} - -public void initialTrackParameters(){ - -// playBack=false; -// QLog.getLogger().dLog(dTAG,TAG+" "+ "initialTrackParameters(), isPlayback: " + playBack ); - lastEle=88888f; -// currentTrackId - eles.clear(); - lastSharedTime =0; - lastOfftime =0; - lastPaused=0; - sumDist=0; - sumNavDist=0; -// sumDist2=0; - offtime=0; - sumPaused=0; - sumOfftimeWp =0; - minTime=0; - locDist=0; - SpDist=0; - lastLocation =null; - lastBearLoc =null; - lastSavedLocation=null; - sumBear=0; -// sumDiff2=0; -// sumDiff=0; - cntBear=0; -// setCntKm(0); - timeKm=0; - bearDist=0; - lastSumbear=0; - lastGpsStartTime=0; - lastGpsStopTime=0; - bearLocs.clear(); - sumBearLocs.clear(); - targetBear=0f; - cntBeared =0; - getLocationCached().clear(); - lastLocationTime=0; - gpsStartTime=0; - - pe.putLong(QiYouConstant.PK_LONG_TRACK_MANULE_PAUSED, 0); //总计手动暂停时长 - pe.putLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, 0); //上次手动暂停时间戳 - pe.commit(); - toDecideLocations=null; -// saveLocationParameters(true); - - maxEle=QiYouConstant.MAX_ELE*-1; - minEle=QiYouConstant.MAX_ELE ; - upDist=0; - downDist=0; - -} -/* - * isUpdate: true-->from pause to tracking - */ -public long getPausedTime(boolean isUpdate){ - if(isUpdate){ - updatePauseParameters(); - } - - long sumPaused =pref.getLong(QiYouConstant.PK_LONG_TRACK_MANULE_PAUSED, 0); -// QLog.getLogger().dLog(dTAG, TAG+" get totalTime,sumPaused: "+sumPaused+","+Utils.getFormatedTime(sumPaused) ); - - - return sumPaused; - -} -/* - * - * isNewPause - * true: start new pause. - * false: update pause starttime to now, and update the sum time of last paused period - */ -public void updatePauseParameters(){ - - if(recordingTrack.getTrackBean().getTrackId()==0)return; -// QLog.getLogger().dLog(dTAG, TAG+" get totalTime,sumPaused: "+sumPaused+","+Utils.getFormatedTime(sumPaused) ); - restartPause(); -/* - long lastPaused =pref.getLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, 0);//last time paused. - -/* if(isNewPause){ - pe.putLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, System.currentTimeMillis()); //上次手动暂停时间戳 - - }else{ - -// if(lastPaused==0){ -// pe.putLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, System.currentTimeMillis()); -// }else{ -// long sumPaused=getPausedTime(false)+System.currentTimeMillis() -lastPaused; -// pe.putLong(QiYouConstant.PK_LONG_TRACK_MANULE_PAUSED, sumPaused); -// } - - if(lastPaused>0){ - long sumPaused=getPausedTime(false)+System.currentTimeMillis() -lastPaused; - pe.putLong(QiYouConstant.PK_LONG_TRACK_MANULE_PAUSED, sumPaused); - } - pe.putLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, System.currentTimeMillis()); - - }*/ - - /*if(lastPaused>0){ - long sumPaused=getPausedTime(false)+System.currentTimeMillis() -lastPaused; - pe.putLong(QiYouConstant.PK_LONG_TRACK_MANULE_PAUSED, sumPaused); - } - pe.putLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, System.currentTimeMillis()); - pe.commit();*/ -} - -/* - * from a pause to a new pause. - */ -public void restartPause(){ -// getPausedTime(false); - long lastPaused =pref.getLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, 0); - if(lastPaused>0){ - long sumPaused=getPausedTime(false)+System.currentTimeMillis() -lastPaused; - pe.putLong(QiYouConstant.PK_LONG_TRACK_MANULE_PAUSED, sumPaused); - } - pe.putLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED, System.currentTimeMillis()); - pe.commit(); - -} - - -public void continueTrack(TrackType trackType){ - new Thread(){ - - @Override - public void run() { - - initialTrackParameters(); //lastLocation is going to be set null. - - if(recordingTrack.getTrackBean().getEndTime()>0){ //for recording UI total time,the time between last end and the continue time will be treated as Manual Pausing time. - pe.putLong(QiYouConstant.PK_LONG_LAST_MANULE_PAUSED,recordingTrack.getTrackBean().getEndTime()); - pe.commit(); - updatePauseParameters(); - } -// setRecordingTrack(currentTrack); -// recordingTrack.getTrackBean().setStatus(QiYouConstant.TRACK_STATUS_TRACKING); - updateTrackStatus(recordingTrack.getTrackBean().getTrackId(),QiYouConstant.TRACK_STATUS_TRACKING); - // if(!playBack)this.canRecord=true; - if(!playBack)startAndroidGPSRequest(); - playBack=false; - setLastRecordingIdStartTime(); - - Location loc= lastLocation; - Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, loc); - // broadcastIntent.putExtra(QiYouConstant.EXTRA_KEY_NO_LOCCATION_SIGNAL, true); - sendBroadcast(broadcastIntent); - regTimeTick(); - - //update the ui to reflect new track - - }}.start(); - -} - - - -public void initialNewTrack(final TrackType trackType){ - QiYouConstant.CAN_SPEAK = true; -new Thread(){ - - @Override - public void run() { - setLastRecordingIdStartTime(); - initialTrackParameters(); //lastLocation is going to be set null. -// setRecordingTrack(new Track()); - getRecordingTrack().startNewTrack(trackType); - // if(!playBack)this.canRecord=true; -// if(!playBack) - startAndroidGPSRequest(); - playBack=trackType==TrackType.COPY; - - - Location loc= lastLocation; - Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, loc); - // broadcastIntent.putExtra(QiYouConstant.EXTRA_KEY_NO_LOCCATION_SIGNAL, true); - sendBroadcast(broadcastIntent); -// regTimeTick(); - - //update the ui to reflect new track - - }}.start(); - } - -/* - *read parameters that updated during the recording. - * This is in case the application exits and recreating, unpredicted. - */ -public void initialLocationParameters() -{/* - if(lastPaused > QiYouConstant.PV_LONG_LAST_START || lastOfftime >QiYouConstant.PV_LONG_LAST_START) return; - sumPaused = pref.getLong(QiYouConstant.PK_LONG_SUM_PAUSE, 0); -// sumOfftime = pref.getLong(QiYouConstant.PK_LONG_SUM_OFFTIME, 0);//offtime only apply to forceupdate. need not persist. - lastOfftime = pref.getLong(QiYouConstant.PK_LAST_OFFTIME, 0); - lastGpsStartTime =pref.getLong("lastGpsStartTime", 0); - lastGpsStopTime =pref.getLong("lastGpsStopTime", 0); -// gpsStartTime =pref.getLong("gpsStartTime", 0); - lastLocationTime =pref.getLong("lastLocationTime", 0); - lastPaused= pref.getLong(QiYouConstant.PK_LAST_PAUSED, 0); - sumDist= pref.getFloat(QiYouConstant.PK_LONG_SUMDIST, 0); - sumOfftimeWp = pref.getLong(QiYouConstant.PK_LONG_SUM_OFFTIMEWP, 0); - minTime = pref.getLong(QiYouConstant.PK_LONG_MINTIME, 0); - locDist= pref.getFloat(QiYouConstant.PK_FLOAT_LOCDIST, 0); - SpDist= pref.getFloat(QiYouConstant.PK_FLOAT_SPDIST, 0); - cntKm= pref.getInt("cntKm", 0); - sumBear= pref.getFloat("sumBear", 0); - sumBear2= pref.getFloat("sumBear2", 0); - cntBear= pref.getInt("cntBear", 0); -// cntBeared= pref.getInt("cntBeared", 0); - targetBear= pref.getFloat("targetBear", 0); - - - -// QLog.getLogger().d(dTAG, "Read Location Parameters."); -// QLog.getLogger().d(TAG," read app.sumPause: "+ sumPaused ); -*/} -/* - * persist the parameters that updated during the recording. - * This is in case the application exits and recreating, unpredicted. - */ -/* - * newTrack, indicate when it is a new track, clear all the parameters. - */ -public void saveLocationParameters(Boolean newTrack) -{ /* - if(!newTrack) - if( recordingTrack==null || recordingTrack.getTrackBean().getStatus()!=QiYouConstant.TRACK_STATUS_TRACKING -// || sumPaused+sumOfftime+sumOfftimeWp+lastOfftime+lastPaused+sumDist ==0 - ) return; - // -// if(!newTrack|| recordingTrack==null || recordingTrack.getTrackBean().getStatus()!=QiYouConstant.TRACK_STATUS_TRACKING -//// || sumPaused+sumOfftime+sumOfftimeWp+lastOfftime+lastPaused+sumDist ==0 -// ) return; -// QLog.getLogger().d(dTAG, TAG+" save app tracking paramentes: "+ sumPaused+sumOfftime+sumOfftimeWp+lastOfftime+lastPaused+sumDist ); - - pe.putLong(QiYouConstant.PK_LONG_SUM_PAUSE, sumPaused); -// pe.putLong(QiYouConstant.PK_LONG_SUM_OFFTIME, offtime); //offtime only apply to forceupdate. need not persist. - pe.putLong(QiYouConstant.PK_LONG_SUM_OFFTIMEWP, sumOfftimeWp); - pe.putLong(QiYouConstant.PK_LAST_OFFTIME, lastOfftime); - pe.putLong(QiYouConstant.PK_LAST_PAUSED, lastPaused); - pe.putFloat(QiYouConstant.PK_LONG_SUMDIST, sumDist); - pe.putLong(QiYouConstant.PK_LONG_MINTIME, minTime); - pe.putFloat(QiYouConstant.PK_FLOAT_LOCDIST, locDist); - pe.putFloat(QiYouConstant.PK_FLOAT_SPDIST, SpDist); - pe.putInt("cntKm", cntKm); - pe.putLong("lastGpsStartTime", lastGpsStartTime); - pe.putLong("lastGpsStopTime", lastGpsStopTime); -// pe.putLong("gpsStartTime", gpsStartTime); - if(lastLocation!=null)pe.putLong("lastLocationTime", lastLocation.getTime()); - pe.putFloat("sumBear", sumBear); - pe.putFloat("sumBear2", sumBear2); - pe.putInt("cntBear", cntBear); - pe.putInt("cntBeared", cntBeared); - pe.putFloat("targetBear", targetBear); - - pe.commit(); -// pe.apply(); - -// QLog.getLogger().d(dTAG, "saved Location Parameters."); - */ -} - -public int getExistTrackingID(){ - return settings.getInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,-1); -} -public boolean isLastTrackExist(){ -// -// int id =getExistTrackingID(); -// long lastStart =settings.getLong(QiYouConstant.PK_LONG_LAST_TRACK_START,0); -// -// QLog.getLogger().dLog(dTAG, String.format("%s,last track id is %s, last track time is %s",TAG, id,lastStart)); - - return settings.getInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,-1)>0 - || settings.getLong(QiYouConstant.PK_LONG_LAST_TRACK_START,0)> 0; -} -public boolean isRestoreLastTracking =false; -public void restoreLastTracking() -{ -// ggGPSwarmup(); - final int id =settings.getInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,-1); - QLog.getLogger().dLog(TAG, "restoreLastTracking(),start to restore track of id "+ id ); - if(id<=0 ){ - - if(settings.getLong(QiYouConstant.PK_LONG_LAST_TRACK_START,0)>0){ //just start, not get gps yet,no trackId yet -// this.initialNewTrack(QiYouConstant.TRACK_TYPE_BIKE); - this.initialNewTrack(TrackType.BIKE);//track type may need to store in pref.//TODO:rewiew - QLog.getLogger().dLog(TAG, "restoreLastTracking(),by initialNewTrack" ); - } - return; - }else - if(currentTrack!=null && currentTrack.getTrackBean().getTrackId()==id){//TODO: review currentTrack.... - this.recordingTrack=currentTrack; - QLog.getLogger().dLog(TAG,"restoreLastTracking(),set recordingTrack to currentTrack "+ id +",track status is "+recordingTrack.getTrackBean().getStatus() ); - return; - } - - - QLog.getLogger().dLog(TAG, "restoreLastTracking(),2 start to restore track of id "+ id ); - if(id >0 ){ - isRestoreLastTracking =true; - getTrack(id) ; - currentTrackId = -11; - this.startAndroidGPSRequest(); - - if(getExistNaviTrackID() ==id && isLastNaviExist() && !playBack){ //last recording track is in naving, restore navi too. - isRestoreNavi=true; - isNaving=true; - restoreNaviService(getExistNaviID()); - } - -// new Handler().post(new Runnable () { -// public void run() { - final Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); -// broadcastIntent.putExtra(QiYouConstant.EXTRA_KEY_NO_LOCCATION_SIGNAL, true); - new Thread(){ - @Override - public void run() { - long topWaiting=0; - // while(currentTrackId==-11){ - while(currentTrackId!=id){ - try { - Thread.sleep(50); - topWaiting+=50; - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB) - { - QLog.getLogger().dLog(TAG, " restoreLastTracking(),Get track with id" + id +" over time limit, Waiting = "+topWaiting); - break; - // Toast toast= Toast.makeText(this, "Get track with id" + id +" over time limit.", Toast.LENGTH_LONG ); - // toast.show(); - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - - - - isRestoreLastTracking =false; - - if(currentTrackId ==id) { - // if(getRecordingTrack().getTrackBean().getStatus()==QiYouConstant.TRACK_STATUS_TRACKING && recordingTrack.getTrackBean().getTrackId()==0) - if(recordingTrack.getTrackBean().getTrackId()==0) - { - recordingTrack= currentTrack; - forceDbUpdate(false); - - //send notice to UI. - sendBroadcast(broadcastIntent); - - // QLog.getLogger().dLog(TAG ," restoreLastTracking(), id "+ id +" Restored, track Status is " +getRecordingTrack().getTrackBean().getStatus()); - // Log.d(dTAG,TAG+" Send restore track information to update UI."); - } - } - else{//failed to restore, check current recording track - // setRecordingTrack(new Track()); - if( recordingTrack ==null || recordingTrack.getTrackBean().getTrackId()==0) - // getRecordingTrack().startNewTrack(QiYouConstant.TRACK_TYPE_BIKE); - getRecordingTrack().startNewTrack(TrackType.BIKE);//TODO: review bike as default or use pref. - QLog.getLogger().dLog(dTAG,TAG+" "+ "restoreLastTracking(), id "+ id +" not Restored, start new track"); - } - - - if( recordingTrack!=null && TrackStatus.FINISHED == recordingTrack.getTrackBean().getStatus()){ - recordingTrack.getTrackBean().setStatus(TrackStatus.RECORDING); - } - - - isRestoreLastTracking =false; - // }}); - }}.start(); - // }}; - - -// Toast toast= Toast.makeText(this, " Incomplete track " + id +" Restored "+TAG, Toast.LENGTH_LONG ); -// toast.show(); - } - - -} - -public boolean isRestoreNavi; - - void restoreNaviService(final int naviId){ - - final Intent serviceIntent = new Intent(this, QNaviSvc.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_START_NAVI, 0); - stopService(serviceIntent); - -// lastStartDialog=!isContinue; //start new navi should not show dialog - - final Handler handler = new Handler(){ - @Override - public void handleMessage(Message msg) { - if (msg.what==10) { - naviTrackId=naviId; //TODO:this need current navi stopped. - startService(serviceIntent); - } - }}; - if(!TextUtils.isEmpty(isLastNaviWeb())){ - - try { - this.setCurrentTrack(Utils.getTrackFromWebCache(isLastNaviWeb())); - getTrackCache().put(naviId,currentTrack); - } catch (JsonSyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - handler.sendEmptyMessage(10); - return; - } - - - new Thread(){ - - @Override - public void run() { - - - - while(isRestoreLastTracking){ - try { - Thread.sleep(100); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - getTrack(naviId) ; - - int topWaiting=0; - while(currentTrackId!=naviId){ - try { - Thread.sleep(100); - topWaiting+=100; - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB) - { - QLog.getLogger().dLog(TAG, " restoreNaviService(),Get track with id" + naviId +" over time limit, Waiting = "+topWaiting); - break; -// Toast toast= Toast.makeText(this, "Get track with id" + id +" over time limit.", Toast.LENGTH_LONG ); -// toast.show(); - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - - if(currentTrackId==naviId) - handler.sendEmptyMessage(10); - - - }}.start(); -} - - -//TODO: try AsyncTask -public int currentTrackId =0; -public void getTrack(final int trackID){ - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID, trackID); - startService(serviceIntent); -// QLog.getLogger().d(dTAG,TAG+" "+ "getTrack result。 currentTrackId==trackID ? "+ currentTrackId+ "=="+ trackID); -} - -/*void showAnimate(long time,int trackID) -{ - //TODO: SHOW ANIMATE GIF FOR WAITING 1 SEC. - long topWaiting=0; - while(topWaiting<=time && currentTrackId !=trackID) - { - try { - Thread.sleep(50); - topWaiting+=50; - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } -}*/ -public void updateTrackStatus( int status){ - updateTrackStatus(0, status);//0: update recordingTrack,else update current track -} - -public void updateTrackStatus(int id, int status) -{ -// if(null != getCurrentTrack()) getTrackCache().put( getCurrentTrack().getTrackBean().getTrackId(), getCurrentTrack()); -// setCurrentTrack( getRecordingTrack()); - QLog.getLogger().d(dTAG,TAG+" start to update track " + id +" to status " + status); - - -// if(id ==0 && recordingTrack!=null )//&& recordingTrack.getTrackBean().getTrackId()>0) - if( recordingTrack!=null &&(id==0 || id ==recordingTrack.getTrackBean().getTrackId()) )//&& recordingTrack.getTrackBean().getTrackId()>0) - recordingTrack.getTrackBean().setStatus(TrackStatus.valueOf(status)); - else if(id > 0 && currentTrack!=null && currentTrack.getTrackBean().getTrackId() ==id) - currentTrack.getTrackBean().setStatus(TrackStatus.valueOf(status)); - else return; - - if( this.getRecordingTrack().getTrackBean().getTrackId() == id){ - setLastRecordingIdStartTime(); //id may eq -1, thats okay to persist the -1 as none recording track exist. - } - - - this.forceDbUpdate(true); - try{ - if(status == QiYouConstant.TRACK_STATUS_TRACKING){ -// setLastRecordingIdStartTime(); -// canRecord=true; -// if(isGPSstopped) startAndroidGPSRequest(); //TODO: review when to startgsprequest - startAndroidGPSRequest(); - regTimeTick(); - } - - else - { -// canRecord =false; - stopAndroidGPSRequest(); - unregTimeTick(); - } - - - - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - if(id ==0 || recordingTrack!=null && recordingTrack.getTrackBean().getTrackId()>0 ) - serviceIntent.putExtra(QiYouConstant.UPDATE_RECORDING_TRACK, recordingTrack.getTrackBean().getTrackId()); - else{ //finish recording. - -// if(System.currentTimeMillis()>currentTrack.getTrackBean().getEndTime()){ -// currentTrack.getTrackBean().setEndTime(System.currentTimeMillis()); -// } - serviceIntent.putExtra(QiYouConstant.EXTR_KEY_FINISH_RECORDING, currentTrack.getTrackBean().getTrackId()); - } - startService(serviceIntent); - - - //keep the lat lon as the last location. - - }catch(Exception e) - { - Log.d(dTAG,TAG+" "+ "wrong on update the new track status to " + status); - Utils.logStackTrace(e, dTAG); - } - - -} -public void getPreferences(){ - - readUser(); -// QiYouConstant.PV_USER_ID=settings.getInt(QiYouConstant.PK_INT_USER_ID, QiYouConstant.PV_USER_ID); -// QiYouConstant.PV_USER_PASSWD=settings.getString(QiYouConstant.PK_STR_USER_PASSWD, QiYouConstant.PV_USER_PASSWD); -// QiYouConstant.PV_USER_ACCOUNT = settings.getString(QiYouConstant.PK_STR_USER_ACCOUNT, QiYouConstant.PV_USER_ACCOUNT); -// QiYouConstant.PV_USER_NAME = settings.getString(QiYouConstant.PK_STR_USER_NAME, QiYouConstant.PV_USER_NAME); -// QiYouConstant.PV_USER_EMAIL=settings.getString(QiYouConstant.PK_STR_USER_EMAIL, QiYouConstant.PV_USER_EMAIL); - QiYouConstant.PV_USER_WEIGHT = Float.valueOf(settings.getString(QiYouConstant.PK_FLOAT_USER_WEIGHT, "60")); - - - QLog.getLogger().d(dTAG, TAG+ " before prefloading QiYouConstant.PV_BL_PLAYBACK_PAUSE_WITH_UI: "+QiYouConstant.PV_BL_PLAYBACK_PAUSE_WITH_UI ); - - QiYouConstant.PV_BL_PLAYBACK_PAUSE_WITH_UI = Boolean.valueOf(settings.getBoolean(QiYouConstant.PK_BL_PLAYBACK_RECORD_SCREEN_OFF, QiYouConstant.PV_BL_PLAYBACK_PAUSE_WITH_UI)); - QLog.getLogger().d(dTAG, TAG+ " prefloading QiYouConstant.PV_BL_PLAYBACK_PAUSE_WITH_UI: "+QiYouConstant.PV_BL_PLAYBACK_PAUSE_WITH_UI ); - - QiYouConstant.PV_BL_SAVE_POWER = Boolean.valueOf(settings.getBoolean(QiYouConstant.PK_BL_SAVE_POWER, QiYouConstant.PV_BL_SAVE_POWER)); - QLog.getLogger().d(dTAG, TAG+ " prefloading QiYouConstant.PV_BL_SAVE_POWER: "+QiYouConstant.PV_BL_SAVE_POWER ); - - QiYouConstant.PV_BL_SHARE_LOCATION = Boolean.valueOf(settings.getBoolean(QiYouConstant.PK_BL_SHARE_LOCATION, QiYouConstant.PV_BL_SHARE_LOCATION)); - - - QiYouConstant.PV_STR_SHARE_MSG = settings.getString(QiYouConstant.PK_STR_SHARE_MSG, QiYouConstant.PV_STR_SHARE_MSG); -// QiYouConstant.PV_LG_SHARE_INTERVAL = settings.getLong(QiYouConstant.PK_LG_SHARE_INTERVAL, QiYouConstant.PV_LG_SHARE_INTERVAL); - QiYouConstant.PV_LAST_BBS_CATE = settings.getString(QiYouConstant.PK_LAST_BBS_CATE, ""); - -// QiYouConstant.BL_SPEAK_KM = settings.getBoolean(QiYouConstant.PK_BL_SPEAK_KM, true) ; - QiYouConstant.PV_APP_CNT =settings.getInt(QiYouConstant.PK_INT_APP_CNT, 0); - QiYouConstant.PV_LONG_LAST_QUIT =settings.getLong(QiYouConstant.PK_LONG_LAST_QUIT, 0); - QiYouConstant.PV_LONG_LAST_START =settings.getLong(QiYouConstant.PK_LONG_LAST_START, 0); - - QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT =settings.getInt(QiYouConstant.PK_INT_MAX_WPS_EVERAGE_ELE_CNT, QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT); -// QiYouConstant.PLAYBACK_CAN_RECORD = settings.getBoolean(QiYouConstant.PK_BL_PLAYBACK_CAN_RECORD, false); -// QiYouConstant.PLAYBACK_CAN_RECORD = new Boolean(settings.getBoolean(QiYouConstant.PK_BL_PLAYBACK_CAN_RECORD, false)); - QiYouConstant.WPS_SAVE_ALL = settings.getBoolean(QiYouConstant.PK_BL_WPS_SAVE_ALL, false) ; -// QiYouConstant.WPS_SAVE_ALL = new Boolean(settings.getBoolean(QiYouConstant.PK_BL_WPS_SAVE_ALL, false)); - -// QiYouConstant.PLAYBACK_CAN_RECORD = Boolean.valueOf(settings.getString(QiYouConstant.PK_BL_PLAYBACK_CAN_RECORD, "false")); -// QiYouConstant.PLAYBACK_CAN_RECORD = (Boolean) settings.getAll().get(QiYouConstant.PK_BL_PLAYBACK_CAN_RECORD ); - - -// QiYouConstant.MAX_GPS_SPAN =settings.getInt(QiYouConstant.PK_INT_GPS_SPAN, QiYouConstant.MAX_GPS_SPAN ); - int span =Integer.valueOf(settings.getString(QiYouConstant.PK_INT_GPS_SPAN, String.valueOf(QiYouConstant.MAX_GPS_SPAN ))); - span =span >1000?span:2000; - QiYouConstant.MAX_GPS_SPAN =span; - - int speakModel =Integer.valueOf(settings.getString(QiYouConstant.PK_INT_SPORTS_SPEAK_MODEL, String.valueOf(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL ))); - QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL=speakModel; - - speakModel =Integer.valueOf(settings.getString(QiYouConstant.PK_INT_NAVI_SPEAK_MODEL, String.valueOf(QiYouConstant.PV_INT_NAVI_SPEAK_MODEL ))); - QiYouConstant.PV_INT_NAVI_SPEAK_MODEL=speakModel; - - -// QiYouConstant.PLAYBACK_TIME_INTERVAL =settings.getInt(QiYouConstant.PK_INT_PLAYBACK_TIME_INTERVAL, QiYouConstant.PLAYBACK_TIME_INTERVAL); -// QiYouConstant.PLAYBACK_TIME_INTERVAL = Integer.valueOf(settings.getString(QiYouConstant.PK_INT_PLAYBACK_TIME_INTERVAL, String.valueOf(QiYouConstant.PLAYBACK_TIME_INTERVAL ))); - QiYouConstant.PV_LAST_LAT = (settings.getFloat(QiYouConstant.PK_DOU_LAST_LAT, QiYouConstant.PV_LAST_LAT)); - QiYouConstant.PV_LAST_LON = (settings.getFloat(QiYouConstant.PK_DOU_LAST_LON, QiYouConstant.PV_LAST_LON)); - QiYouConstant.PV_LAST_CITY = (settings.getString(QiYouConstant.PK_STR_CITY, QiYouConstant.PV_LAST_CITY)); - - int intV=0; - if(settings.contains(QiYouConstant.PK_INT_WPS_CNT_BEAR)){ - intV =Integer.valueOf(settings.getString(QiYouConstant.PK_INT_WPS_CNT_BEAR, String.valueOf(QiYouConstant.WPS_ROAD_BEAR_CNT ))); - intV =intV >1?intV:QiYouConstant.WPS_ROAD_BEAR_CNT; - QiYouConstant.WPS_ROAD_BEAR_CNT =intV; - } - if(settings.contains(QiYouConstant.PK_INT_ANGLE_BEAR)){ - intV =Integer.valueOf(settings.getString(QiYouConstant.PK_INT_ANGLE_BEAR, String.valueOf(QiYouConstant.WPS_ROAD_BEARING ))); - intV =intV >10?intV:QiYouConstant.WPS_ROAD_BEARING; - QiYouConstant.WPS_ROAD_BEARING =intV; - } - - if(settings.contains(QiYouConstant.PK_INT_WPS_KEEP_PERCENT)){ - intV =Integer.valueOf(settings.getString(QiYouConstant.PK_INT_WPS_KEEP_PERCENT, String.valueOf(QiYouConstant.WPS_SAVE_PERCENT_FACTOR ))); - intV =intV >0?intV:QiYouConstant.WPS_ROAD_BEARING; - QiYouConstant.WPS_SAVE_PERCENT_FACTOR =intV; - } - - QiYouConstant.PV_INT_SCREEN_WIDTH=settings.getInt(QiYouConstant.PK_INT_SCREEN_WIDTH, QiYouConstant.PV_INT_SCREEN_WIDTH); - QiYouConstant.PV_INT_SCREEN_HEIGHT=settings.getInt(QiYouConstant.PK_INT_SCREEN_HEIGHT, QiYouConstant.PV_INT_SCREEN_HEIGHT); - QiYouConstant.MAP_PIC_SIZE = QiYouConstant.PV_INT_SCREEN_WIDTH/20;//40;//PIC SHOW ON MAP - QiYouConstant.SUBNAIL_PIC_SIZE = QiYouConstant.PV_INT_SCREEN_WIDTH/2;//400;//PIC SHOW ON MAP - QiYouConstant.BL_ONE_SHOT_BEAR = Boolean.valueOf(settings.getBoolean(QiYouConstant.PK_BL_ONE_SHOT_BEAR, false)); - - - QiYouConstant.PV_BL_NAVI_VIBRATOR_ON = Boolean.valueOf(settings.getBoolean(QiYouConstant.PK_BL_NAVI_VIBRATOR_ON, QiYouConstant.PV_BL_NAVI_VIBRATOR_ON)); - - -// QLog.getLogger().d(dTAG, TAG+ " prefloading QiYouConstant.WPS_ROAD_BEARING,QiYouConstant.WPS_ROAD_BEAR_CNT: "+ QiYouConstant.WPS_ROAD_BEARING+","+QiYouConstant.WPS_ROAD_BEAR_CNT); -// QLog.getLogger().d(dTAG, TAG+ " prefloading QiYouConstant.WPS_SAVE_PERCENT_FACTOR: "+QiYouConstant.WPS_SAVE_PERCENT_FACTOR ); - - -// public static String PK_INT_WPS_CNT_BEAR ="PK_INT_WPS_CNT_BEAR"; -// public static String PK_INT_ANGLE_BEAR ="PK_INT_ANGLE_BEAR"; -// public static int WPS_ROAD_BEARING =20; //how much bearing change can be take as a roadwp,35,2; 25,4;...30,4;35,3;20,4 -// public static int WPS_ROAD_BEAR_CNT =4; //at least how much continued bear points can be counted as a valid roadbear - - QiYouConstant.PV_OPEN_ID = settings.getString(QiYouConstant.PK_ST_OPEN_ID, QiYouConstant.PV_OPEN_ID); - QiYouConstant.PV_ACCESS_TOKEN = settings.getString(QiYouConstant.PK_STR_ACCESS_TOKEN, QiYouConstant.PV_ACCESS_TOKEN); - QiYouConstant.PV_EXPIRES_IN=settings.getLong(QiYouConstant.PK_L_EXPIRES_IN, QiYouConstant.PV_EXPIRES_IN); -// QLog.getLogger().d(dTAG, TAG+ String.format(" prefloading QiYouConstant.PV_INT_LIVE_SPAN :'%s'", -// settings.getInt(QiYouConstant.PK_INT_LIVE_SPAN, QiYouConstant.PV_INT_LIVE_SPAN )) ); - - if(settings.contains(QiYouConstant.PK_INT_LIVE_SPAN)){ - QiYouConstant.PV_INT_LIVE_SPAN = Integer.valueOf(settings.getString(QiYouConstant.PK_INT_LIVE_SPAN, String.valueOf(QiYouConstant.PV_INT_LIVE_SPAN ))); - } - -// QiYouConstant.PV_INT_LIVE_SPAN = settings.getInt(QiYouConstant.PK_INT_LIVE_SPAN, QiYouConstant.PV_INT_LIVE_SPAN ) ; - QLog.getLogger().d(dTAG, TAG+ String.format(" prefloading QiYouConstant.PV_INT_LIVE_SPAN :'%s'",QiYouConstant.PV_INT_LIVE_SPAN) ); - - -// saveShareLocationOption(); - -} - -public long getTokenExpiresIn(){ - return System.currentTimeMillis()-settings.getLong(QiYouConstant.PK_L_EXPIRES_IN, QiYouConstant.PV_EXPIRES_IN); -} -public void saveAuth20Token(){ - - pEditor.putString(QiYouConstant.PK_ST_OPEN_ID, QiYouConstant.PV_OPEN_ID);//(QiYouConstant.PK_DOU_LAST_LAT, QiYouConstant.PV_LAST_LAT); - pEditor.putString(QiYouConstant.PK_STR_ACCESS_TOKEN, QiYouConstant.PV_ACCESS_TOKEN); - pEditor.putLong(QiYouConstant.PK_L_EXPIRES_IN, QiYouConstant.PV_EXPIRES_IN); - pEditor.commit(); -} -public void updateUserPref(){ - - QiYouConstant.PV_ACCESS_TOKEN=user.getUserbean().getToken(); - QiYouConstant.PV_USER_ID=user.getUserbean().getId(); - QiYouConstant.PV_EXPIRES_IN=user.getUserbean().getQqExprires(); - pEditor.putString(QiYouConstant.PK_STR_USER, Utils.getGsonString(user.getUserbean())); - pEditor.putString(QiYouConstant.PK_STR_ACCESS_TOKEN, QiYouConstant.PV_ACCESS_TOKEN); - pEditor.commit(); - -} - -public void logout(){ - user = new User(); - updateUserPref(); - setAuth(); - -} - -public void saveShareLocationOption(){ - pEditor.putBoolean(QiYouConstant.PK_BL_SHARE_LOCATION, QiYouConstant.PV_BL_SHARE_LOCATION); - pEditor.putString( QiYouConstant.PK_INT_LIVE_SPAN, String.valueOf(QiYouConstant.PV_INT_LIVE_SPAN)); - pEditor.putString(QiYouConstant.PK_STR_SHARE_MSG, QiYouConstant.PV_STR_SHARE_MSG); - - pEditor.commit(); -} - -public void setlastLocation(float lat,float lon){ - QiYouConstant.PV_LAST_LAT = lat ; - QiYouConstant.PV_LAST_LON = lon ; - pEditor.putFloat(QiYouConstant.PK_DOU_LAST_LAT, QiYouConstant.PV_LAST_LAT); - pEditor.putFloat(QiYouConstant.PK_DOU_LAST_LON, QiYouConstant.PV_LAST_LON); - if(this.getGEOinfo()!=null) - pEditor.putString(QiYouConstant.PK_STR_CITY, getGEOinfo().getCity()); - pEditor.commit(); -} -public void setScreenInfo(Point outSize){ - QiYouConstant.PV_INT_SCREEN_WIDTH =outSize.x ; - QiYouConstant.PV_INT_SCREEN_HEIGHT=outSize.y; - QiYouConstant.MAP_PIC_SIZE = QiYouConstant.PV_INT_SCREEN_WIDTH/20;//40;//PIC SHOW ON MAP - QiYouConstant.SUBNAIL_PIC_SIZE = QiYouConstant.PV_INT_SCREEN_WIDTH/2;//400;//PIC SHOW ON MAP - pEditor.putInt(QiYouConstant.PK_INT_SCREEN_WIDTH, QiYouConstant.PV_INT_SCREEN_WIDTH); - pEditor.putInt(QiYouConstant.PK_INT_SCREEN_HEIGHT, QiYouConstant.PV_INT_SCREEN_HEIGHT); - pEditor.commit(); -} - -//last time that geo has been done. -public void setlastGeoRequestTime(){ - QiYouConstant.LAST_GEO_UPDATE =System.currentTimeMillis(); - pEditor.putLong(QiYouConstant.PK_LONG_LAST_GEO_UPDATE,QiYouConstant.LAST_GEO_UPDATE); - - pEditor.commit(); -} - -//last time that offmap has been done. -public void setlastOffMapRequestTime(){ - QiYouConstant.LAST_OFFMAP_UPDATE =System.currentTimeMillis(); - pEditor.putLong(QiYouConstant.PK_LONG_LAST_OFFMAP_UPDATE,QiYouConstant.LAST_OFFMAP_UPDATE); - - pEditor.commit(); -} -/* public void updateUserPref(int userId,String email,String account,String passwd,String title,int score,int paiming){ - user.getUserbean().setId(userId); - user.getUserbean().setMail(email); - user.getUserbean().setUserName(account); - user.getUserbean().setPassword(passwd); - user.getUserbean().setScore(score); - user.getUserbean().setPaiming(paiming); - updateUserPref(); - }*/ - public void updateUserPref(User_bean ub){ - user.setUserbean(ub); - updateUserPref(); - } - -public void readUser(){ - - String u = settings.getString(QiYouConstant.PK_STR_USER, ""); - if(!TextUtils.isEmpty(u)){ - User_bean ub = (User_bean)Utils.getGsonObject(u, User_bean.class); - user.setUserbean(ub); - } - QiYouConstant.PV_USER_ID=user.getUserbean().getId(); -// QiYouConstant.PV_USER_ACCOUNT =user.getUserbean().getAccount(); - QiYouConstant.PK_STR_USER_NAME =user.getUserbean().getUserName(); - - - -// QiYouConstant.PV_USER_PASSWD=settings.getString(QiYouConstant.PK_STR_USER_PASSWD, QiYouConstant.PV_USER_PASSWD); -// QiYouConstant.PV_USER_ACCOUNT = settings.getString(QiYouConstant.PK_STR_USER_ACCOUNT, QiYouConstant.PV_USER_ACCOUNT); -// QiYouConstant.PV_USER_EMAIL=settings.getString(QiYouConstant.PK_STR_USER_EMAIL, QiYouConstant.PV_USER_EMAIL); - - /*user.getUserbean().setUserName(settings.getString(QiYouConstant.PK_STR_USER_NAME, QiYouConstant.PV_USER_NAME)); - user.getUserbean().setAccount(settings.getString(QiYouConstant.PK_STR_USER_ACCOUNT, QiYouConstant.PV_USER_ACCOUNT)); - user.getUserbean().setTitle(settings.getString(QiYouConstant.PK_STR_USER_TITLE, "")); - user.getUserbean().setPassword(settings.getString(QiYouConstant.PK_STR_USER_PASSWD, "")); - user.getUserbean().setId(settings.getInt(QiYouConstant.PK_INT_USER_ID, QiYouConstant.PV_USER_ID)); - user.getUserbean().setPaiming(settings.getInt(QiYouConstant.PK_STR_USER_PAIMING, 0)); - user.getUserbean().setScore(settings.getInt(QiYouConstant.PK_STR_USER_SCORE, 0));*/ - -} -//set gpx to show -public void setGpxShowingTracks(String trackId,Boolean isAdd){ - - String trackIds = settings.getString(QiYouConstant.PK_STRING_SHOWING_GPX,""); - trackId=","+trackId+","; - if(isAdd){ - trackIds+=trackId; - }else{ - trackIds=trackIds.replace(trackId, ""); - } - pEditor.putString(QiYouConstant.PK_STRING_SHOWING_GPX,trackIds); - pEditor.commit(); -} -//last time that offmap has been done. -public ArrayList getGpxShowingTracks(){ - - String trackIds = settings.getString(QiYouConstant.PK_STRING_SHOWING_GPX,""); - String[] ids =trackIds.split(","); - ArrayListiids= new ArrayList(); - int iid; - for(String id:ids){ - id =id.trim(); - if(TextUtils.isEmpty(id))continue; - iid=Integer.valueOf(id); - if(iid>0 && !iids.contains(iid)){ - iids.add(iid); - - } - } - return iids; - - } -public void initialShowingGpxs(){ - - if(getGpxShowingTracks().size()==0)return; - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.INITIAL_GPXS, 1); - startService(serviceIntent); -} - - - - - - -public long getLastStatSyncTime(){ - return settings.getLong(QiYouConstant.PK_INT_LAST_SYNC_TIME,0); -// return TextUtils.isEmpty() ; -} - -public void setLastStatSyncTime(long time){ - pEditor.putLong(QiYouConstant.PK_INT_LAST_SYNC_TIME,time); - pEditor.commit(); -} - - - - - - - - - -public void setlastLocation(Location loc){ -// Editor pEditor = settings.edit(); - if( loc!=null) { - QiYouConstant.PV_LAST_LAT = (float) (lastLocation.getLatitude()) ; - QiYouConstant.PV_LAST_LON = (float) (lastLocation.getLongitude()) ; - pEditor.putFloat(QiYouConstant.PK_DOU_LAST_LAT, QiYouConstant.PV_LAST_LAT); - pEditor.putFloat(QiYouConstant.PK_DOU_LAST_LON, QiYouConstant.PV_LAST_LON); - pEditor.commit(); - } -} - -public void setLastTracktype(){ - if(recordingTrack!=null -// && QiYouConstant.TRACK_TYPE_COPY != recordingTrack.getTrackBean().getType() - && TrackType.COPY != recordingTrack.getTrackBean().getType() - && recordingTrack.getTrackBean().getStatus()!=TrackStatus.FINISHED) { - pEditor.putInt(QiYouConstant.PK_INT_LAST_TRACKTYPE,recordingTrack.getTrackBean().getType().toInt()); - pEditor.commit(); - } -} - -public int getLastTracktype(){ - return settings.getInt(QiYouConstant.PK_INT_LAST_TRACKTYPE, 0); -} - -public void setLastRecordingIdStartTime(){ -// Editor pEditor = settings.edit(); - if(recordingTrack!=null -// && QiYouConstant.TRACK_TYPE_COPY != recordingTrack.getTrackBean().getType() - && TrackType.COPY != recordingTrack.getTrackBean().getType() - && recordingTrack.getTrackBean().getStatus()!=TrackStatus.FINISHED) { - pEditor.putInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,recordingTrack.getTrackBean().getTrackId()); - if(isNaving) - pEditor.putInt(QiYouConstant.PK_INT_LAST_NAVI_TRACK,recordingTrack.getTrackBean().getTrackId()); - - pEditor.putLong(QiYouConstant.PK_LONG_LAST_TRACK_START,System.currentTimeMillis()); - pEditor.commit(); - } - else{ - clearLastRecordingIdStartTime(); - } - - // apply(); - - // pEditor.apply(); - //TODO: use apply on high plaform while commit on low platform. - -} - -public void clearLastRecordingIdStartTime(){ - pEditor.putInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,-1); - pEditor.putLong(QiYouConstant.PK_LONG_LAST_TRACK_START,0); - if(isNaving) - pEditor.putInt(QiYouConstant.PK_INT_LAST_NAVI_TRACK,-1); -// pEditor.putInt(QiYouConstant.PK_INT_LAST_TRACKTYPE,0); - pEditor.commit(); -} - -public Map tabSpIndex; - - public void setPreferences(boolean isExitApp,boolean isStartup){ - -// Editor pEditor = settings.edit(); - if(isExitApp){ - pEditor.putLong(QiYouConstant.PK_LONG_LAST_QUIT, System.currentTimeMillis()); - pEditor.putInt(QiYouConstant.PK_INT_APP_CNT, ++QiYouConstant.PV_APP_CNT); - if( tabSpIndex !=null && tabSpIndex.keySet().size()>0){ - QiYouConstant.PV_LAST_BBS_CATE = Utils.getGsonString(tabSpIndex); - pEditor.putString(QiYouConstant.PK_LAST_BBS_CATE, QiYouConstant.PV_LAST_BBS_CATE ); - } - - -// if(this.recordingTrack.getTrackBean().getStatus()!=QiYouConstant.TRACK_STATUS_FINISHED) -// { -// pEditor.putInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,recordingTrack.getTrackBean().getTrackId()); -// }else -// pEditor.putInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,-1); - -// setLastRecordingIdStartTime(); - - }else if (isStartup){ - - pEditor.putLong(QiYouConstant.PK_LONG_LAST_START, System.currentTimeMillis()); -// Toast toast= Toast.makeText(this, " QY Application is on create. "+TAG, Toast.LENGTH_LONG ); -// toast.show(); - } - - - - pEditor.commit();// apply(); -// String a = ""; - // pEditor.apply(); - //TODO: use apply on high plaform while commit on low platform. - -} - - /*public void getTracks(String[] ids) - { - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_IDS, ids); - startService(serviceIntent); - }*/ - public HashMap geoWps; - public void updateGEOs(HashMap geoWps){ - if(geoWps==null||geoWps.size()==0)return; - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - this.geoWps= geoWps; - QLog.getLogger().d(dTAG, TAG+" app.geoWps.size():"+geoWps.size() ); - serviceIntent.putExtra( QiYouConstant.EXTRA_KEY_TRACK_GEOS, 1); - startService(serviceIntent); - } - - - public void getStaticsTracks(int trackType) - { - if(statTrackLoading)return; -// statTrackLoading=true; - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_STSTICS_TRACKS, trackType); - startService(serviceIntent); - } - - public void syncStatistics() - { - QLog.getLogger().d(dTAG, " begin to sync statistics.............."); - Intent serviceIntent = new Intent(this, sync.class); - serviceIntent.putExtra(QiYouConstant.ACTION_SYNC_STATISTICS, 0); - startService(serviceIntent); - } - public void syncStatisticsBeforExit() - { - QLog.getLogger().d(dTAG, " begin to sync statistics before exit app.............."); - Intent serviceIntent = new Intent(this, sync.class); - serviceIntent.putExtra(QiYouConstant.ACTION_SYNC_STATISTICS, 1); - startService(serviceIntent); - } - - /* - * get all tracks to the statisticTracks. - */ - public void getStaticsTracks() - { -// Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); -// serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_STSTICS_TRACKS, -100); -// startService(serviceIntent); - getStaticsTracks(-100); - statTrackLoading=true; - } - - - /* - * Application start 1 分钟内, 不做trackstatus, gps status ,forceupdate 开关 处理. - */ - public boolean isAppLong() - { - return (System.currentTimeMillis() - startTime)/1000/60 >QiYouConstant.MAX_TRACK_RESTORE_TIME; - } - - /* - * Application may restart, for memory or other service process may need to create new Application instance. - * this causes lost status of application members - * use start time to judge need to cancel gps request and force_update - */ - public void reviewTrackStatus(){ - -/* if (isAppLong()){ - - if(!isGPSstopped){ -// if((getRecordingTrack().getTrackBean().getStatus()!=QiYouConstant.TRACK_STATUS_TRACKING ||!canRecord) || playBack) { -// QLog.getLogger().d(dTAG,TAG+" "+ "recordingTrackStatus: " +getRecordingTrack().getTrackBean().getStatus() + -// ",app.canRecord "+canRecord +",app.playBack " +playBack); - if(!isCanRecord()){ - QLog.getLogger().d(dTAG,TAG+" Application start time since now(s): " +(System.currentTimeMillis() - startTime)/1000); - stopAndroidGPSRequest(); - QLog.getLogger().d(dTAG,TAG+" GPS request is cancelled. "); - } - }else{ //GPS request is stopped, to check recording track status.This will be triggered by force update. -// if(getRecordingTrack().getTrackBean().getStatus() == QiYouConstant.TRACK_STATUS_TRACKING && canRecord) - { - startAndroidGPSRequest(); - QLog.getLogger().d(dTAG,TAG+" "+ "GPS request is started by force-update. "); - } - } - } */ - /* if (isAppLong()){ - if(isCanRecord()){ - if(isGPSstopped) - startAndroidGPSRequest(); - }else{ - if(!isGPSstopped) - stopAndroidGPSRequest(); - } - }*/ - - - -// canRecord =QiYouConstant.PLAYBACK_CAN_RECORD; -// initialLocationParameters(); -// QLog.getLogger().d(TAG," read app.sumofftime "+ sumOfftime ); -// QLog.getLogger().d(TAG," read app.sumPaused "+ sumPaused ); - - } - - - - - /* - * stop all services/ activities - * release all resource - * - */ - public void ExitApp() - { - QLog.getLogger().d(dTAG,TAG+" ------------------------ExitApp called.------------------------"); - // 取消监听 SDK 广播 - try{ - unregisterReceiver(mReceiver); - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - } - forceDbUpdate(true); -// stopAndroidGPSRequest(); - unregTimeTick(); - setPreferences(true,false); -// Toast toast= Toast.makeText(this, " QY Application is Exiting..bye.. "+TAG, Toast.LENGTH_LONG ); -// toast.show(); - stopNetworkLocationRequest(); -// syncStatisticsBeforExit(); - final long start = System.currentTimeMillis(); - - if (isStaticsticsDone) { - isStaticsticsDone = false; - } - syncStatisticsBeforExit(); - MobclickAgent.onKillProcess(this); //用来保存统计数据。 - - final Handler handler = new Handler(){ - @Override - public void handleMessage(Message msg) { - if (msg.what==0) { - QLog.getLogger().d(dTAG, TAG+" to exit app. sync cost(s) " + (System.currentTimeMillis() -start)/1000); - if(!isUIactive ){ - - System.exit(0); - } - } - }}; - - new Thread(){ - - @Override - public void run() { - //需要花时间计算的方法 - int topWaiting=0; - - - while(!isStaticsticsDone - - ){ //||start,end, type){ - try { - Thread.sleep(500); - topWaiting+=500; - QLog.getLogger().d(dTAG, TAG+" Waiting: " + topWaiting); - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB*10 ) - { - - break; - } - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - handler.sendEmptyMessage(0); - } - } - QLog.getLogger().d(dTAG, TAG+" get sync done topWaiting: " +topWaiting); - //向handler发消息 - handler.sendEmptyMessage(0); - }}.start(); - -// System.exit(0); - } - - - /* - * when startup,check network status\ - * initialize httpClient - * 1. update GEOs - * 2. get the location info, which city located? - */ - public void worksOnLine(int trackId){ - - mHttpClient = this.createHttpClient(); - - int networkType =Utils.getNetworkType(this); - if(networkType==-1) return; //no active network - - if(trackId>0 || networkType == QiYouConstant.NETWORK_TYPE_WIFII && Utils.canUpdateGEOfootmark(this)) - { - -// Intent serviceIntent = new Intent(this, OfflineMapService.class); -// startService(serviceIntent); - - Intent serviceIntent = new Intent(this, TrackGEOService.class); - - if(trackId>0) - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID,trackId ); //update all tracks that KEY_TRACK_GEO_STATUS !=1 - else - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_TRACK_GEOS,-1 ); //update all tracks that KEY_TRACK_GEO_STATUS !=1 - - startService(serviceIntent); -// getCurrentCity(); -// startNetworkLocationRequest(true); - } -// startNetworkLocationRequest(true); - - } - - - - - - public boolean canUpdateOffmap( ){ - return Utils.canUpdateOffmap(this); - } - - -public boolean isOfflimeMapWorking =false; -public boolean isNetworkLocationRequestStarted =false; - -/* - * when activity is created, call this method with isOffMap=true to check and update the offline maps . - */ -public void startNetworkLocationRequest(Boolean isOffMap){ - -// if(( QiYouConstant.NETWORK_CONNECTED || Utils.isNetworkConnected(this)) _&& !isNetworkLocationRequestStarted){ - if( Utils.isNetworkConnected(this) && !isNetworkLocationRequestStarted || this.isLocationFinding){ - -// if( Utils.isNetworkConnected(this)){ - - - /* - if (ContextCompat.checkSelfPermission(this, - Manifest.permission.CALL_PHONE) - != PackageManager.PERMISSION_GRANTED) - { - - ContextCompat.requestPermissions(this, - new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1 ); - } - - */ - - - Intent serviceIntent = new Intent(this, BDLocationSvc.class); - if(isOffMap){ - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_CURRENT_CITY, ""); - QLog.getLogger().d(dTAG,TAG+" start to request offmap information from network " ); - } - else{ - serviceIntent.putExtra(LocationManager.KEY_LOCATION_CHANGED, ""); - QLog.getLogger().d(dTAG,TAG+" start to request location information from network " ); - } - - if(isOffMap){ - - if(/*this.mMapview ==null || */!Utils.canUpdateOffmap(this) )return; - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_NETWORK_LOCATION,QiYouConstant.EXTRA_KEY_GET_CURRENT_CITY); - startService(serviceIntent); - // QLog.getLogger().d(dTAG,TAG+" start to request offmap information from network " ); - } - else if( canRecord()||this.isRouting ||isLocationFinding){ //network location request. - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_NETWORK_LOCATION,LocationManager.KEY_LOCATION_CHANGED); - QLog.getLogger().d(dTAG,TAG+" start to request location information from network " ); - startService(serviceIntent); -// if(QiYouConstant.DEVELOPER_MODE) Toast.makeText( this, "无gps信号,启动..网络定位....", Toast.LENGTH_SHORT).show(); - } - - - - - } - - -// -// -//// if(!isNetworkLocationRequestStarted){ -// if(lm==null){ -// lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); -// } -// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000,0, netwrokLocationListenerPendingIntent); -// -// -// isNetworkLocationRequestStarted =true; -// QLog.getLogger().d(dTAG, TAG+ " Network location service request started...."); - - } -public void stopNetworkLocationRequest(){ - - if( mLocClient==null) return; - - mLocClient.getLocOption().setScanSpan(1); //set it less than 1000, can stop its location request. - isNetworkLocationRequestStarted=false; - // QLog.getLogger().d(dTAG,TAG+" network location request is going to be cancled."); -// if(QiYouConstant.DEVELOPER_MODE) Toast.makeText( this, "停止...网络定位.... 停止", Toast.LENGTH_SHORT).show(); -// if(isNetworkLocationRequestStarted){ -// if(lm==null){ -// lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); -// } -// lm.removeUpdates(netwrokLocationListenerPendingIntent); -// } -// isNetworkLocationRequestStarted =false; - } - - - -/*public StatTrack getStatTrack() { - if(statTrack==null)statTrack= new StatTrack(); - - - return statTrack; -} -public void setStatTrack(StatTrack statTrack) { - this.statTrack = statTrack; -}*/ - -public GEOaddress getGEOinfo() { - return GEOinfo; -} -public void setGEOinfo(GEOaddress gEOinfo) { - GEOinfo = gEOinfo; - this.setlastLocation((float)Utils.getggLat(gEOinfo.getLat() , gEOinfo.getLon()),(float)Utils.getggLon(gEOinfo.getLat(), gEOinfo.getLon())); -} - -/* -boolean getBdGEOadress(double lat, double lon){ - - if(mSearch ==null){ - mSearch= GeoCoder.newInstance(); - mSearch.setOnGetGeoCodeResultListener(new MySearchListener()); - } - - GEOadress=null; - isGEOerror=false; -// double blat = Utils.getbdLat(lat, lon); -// double blon = Utils.getbdLon(lat, lon); - LatLng ptCenter = new LatLng( lat, lon) ; -// LatLng ptCenter = new LatLng(Utils.getbdLat(lat, lon), Utils.getbdLon(lat, lon)); - isGEOerror =mSearch.reverseGeoCode(new ReverseGeoCodeOption() .location(ptCenter)); - return isGEOerror; - - -} - - AddressComponent GEOadress; - ReverseGeoCodeResult addressResult; - public boolean isGEOerror =false; - class MySearchListener implements OnGetGeoCoderResultListener { - - @Override - public void onGetGeoCodeResult(GeoCodeResult result) { - // TODO Auto-generated method stub - QLog.getLogger().d(dTAG,TAG+" ----------------- onGetGeoCodeResult " + result.getAddress()); - } - - @Override - public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) { - // TODO Auto-generated method stub -// isGEOerror = error>0; - - GEOadress = result.getAddressDetail(); - if(GEOadress!=null) - City=GEOadress==null?"":GEOadress.city; - addressResult =result; - - QLog.getLogger().d(dTAG,TAG+" ----------------- onGetReverseGeoCodeResult " + result.getAddress()); - - } - } - */ - @Override - public void onLowMemory() { - // TODO Auto-generated method stub - super.onLowMemory(); -// this.shutdownHttpClient(); //will cause android.os.NetworkOnMainThreadException -// Utils.logStackTrace(new Exception(" Memory Low..........,allocated memory by M:"+ android.os.Debug.getNativeHeapAllocatedSize()/1000/1000),dTAG); - QLog.getLogger().dLog(dTAG,TAG+"................. Memory Low..........,allocated memory by M:"+ android.os.Debug.getNativeHeapAllocatedSize()/1000/1000); -// ImageLoader.getInstance().clearMemoryCache(); -// ImageLoader.getInstance().clearDiskCache(); -// initialImageLoader(); - } - - public void initialImageLoader(){ - - File cacheDir=new File(QiYouConstant.PHOTO_CACHE_PATH); - if(!cacheDir.exists())cacheDir.mkdirs(); - DisplayImageOptions defaultOptions = new DisplayImageOptions - .Builder() -// .resetViewBeforeLoading() - .showImageForEmptyUri(R.drawable.empty_photo) - .showImageOnFail(R.drawable.empty_photo) - .cacheInMemory(true) -// .cacheOnDisc(true) - .cacheOnDisk(true) - .bitmapConfig(Bitmap.Config.RGB_565) -// .imageScaleType(ImageScaleType.EXACTLY) //good - .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) //better - .build(); - ImageLoaderConfiguration config = new ImageLoaderConfiguration - .Builder(getApplicationContext()) - .memoryCache(new WeakMemoryCache()) - .denyCacheImageMultipleSizesInMemory() - .diskCache(new UnlimitedDiscCache(cacheDir)) -// .memoryCacheExtraOptions(480, 800) // default=device screen dimensions - -// .diskCacheExtraOptions(480, 800, CompressFormat.JPEG, 75) - - .defaultDisplayImageOptions(defaultOptions) - .tasksProcessingOrder(QueueProcessingType.FIFO) - .memoryCacheSize(50 * 1024 * 1024) - .diskCacheSize(100 * 1024 * 1024)// -// .diskCacheFileCount(100)//缓存一百张图片 - .writeDebugLogs() - .build(); - ImageLoader.getInstance().init(config); - } - - - - - /* class mSensorListener implements SensorEventListener{ - - @Override - public void onSensorChanged(SensorEvent event) { - // TODO Auto-generated method stub - if (event.sensor.getType() ==SensorManager.sen ) { - oy=values[1]; - oz=values[2]; - } - if (sensor == SensorManager.SENSOR_ACCELEROMETER) { - ax=values[0]; - ay=values[1]; - } - - } - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - // TODO Auto-generated method stub - - } - - - - } - */ - - - public static volatile PowerManager.WakeLock lockStatic=null; - - synchronized public static PowerManager.WakeLock getLock(Context context) { - if (lockStatic == null) { - PowerManager mgr= - (PowerManager)context.getSystemService(Context.POWER_SERVICE); - - lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); - lockStatic.setReferenceCounted(true); - } - - return(lockStatic); - } - - - public void regTimeTick(){ -// IntentFilter javaFilter = new IntentFilter(); -// javaFilter.addAction("android.intent.action.TIME_TICK"); -// registerReceiver(timeTickReceiver, javaFilter); -// unregTimeTick(); - if(this.isLastTrackExist() && !playBack){ -// if(this.canRecord()){ - forceDbUpdate(false); - if(timeTickIntent==null) - timeTickIntent = new Intent(this, TimtickService.class); -// serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID, trackId); - - // QLog.getLogger().dLog(dTAG,TAG+"...startting service timeTickIntent TimtickService.....," ); - // - startService(timeTickIntent); - } - - } - - public void unregTimeTick(){ - if(timeTickIntent==null) - timeTickIntent = new Intent(this, TimtickService.class); - this.stopService(timeTickIntent); - // // // QLog.getLogger().dLog(dTAG,TAG+"...stopped service timeTickIntent .....," ); - } - - - - - - - - public void initialStatistics(){ -// testEnde(); - StringBuffer statJson=new StringBuffer(); - /* try { - - statJson.append(Utils.readSDFile(QiYouConstant.STAT_TEXT)); - - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - }*/ - - - -// statJson.append(FileUtil.readFile(QiYouConstant.STAT_TEXT+"_en", crypto, entity)); - - - try { - // QLog.getLogger().d(dTAG, " begin to read Statistics from "+ QiYouConstant.STAT_TEXT+"_en ..........................................." ); - -// FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_en", QiYouConstant.STAT_TEXT, crypto, entity); -// statJson.append(Utils.readSDFile(QiYouConstant.STAT_TEXT)); - statJson.append(FileUtil.readEncodedFile(QiYouConstant.STAT_TEXT, crypto, entity)); -// // // QLog.getLogger().d(dTAG, " QiYouConstant.STAT_TEXT is: "+QiYouConstant.STAT_TEXT ); - // QLog.getLogger().d(dTAG, " statJsn is: "+statJson.toString() ); - if(QiYouConstant.DEVELOPER_MODE) - Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_de", statJson.toString()); -// Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); - - mStatistics= (Statistics)Utils.getGsonObject(statJson.toString(), Statistics.class) ; - -// // // // QLog.getLogger().d(dTAG, " read Statistics from "+ QiYouConstant.STAT_TEXT+"_en ........................................... done" ); - - }catch( JsonSyntaxException je){ - Utils.logStackTrace(je, TAG); - mStatistics=null; - } catch (IOException e) { -// // TODO Auto-generated catch block - e.printStackTrace(); - } - - - mStatistics =mStatistics==null?new Statistics():mStatistics; - - HashMap deltaList=new HashMap(); - - if(mStatistics!=null && mStatistics.getGpList().size()>100){ //remove duplicated ones - int ikey=0; - GPItem item; - for(Integer key:mStatistics.getGpList().keySet()){ - item =mStatistics.getGpList().get(key); - if(item!=null){ - deltaList.put(item.getLat()+"_"+item.getLng(), item); - } - } - - mStatistics.getGpList().clear(); - for(String key:deltaList.keySet()){ - item =deltaList.get(key); - if(item!=null){ - mStatistics.getGpList().put(ikey, item); - ikey++; - } - } - } - - - - } - - public void writeStatiscs(){ - try { -// Gson gson = new Gson(); - - Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_tmp",Utils.getGsonString(mStatistics)); - FileUtil.encodeFile(QiYouConstant.STAT_TEXT, QiYouConstant.STAT_TEXT+"_tmp", crypto, entity); - -// FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_conseal_en", QiYouConstant.STAT_TEXT+"_conseal_plain", crypto, entity); - - -// FileUtil.writeFile(this.crypto,this.entity, QiYouConstant.STAT_TEXT+"_conseal", gson.toJson(mStatistics) ); -// FileUtil.writeFile(this.crypto,this.entity, QiYouConstant.STAT_TEXT+"_test", "a" ); -// Utils.writeSDFile( QiYouConstant.STAT_TEXT+"_test_a","a" ); -// Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_a_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - /*} catch (CryptoInitializationException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } catch (KeyChainException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - */ - } - } - - - - - -public TypeStatistics getTracksStat(int trackType,long startDate,long endDate){ - -// int totalChartSize=11; - -// if(activity.app.statisticsTrack==null ) -// initialStatTracks(); - - //startDate=0;, endDate - TypeStatistics mTypeStatistics = new TypeStatistics(); - if( getStatisticsTrack(trackType)==null) return mTypeStatistics;//no records for selected type or date. -// QLog.getLogger().d(dTAG, TAG+ " dddddddddddddddddddddd-------------------begin to get StatTrack. ------------of type-"+ trackType ); - - - - ConcurrentHashMap sbs = getStatisticsTrack(trackType).getSbs(); - Statics_bean sb; - int sbCnt=0; - for(Integer key :sbs.keySet()){ - sb=sbs.get(key); - if(sb==null)continue; - - if( ( - startDate>0 && endDate >= startDate - && - (sb.getStartTime()>=startDate && sb.getStartTime()<=endDate - ||sb.getEndTime()>=startDate && sb.getEndTime()<=endDate - ) - ||(startDate == endDate && startDate==0) - ) - && sb.getType() == trackType ) - mTypeStatistics.getSbs().put(sb.getTrackid(), sb); - } - - StatTrack st = new StatTrack(); - for(Integer key : mTypeStatistics.getSbs().keySet()){ - sb=mTypeStatistics.getSbs().get(key); -// st.seteDownDist(sb.geteDownDist() ); -// st.seteUpDist( sb.geteUpDist()+sb.geteDownDist()); - st.setUpDistE( sb.geteUpDist()); - st.setTopSpeed(sb.getTopSpeed() ); - st.setPause(sb.getPause() ); - st.setOffTime( sb.getOffTime()); - st.setDist(sb.getDist()); - st.setMaxR( sb.getMaxR()); - st.setSportTime( sb.getSportTime()); - st.setAvSpeed(sb.getAvs()); - st.setTavSpeed(sb.getTavs()); - st.setBurn(sb.getBurn()); -// st.setTotalTime(sb.getSportTime()+sb.getPause()); - st.setTotalTime(sb.getTotalTime()); - st.setUpDist(sb.getUpDist()); - st.setDownDist(sb.getDownDist()); - st.setMaxEle(sb.getMaxEle()); - st.setMinEle(sb.getMinEle()); - st.setMinTimeKm(sb.getKmTime()); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd getStatTracks------------------" ); -// -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getDistance()"+sb.getDistance() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getSportTime()"+sb.getSportTime() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getAVS()"+sb.getAVS() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getPause()"+sb.getPause() ); - - } - - mTypeStatistics.setStatTrack(st); -// QLog.getLogger().d(dTAG, TAG+ " dddddddddddddddddddddd-------------------Get StatTrack. -------------" ); - - - return mTypeStatistics; - } - - - - - - - - - - - - public TypeStatistics getStatisticsTrack(int type){ - TypeStatistics mTypeStatistics =new TypeStatistics(); -// QLog.getLogger().d(dTAG,TAG+"-------...mStatistics==null .....,"+(mStatistics==null)+startTime ); - if(mStatistics==null && !statTrackLoading) { - getStaticsTracks(); - - }else if(mStatistics!=null){ - mTypeStatistics =mStatistics.getStatisticsTracks().get(Integer.valueOf(type)); -// if(statTrack==null || mTypeStatistics.getSbs().keySet().size()==0){ - if(mTypeStatistics==null || mTypeStatistics.getSbs().keySet().size()==0){ - this.getStaticsTracks(type); -// return new TypeStatistics(); - } - } - return mTypeStatistics; - } - public void updateStatistics(){ - - new Thread(){ - - @Override - public void run() { - - QLog.getLogger().d(dTAG, TAG+" begin to Merge Track statiscs: ------------------->"); -// if(!isUIactive || - if( - recordingTrack==null - ||recordingTrack.getTrackBean().getTrackId()==0 -// ||isLostGps() -// ||System.currentTimeMillis()- recordingTrack.getTrackBean() -// .getLastdbTime() >2* QiYouConstant.MAX_TIME_FORCE_UDATE - ){ - QLog.getLogger().d(dTAG, TAG+" 1 return not merge statiscs: ------------------->"); - return; - } - - if(mStatistics!=null && !statTrackLoading ) { -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: ------------------->"); -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: Current recordingTrack tb.getLastdbTime():?" + Utils.getFormatedTime( recordingTrack.getTrackBean().getLastdbTime() )); - mStatistics.mergeTrack(recordingTrack); -// if( canSendLocation2UI) - writeStatiscs(); - return; - }else{ - // QLog.getLogger().d(dTAG, TAG+" mStatistics!=null ? "+(mStatistics!=null)); - // QLog.getLogger().d(dTAG, TAG+" statTrackLoading ? "+statTrackLoading); - // QLog.getLogger().d(dTAG, TAG+" 2 return not merge statiscs: ------------------->"); - } - - - }}.start(); - - - - - /*Intent locIntent = new Intent(QiYouConstant.ACTION_NEW_WAYPOINTS_TO_SAVE); - locIntent.putExtra(QiYouConstant.EXTRA_KEY_FORCE_UPDATE_STAT,1); - sendBroadcast(locIntent);*/ - - - } - - public void updateUIstatus(boolean isShowing){ - canSendLocation2UI =isShowing; - pEditor.putBoolean(QiYouConstant.PK_BL_CAN_UPDATE_UI,canSendLocation2UI); - - pEditor.commit(); - } - - - - @Override - public void onTerminate() { - // TODO Auto-generated method stub - super.onTerminate(); - this.shutdownHttpClient(); - stopMts(); - QLog.getLogger().dLog(TAG, " Application Terminited." ); - - - } - - - /**创建HttpClient实例 - * @return - */ - private HttpClient createHttpClient(){ - HttpParams params = new BasicHttpParams(); - //设置基本参数 - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, CHARSET); - HttpProtocolParams.setUseExpectContinue(params, true); - //超时设置 - /*从连接池中取连接的超时时间*/ - ConnManagerParams.setTimeout(params, 1000); - /*连接超时*/ - HttpConnectionParams.setConnectionTimeout(params, 4000); - /*请求超时*/ - HttpConnectionParams.setSoTimeout(params, 8000); - //设置HttpClient支持HTTp和HTTPS两种模式 - SchemeRegistry schReg = new SchemeRegistry(); - schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); -// schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); -// schReg.register(new Scheme("https", new EasySSLSocketFactory(), 443)); - //使用线程安全的连接管理来创建HttpClient - ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); - HttpClient client = new DefaultHttpClient(conMgr, params); - return client; - } - private void shutdownHttpClient(){ - if(mHttpClient != null && mHttpClient.getConnectionManager() != null){ - mHttpClient.getConnectionManager().shutdown(); - } - } - - - public HttpClient getHttpClient(){ - if(mHttpClient==null)createHttpClient(); - return mHttpClient; - } - public HashMap> getNewCategoryList() { - if(newCategoryList==null)newCategoryList =new HashMap>(); - return newCategoryList; - } - public void setNewCategoryList(HashMap> newCategoryList) { - this.newCategoryList = newCategoryList; - } - public HashMap> getDelCategoryList() { - if(delCategoryList==null)delCategoryList =new HashMap>(); - return delCategoryList; - } - public void setDelCategoryList(HashMap> delCategoryList) { - this.delCategoryList = delCategoryList; - } - public boolean updateCates(String newCate){ - if(!TextUtils.isEmpty(newCate) && !mStatistics.getCategoryList().containsKey(newCate)){ - //add to newCateList for insert to db - if( getNewCategoryList().get(0) ==null){ - getNewCategoryList().put(0, new ArrayList()); - getNewCategoryList().get(0).add(newCate); - }else if(! getNewCategoryList().get(0).contains(newCate)) - getNewCategoryList().get(0).add(newCate); - - - - //add the new cate to the statics for catelist update ui - ArrayList ids= mStatistics.getCategoryList().get(newCate); - if(ids==null)ids =new ArrayList(); - if(!ids.contains(0)){ - ids.add(0); - } - mStatistics.getCategoryList().put(newCate, ids); - } - - - if( - mStatistics.mergeCates(getNewCategoryList(), true) || - mStatistics.mergeCates(getDelCategoryList(), false) - ){ - - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.UPDATE_CATE_TRACK , 1); - startService(serviceIntent); - return true; - } - return false; - } - - - public void updateTrackSvrNos( HashMap ids){ - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_UPDATE_SVRNOS , ids) ; - startService(serviceIntent); - } - - /* - * update track md - */ - public void updateTrackMds( int trackId,String mds){ - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_UPDATE_MEDIAS , mds) ; - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_ID , trackId) ; - startService(serviceIntent); - } - - public void updateTrackAvStatus(int trackId){ - Intent serviceIntent = new Intent(this, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.UPDATE_TRACK_AVSTATUS , trackId); - startService(serviceIntent); - } - public void initialCates(){ - return; -// QLog.getLogger().d(dTAG, " .................initialCates called"); - - /*String newCate="通勤"; - if(mStatistics.getCategoryList().containsKey(newCate)) return; - updateCates(newCate); - updateCates("拉练"); - updateCates("休闲"); - updateCates("越野"); - updateCates("竞赛"); */ -// updateCates("环湖"); - } - public ArrayList getQueryCategoryList() { - if(queryCategoryList==null)queryCategoryList=new ArrayList(); - return queryCategoryList; - } - public void setQueryCategoryList(ArrayList queryCategoryList) { - this.queryCategoryList = queryCategoryList; - } - - - - //initial speech utils - private SpeechSynthesizer mTts; - - private String mSampleDirPath; - private static final String SAMPLE_DIR_NAME = "baiduTTS"; - private static final String SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female.dat"; - private static final String SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male.dat"; - private static final String TEXT_MODEL_NAME = "bd_etts_text.dat"; -// private static final String LICENSE_FILE_NAME = "temp_license"; - private static final String ENGLISH_SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female_en.dat"; - private static final String ENGLISH_SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male_en.dat"; - private static final String ENGLISH_TEXT_MODEL_NAME = "bd_etts_text_en.dat"; - private void makeDir(String dirPath) { - File file = new File(dirPath); - if (!file.exists()) { - file.mkdirs(); - } - } - private void initialEnv() { - QLog.getLogger().d(dTAG,"begin to copy bdtts assets to sd ..."); - if (mSampleDirPath == null) { - String sdcardPath = Environment.getExternalStorageDirectory().toString(); - mSampleDirPath = sdcardPath + "/qiyou/" + SAMPLE_DIR_NAME; - } - makeDir(mSampleDirPath); - copyFromAssetsToSdcard(false, SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_FEMALE_MODEL_NAME); - copyFromAssetsToSdcard(false, SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_MALE_MODEL_NAME); - copyFromAssetsToSdcard(false, TEXT_MODEL_NAME, mSampleDirPath + "/" + TEXT_MODEL_NAME); -// copyFromAssetsToSdcard(false, LICENSE_FILE_NAME, mSampleDirPath + "/" + LICENSE_FILE_NAME); -// copyFromAssetsToSdcard(false, "english/" + ENGLISH_SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/" -// + ENGLISH_SPEECH_FEMALE_MODEL_NAME); -// copyFromAssetsToSdcard(false, "english/" + ENGLISH_SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/" -// + ENGLISH_SPEECH_MALE_MODEL_NAME); -// copyFromAssetsToSdcard(false, "english/" + ENGLISH_TEXT_MODEL_NAME, mSampleDirPath + "/" -// + ENGLISH_TEXT_MODEL_NAME); - - QLog.getLogger().d(dTAG," copy bdtts assets to sd ...done"); - } - - /** - * 将sample工程需要的资源文件拷贝到SD卡中使用(授权文件为临时授权文件,请注册正式授权) - * - * @param isCover 是否覆盖已存在的目标文件 - * @param source - * @param dest - */ - private void copyFromAssetsToSdcard(boolean isCover, String source, String dest) { - File file = new File(dest); - if (isCover || (!isCover && !file.exists())) { - InputStream is = null; - FileOutputStream fos = null; - try { - is = this.getResources().getAssets().open(source); - String path = dest; - fos = new FileOutputStream(path); - byte[] buffer = new byte[1024]; - int size = 0; - while ((size = is.read(buffer, 0, 1024)) >= 0) { - fos.write(buffer, 0, size); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fos != null) { - try { - fos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - try { - if (is != null) { - is.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private void initialSpeech(){ - QLog.getLogger().d(dTAG,"begin to initial bd tts speach...."); - initialEnv(); - this.mTts = SpeechSynthesizer.getInstance(); - this.mTts.setContext(this); - this.mTts.setSpeechSynthesizerListener(mTtsInitListener); - this.mTts.setParam(SpeechSynthesizer.PARAM_VOLUME, "5"); - this.mTts.setParam(SpeechSynthesizer.PARAM_SPEED, "5"); - this.mTts.setParam(SpeechSynthesizer.PARAM_PITCH, "5");// 语调 [ 0- 9] - this.mTts.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");// - - // 文本模型文件路径 (离线引擎使用) - this.mTts.setParam(SpeechSynthesizer.PARAM_TTS_TEXT_MODEL_FILE, mSampleDirPath + "/" - + TEXT_MODEL_NAME); -// // 声学模型文件路径 (离线引擎使用) - this.mTts.setParam(SpeechSynthesizer.PARAM_TTS_SPEECH_MODEL_FILE, mSampleDirPath + "/" - + SPEECH_FEMALE_MODEL_NAME); -// // 本地授权文件路径,如未设置将使用默认路径.设置临时授权文件路径,LICENCE_FILE_NAME请替换成临时授权文件的实际路径,仅在使用临时license文件时需要进行设置,如果在[应用管理]中开通了正式离线授权,不需要设置该参数,建议将该行代码删除(离线引擎) -// // 如果合成结果出现临时授权文件将要到期的提示,说明使用了临时授权文件,请删除临时授权即可。 -// this.mTts.setParam(SpeechSynthesizer.PARAM_TTS_LICENCE_FILE, mSampleDirPath + "/" -// + LICENSE_FILE_NAME); - // 请替换为语音开发者平台上注册应用得到的App ID (离线授权) - this.mTts.setAppId("6079582"/*这里只是为了让Demo运行使用的APPID,请替换成自己的id。*/); - // 请替换为语音开发者平台注册应用得到的apikey和secretkey (在线授权) - this.mTts.setApiKey("8BEjRGmT6kvGcPzTmkq224MzlLzaMgKV", - "87YRjXyLT2PlPeGDonuHH5n1MrwvFLGm"/*这里只是为了让Demo正常运行使用APIKey,请替换成自己的APIKey*/); - // 发音人(在线引擎),可用参数为0,1,2,3。。。(服务器端会动态增加,各值含义参考文档,以文档说明为准。0--普通女声,1--普通男声,2--特别男声,3--情感男声。。。) - this.mTts.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0"); - // 设置Mix模式的合成策略 - this.mTts.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT); - // 授权检测接口(只是通过AuthInfo进行检验授权是否成功。) - // AuthInfo接口用于测试开发者是否成功申请了在线或者离线授权,如果测试授权成功了,可以删除AuthInfo部分的代码(该接口首次验证时比较耗时),不会影响正常使用(合成使用时SDK内部会自动验证授权) - AuthInfo authInfo = this.mTts.auth(TtsMode.MIX); - - if (authInfo.isSuccess()) { -// QLog.getLogger().d(dTAG, "baidu tts auth success" ); - } else { - String errorMsg = authInfo.getTtsError().getDetailMessage(); -// QLog.getLogger().d(dTAG, "baidu tts auth fail" ); - } - - // 初始化tts - mTts.initTts(TtsMode.MIX); -// // 加载离线英文资源(提供离线英文合成功能) -// int result = -// mSpeechSynthesizer.loadEnglishModel(mSampleDirPath + "/" + ENGLISH_TEXT_MODEL_NAME, mSampleDirPath -// + "/" + ENGLISH_SPEECH_FEMALE_MODEL_NAME); -// toPrint("loadEnglishModel result=" + result); - - //打印引擎信息和model基本信息 - printEngineInfo(); - } - /** - * 打印引擎so库版本号及基本信息和model文件的基本信息 - */ - private void printEngineInfo() { - QLog.getLogger().d(dTAG, "EngineVersioin=" + SynthesizerTool.getEngineVersion()); - QLog.getLogger().d(dTAG, "EngineInfo=" + SynthesizerTool.getEngineInfo()); -// String textModelInfo = SynthesizerTool.getModelInfo(mSampleDirPath + "/" + TEXT_MODEL_NAME); -// QLog.getLogger().d(dTAG, "textModelInfo=" + textModelInfo); -// String speechModelInfo = SynthesizerTool.getModelInfo(mSampleDirPath + "/" + SPEECH_FEMALE_MODEL_NAME); -// QLog.getLogger().d(dTAG, "speechModelInfo=" + speechModelInfo); - } - private boolean bdSpeaking = false; - class bdttsListener implements SpeechSynthesizerListener{ - - @Override - public void onSynthesizeStart(String s) { - - } - - @Override - public void onSynthesizeDataArrived(String s, byte[] bytes, int i) { - - } - - @Override - public void onSynthesizeFinish(String s) { - - } - - @Override - public void onSpeechStart(String s) { - bdSpeaking = true; - } - - @Override - public void onSpeechProgressChanged(String s, int i) { - - String spkS = s; - int progress = i; - bdSpeaking = lastSpeakWordLenght > i; -// QLog.getLogger().d(dTAG,"speaking: " + lastSpeakWord + ", length " + lastSpeakWordLenght +", progress is: " + i +",bdSpeaking: " +bdSpeaking); - - - } - - @Override - public void onSpeechFinish(String s) { - bdSpeaking = false; - } - - @Override - public void onError(String s, SpeechError speechError) { - bdSpeaking = false; - } - } - - private bdttsListener mTtsInitListener = new bdttsListener() ; - - - private int speekingLevel=0; - int sumSleep = 0; - int lastSpeakWordLenght = 0; - String lastSpeakWord =""; - public void speech(final String text,final int level){ -// if(!QiYouConstant.CAN_SPEAK)return; - - - - new Thread(){ - - @Override - public void run() { - while(bdSpeaking &&level <=speekingLevel && sumSleep < 5000 ){ - try { - Thread.sleep(1000); -// QLog.getLogger().d(dTAG,"speaking: waiting..... " + sumSleep); - sumSleep +=1000; - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - if (sumSleep > 0 || bdSpeaking &&level > speekingLevel){ - mTts.stop(); - } - sumSleep =0; -// bdSpeaking = false; - speekingLevel =level; - - mTts.speak(text); - lastSpeakWord = text; - lastSpeakWordLenght = text.length(); - }}.start(); - - } - - - public void stopSpeech(){ - - { -// mTts.pauseSpeaking(mTtsListener); - mTts.stop(); - } - } - public void resumeSpeech(){ - - { -// mTts.resumeSpeaking(mTtsListener); - mTts.resume(); - } - } - public boolean isSpeaking(){ - - return bdSpeaking; - } - - - void stopMts(){ -// mTts.stopSpeaking(mTtsListener); -//// // 閫?嚭鏃堕噴鏀捐繛鎺? -// mTts.destory(); - - mTts.stop(); - mTts.freeCustomResource(); - mTts.release(); - - } - - -//xunfei is below.... - - -/* - private SpeechSynthesizer mTts; - private Toast mToast; - private void initialSpeech(){ -// 请的应用的appid - SpeechUtility.getUtility(this.getApplicationContext()).setAppid("54769bf1"); - // 初始化合成对象 - mTts = new SpeechSynthesizer(this, mTtsInitListener); -// mToast = Toast.makeText(this,"",Toast.LENGTH_LONG); -} - - - private InitListener mTtsInitListener = new InitListener() { - - @Override - public void onInit(ISpeechModule arg0, int code) { -// Log.d(TAG, "InitListener init() code = " + code); - if (code == ErrorCode.SUCCESS) { - setParam(); - } -// mTts.startSpeaking("你", mTtsListener); -// speech("你好"); - } - }; - - - private SynthesizerListener mTtsListener = new SynthesizerListener.Stub() { - @Override - public void onBufferProgress(int progress) throws RemoteException { -// Log.d(TAG, "onBufferProgress :" + progress); -// showTip("onBufferProgress :" + progress); - } - - @Override - public void onCompleted(int code) throws RemoteException { -// Log.d(TAG, "onCompleted code =" + code); -// showTip("onCompleted code =" + code); - } - - @Override - public void onSpeakBegin() throws RemoteException { -// Log.d(TAG, "onSpeakBegin"); -// showTip("onSpeakBegin"); - } - - @Override - public void onSpeakPaused() throws RemoteException { -// Log.d(TAG, "onSpeakPaused."); -// showTip("onSpeakPaused."); - } - - @Override - public void onSpeakProgress(int progress) throws RemoteException { -// Log.d(TAG, "onSpeakProgress :" + progress); -// showTip("onSpeakProgress :" + progress); - } - - @Override - public void onSpeakResumed() throws RemoteException { -// Log.d(TAG, "onSpeakResumed."); -// showTip("onSpeakResumed"); - } - }; - - - - - private int speekingLevel=0; - - public void speech(final String text,final int level){ -// if(!QiYouConstant.CAN_SPEAK)return; - - new Thread(){ - - @Override - public void run() { - while(mTts.isSpeaking() &&level <=speekingLevel){ - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - speekingLevel =level; - mTts.startSpeaking(text, mTtsListener); - - }}.start(); - - } - - - public void stopSpeech(){ - - { -// mTts.pauseSpeaking(mTtsListener); - mTts.stopSpeaking(mTtsListener); - } - } - public void resumeSpeech(){ - - { - mTts.resumeSpeaking(mTtsListener); - } - } - public boolean isSpeaking(){ - - return mTts.isSpeaking(); - } - - private void setParam(){ - - // 设置引擎类型 - mTts.setParameter(SpeechConstant.ENGINE_TYPE, "local"); - // 设置发音人 - mTts.setParameter(SpeechSynthesizer.VOICE_NAME, ""); // 设置本地合成发音人 voicer为空,默认通过语音+界面指定发音人 - // 设置语速 - mTts.setParameter(SpeechSynthesizer.SPEED, "50"); - // 设置音调 - mTts.setParameter(SpeechSynthesizer.PITCH, "50"); - // 开始合成 - - - // 停止 - mTts.stopSpeaking(mTtsListener); - // 暂停播放 - mTts.pauseSpeaking(mTtsListener); - // 恢复播放 - mTts.resumeSpeaking(mTtsListener); - - } - */ - - - - - - - - - - - - - - - - - public void naviUI(Location loc,String msg){ - - if(! canSendLocation2UI)return; - - Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); -// broadcastIntent.setFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_NAVIFO_MSG,loc); - sendBroadcast(broadcastIntent); - } - - public HttpResponse httpExecute(String mUrl){ - - - return httpExecute(mUrl,this.getHttpClient()) ; - - } - - public HttpResponse httpExecute(String mUrl,HttpClient client){ - -// mUrl="https://addons.mozilla.org/zh-CN/firefox/extensions/bookmarks/"; - // QLog.getLogger().d(dTAG, "request http of url:" +mUrl); - URL url; - URI uri = null ; - try { - url = new URL(mUrl); - uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - - } - - - HttpGet httpget = new HttpGet(uri); - HttpResponse response; - try { - response = client.execute(httpget); - // QLog.getLogger().d(dTAG, " request http response status:" + response.getStatusLine().getStatusCode()); - return response; - } catch (ClientProtocolException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } catch (Exception e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - - /*catch(IllegalArgumentException e){ - Utils.logStackTrace(e, dTAG); - } catch(Exception e){ - Utils.logStackTrace(e, dTAG); - }*/ - - return null ; - - } - - public HttpResponse httpsExecute(String mUrl){ - return httpExecute(mUrl,sslClient(this.getHttpClient())) ; - - } - - - public HttpClient sslClient(HttpClient client) { - try { - X509TrustManager tm = new X509TrustManager() { - public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { - } - - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(null, new TrustManager[]{tm}, null); - SSLSocketFactory ssf = new MySSLSocketFactory(ctx); - ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - ClientConnectionManager ccm = client.getConnectionManager(); - SchemeRegistry sr = ccm.getSchemeRegistry(); - sr.register(new Scheme("https", ssf, 443)); - return new DefaultHttpClient(ccm, client.getParams()); - } catch (Exception ex) { - return null; - } - } - - - public class MySSLSocketFactory extends SSLSocketFactory { - SSLContext sslContext = SSLContext.getInstance("TLS"); - - public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sslContext.init(null, new TrustManager[] { tm }, null); - } - - public MySSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { - super(null); - sslContext = context; - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - - - - - - - - - - - /** - * km/h - * @return - */ - public float getAVS(){ - float avspeed = mStatistics==null?0:mStatistics.getAVS(); - avspeed =Float.isNaN(avspeed)||avspeed==0?15:avspeed; - return avspeed; - - } - /** - * m/s - * @return - */ - public float getRAVS(){ - float avSpeed=getAVS();///3600; e - avSpeed=avSpeed>0?avSpeed:20f; - avSpeed=avSpeed>40 ?40 :avSpeed; - avSpeed=avSpeed<18 ?18 :avSpeed; - avSpeed=avSpeed/3600*0.8f; - return avSpeed; - } - -// private static final String BASE_URL = "http://office:8080/qiyouji/"; - - private static AsyncHttpClient client;// = new AsyncHttpClient(); - - private static void initClient(Context context) { - if (client != null) { - return; - } - client = new AsyncHttpClient(); - /* PersistentCookieStore cookieStore = new PersistentCookieStore(context); - client.setCookieStore(cookieStore); - */ - - - } - - public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - try{ -// pirntCookies(); - // QLog.getLogger().d(dTAG, "request url is:" +getAbsoluteUrl(url)); - client.get(getAbsoluteUrl(url), params, responseHandler); - }catch(Exception er){ - Utils.logStackTrace(er, TAG); - } - } - public static void requestWeb(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - try{ -// pirntCookies(); - // QLog.getLogger().d(dTAG, "request url is:" +getAbsoluteUrl(url)); - client.get(getWebAbsoluteUrl(url), params, responseHandler); - }catch(Exception er){ - Utils.logStackTrace(er, TAG); - } - } - - - public static void get3dpart(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - try{ -// pirntCookies(); - // QLog.getLogger().d(dTAG, "request url is:" +getAbsoluteUrl(url)); - client.get(url, params, responseHandler); - }catch(Exception er){ - Utils.logStackTrace(er, TAG); - } - } - - - public static void getEle(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.get( url, params, responseHandler); - } - - public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - pirntCookies(); - client.post(getAbsoluteUrl(url), params, responseHandler); - } - - public static void post (Context context, String url, HttpEntity entity, String contentType, - ResponseHandlerInterface responseHandler){ - pirntCookies(); - client.post(context, getAbsoluteUrl(url), entity, contentType, responseHandler); - } - - public static HttpContext getHttpContext(){ - return client.getHttpContext(); - } - - private static String getAbsoluteUrl(String relativeUrl) { - return QiYouConstant.BASE_URL +"mb"+ relativeUrl; - } - - private static String getWebAbsoluteUrl(String relativeUrl) { - return QiYouConstant.BASE_URL +"/"+ relativeUrl; - } - - /*public static void setCookieStore(PersistentCookieStore myCookieStore) { - // TODO Auto-generated method stub - - client.setCookieStore(myCookieStore); - - }*/ - public void setAuth(){ - /* PersistentCookieStore myCookieStore = new PersistentCookieStore(this); - String name = "uk"; - String value = QiYouConstant.PV_ACCESS_TOKEN +"-c-d-x-"+QiYouConstant.PV_USER_ID; - BasicClientCookie clientCookie = new BasicClientCookie(name, value); - clientCookie.setComment(""); - clientCookie.setDomain("i7lv.com"); -// clientCookie.setExpiryDate(""); - clientCookie.setPath("//"); - myCookieStore.clear(); // if it is okay? - myCookieStore.addCookie(clientCookie); - client.setCookieStore(myCookieStore); - client.setBasicAuth(String.valueOf(QiYouConstant.PV_USER_ID), QiYouConstant.PV_ACCESS_TOKEN); - - for(Cookie c:myCookieStore.getCookies()){ - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue()); - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath()); - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts()); - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() ); - } - */ - - - String token;// =Utils.encodeBase64(QiYouConstant.PV_ACCESS_TOKEN); - token =QiYouConstant.PV_ACCESS_TOKEN; - client.setBasicAuth(String.valueOf(QiYouConstant.PV_USER_ID), token); -// QLog.getLogger().d(dTAG,TAG+ " Original token "+ QiYouConstant.PV_ACCESS_TOKEN ); -// QLog.getLogger().d(dTAG,TAG+ " encoded token "+ Utils.encodeBase64(QiYouConstant.PV_USER_ID+":"+QiYouConstant.PV_ACCESS_TOKEN) ); - } - - /*// 设置cookie - public static void synCookies(Context context, String url) { - CookieSyncManager.createInstance(context); - CookieManager cookieManager = CookieManager.getInstance(); - cookieManager.setCookie(url, "uid=1243432"); - CookieSyncManager.getInstance().sync(); - } - - // 清除cookie - private void removeCookie(Context context) { - CookieSyncManager.createInstance(context); - CookieManager cookieManager = CookieManager.getInstance(); - cookieManager.removeAllCookie(); - CookieSyncManager.getInstance().sync(); - }*/ - - - static void pirntCookies(){ -// AsyncHttpClient client = new AsyncHttpClient(); - HttpContext httpContext =QiYouApplication.getHttpContext();// QiyouRestClient.getHttpContext(); - - CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);//获取AsyncHttpClient中的CookieStore - QLog.getLogger().d(dTAG," begin to print cookies..............................."); - if(cookies!=null){ - for(Cookie c:cookies.getCookies()){ - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue()); - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath()); - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts()); - QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() ); - } - }else{ - QLog.getLogger().d(dTAG,"main before~~,cookies is null"); - } - QLog.getLogger().d(dTAG," print cookies end ..............................."); -/* //save cookie - PersistentCookieStore myCookieStore = new PersistentCookieStore(context); - QiyouRestClient.setCookieStore(myCookieStore); - - httpContext = QiyouRestClient.getHttpContext(); - cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE); - if(cookies!=null){ - QLog.getLogger().d(dTAG, "main after~~,cookies is not null"); - for(Cookie c:cookies.getCookies()){ - QLog.getLogger().d(dTAG,"main after ~~"+c.getName()+","+c.getValue()); - } - }else{ - QLog.getLogger().d(dTAG, "main after~~,cookies is null"); - } - */ - } - - /* - * - */ - public boolean isShowSlidTabs(){ - - return pref.getInt(QiYouConstant.PK_INT_TAB_SLICED, 0)<5; - } - - /* - * from a pause to a new pause. - */ - public void updateSlidTabs(){ - if(!isShowSlidTabs())return; - pe.putInt(QiYouConstant.PK_INT_TAB_SLICED,pref.getInt(QiYouConstant.PK_INT_TAB_SLICED, 0)+1 ); - pe.commit(); - - } - - - public int getExistNaviID(){ - return settings.getInt(QiYouConstant.PK_INT_LAST_UNFINISHED_NAVID,-1); - } - public int getExistNaviTrackID(){ - return settings.getInt(QiYouConstant.PK_INT_LAST_NAVI_TRACK,-1); - } - - public boolean isLastNaviExist(){ - return settings.getInt(QiYouConstant.PK_INT_LAST_UNFINISHED_NAVID,-1)>0 ; - } - public void setLastNavId(){ -// Editor pEditor = settings.edit(); - if(this.playBack)return; - - if(isNaving) { - pEditor.putInt(QiYouConstant.PK_INT_LAST_UNFINISHED_NAVID, naviTrackId); - - if(getRecordingTrack().getTrackBean().getTrackId()>0) - pEditor.putInt(QiYouConstant.PK_INT_LAST_NAVI_TRACK, getRecordingTrack().getTrackBean().getTrackId()); - - pEditor.commit(); - } - else{ - clearLastNavId(); - } - } - - public void setLastNavWeb(String cache){ -// Editor pEditor = settings.edit(); - if(this.playBack)return; - - if(isNaving) { - pEditor.putString(QiYouConstant.PK_INT_LAST_UNFINISHED_NAV_WEB, cache); - pEditor.commit(); - } - else{ - clearLastNavId(); - } - } - public String isLastNaviWeb(){ - return settings.getString(QiYouConstant.PK_INT_LAST_UNFINISHED_NAV_WEB,""); -// return TextUtils.isEmpty() ; - } - - - public void clearLastNavId(){ -// naviTrackId =-1; - pEditor.putInt(QiYouConstant.PK_INT_LAST_UNFINISHED_NAVID,-1); - pEditor.putString(QiYouConstant.PK_INT_LAST_UNFINISHED_NAV_WEB,""); - pEditor.commit(); - } - - - - - public int getCntKm() { -// return cntKm;\ - int km = (int) ((getRecordingTrack().getTrackBean().getDistance()+500)/1000); - km=km>0?km:1; - return km; - } - /*public void setCntKm(int cntKm) { - this.cntKm = cntKm; - }*/ - /* - public boolean getCityGEO(double lat, double lon){ - - getBdGEOadress(lat,lon); - // QLog.getLogger().d(dTAG,TAG+ String.format("lat: %s; lon: %s", lat,lon)); - int topWaiting=0; - while( GEOadress==null && ! isGEOerror && Utils.getNetworkType(this)!=QiYouConstant.NETWORK_TYPE_OFF) - try { - Thread.sleep(50); - topWaiting+=50; - QLog.getLogger().d(dTAG,TAG+" getCityGEO waiting for "+ topWaiting ); - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB/3 ) - { - Log.e(dTAG,TAG+" 获取地址超时."); - return false; - - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - return true; - - }*/ - - - int getuniqueId(){ - TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); - String imei=tm.getDeviceId(); - return TextUtils.isEmpty(imei)?-1:imei.hashCode(); - /*String simSerialNumber=tm.getSimSerialNumber(); - String androidId = android.provider.Settings.Secure.getString( - getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); - java.util.UUID deviceUuid =new java.util.UUID(androidId.hashCode(), ((long)imei.hashCode() << 32) | simSerialNumber.hashCode()); - String uniqueId = deviceUuid.toString();*/ - } - public void setPhoneId(){ - if(getPhoneId()==-1){ - pEditor.putInt(QiYouConstant.PK_INT_PHONEID,getuniqueId()); - pEditor.commit(); - } - } - - public int getPhoneId(){ - if( QiYouConstant.PV_INT_PHONEID==-1){ - QiYouConstant.PV_INT_PHONEID =settings.getInt(QiYouConstant.PK_INT_PHONEID,-1); - if(QiYouConstant.PV_INT_PHONEID>0){ - QiYouConstant.PV_INT_PHONEID=QiYouConstant.PV_INT_PHONEID*-1; - - } - } - return QiYouConstant.PV_INT_PHONEID; - - } - public boolean isLocationFinding=false; - public boolean canStopNetworkRequest(){ - return playBack ||! canRecord() &&! isRouting &&!isLocationFinding; - } - - - - public void sendSharedLocation(){ - - Intent serviceIntent = new Intent(this, LocationService2.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_UPLOAD_SHARED_LOCATION, 0); - startService(serviceIntent); - - QLog.getLogger().dLog(dTAG," send shared location service called.... "); - } - - - /*public boolean isAdmin(User_bean u){ - return QiYouConstant.DEVELOPER_MODE; - }*/ - - public boolean isAdmin(){ - return user.getUserbean().isPower(); - } - public ConcurrentHashMap getWebObjcache() { - if ( webObjcache == null){ - webObjcache = new ConcurrentHashMap(); - } - return webObjcache; - } - - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/QiYouConstant.java b/qy/src/main/java/com/qiyou/mb/android/QiYouConstant.java deleted file mode 100644 index 7f19d26..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/QiYouConstant.java +++ /dev/null @@ -1,409 +0,0 @@ -package com.qiyou.mb.android; - -public class QiYouConstant { - - public QiYouConstant() { - // TODO Auto-generated constructor stub - } -//public final static String BAIDU_API_KEY = "rI4GlZIZcFv5fB5qxotyrW9f"; - -//public final static String GG_API_KEY ="AIzaSyAnkLsprzJIbz_9EVOMcXvlPlxYtIfc0yg"; --office AIzaSyBygKp-tvHCRJFt19NJ2oyq0N6aCUCbKjU -public final static String GG_API_KEY ="AIzaSyBAey0WNbuvc2WeEbCOsGEpp2WW0iw77u0"; -//public final static String BASE_URL ="https://www.i7lv.net/";// "http://office:8080/qiyouji/"; //http://121.42.55.18:8080/qiyouji/ -public final static String BASE_URL ="https://www.i7lv.com/";//new website -public final static String BASE_MD_URL = BASE_URL;//+"upload/"; -public final static String BASE_STATIC_URL = BASE_URL +"staticmap/"; -public final static String TENCENT_APP_ID = "1104563148"; -// TODO Turn off when deploying. -public static boolean DEVELOPER_MODE = false; -//public final static float POINT_RD = 500; //used in route_fragment for checkWps -public static boolean PLAYBACK_CAN_RECORD = false ;//DEVELOPER_MODE ; - -public static boolean STRICT_MODE =false;//DEVELOPER_MODE; -// public static boolean STRICT_MODE =false; - -public static boolean LOG_LEVEL_DEBUG = DEVELOPER_MODE; -// public static boolean LOG_LEVEL_DEBUG =true; -public static boolean LOG_LEVEL_ERROR =DEVELOPER_MODE; -// public static boolean LOG_LEVEL_ERROR =true; -//public static String APP_DIR ="/qiyou/"; - -public static int MAX_UPLOAD_WPS_SIZE_PER_KM = 10; -public static boolean LOG_LEVEL_DEBUG_FILE = DEVELOPER_MODE;// LOG_LEVEL_DEBUG; -public static String APP_SD_DIR="qiyou"; -public static String SD_PATH ="/sdcard/qiyou/"; -public static String MEDIA_PATH =SD_PATH+"medias/"; -public static String MEDIA_FOLDER_PREFIX ="i7lv_No."; -public static String FOOTMARK_PATH =SD_PATH+"footmarks/"; -public static String PHOTO_CACHE_PATH =SD_PATH+"photoCache/"; -public static String EXP_PATH =SD_PATH+"exp/"; -public static String IMP_PATH =SD_PATH+"imp/"; -public static String CONTENT_SD_DIR=SD_PATH+"dbcontent/"; -public static String VERSION_ADDRESS ="download/version.xml"; -public static String GPX_CACHE_PATH= SD_PATH + "gpxcache/"; -public static String ACT_CACHE_PATH= SD_PATH + "actcache/"; -public static String BEAR_TEXT = "BEARS.txt"; -public static String STAT_TEXT = "STAT"; - - -public static boolean SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; -public static boolean SUPPORTS_HONEYCOMB = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB; -public static boolean SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; -public static boolean SUPPORTS_ECLAIR = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ECLAIR; - -//public static String NO_SAT_SIGNAL ="卫星定位中..."; - -public static String ACTION_NEW_FORCE_UPDATE ="com.qiyou.mb.android.receivers.FORCE_UPDATE_RECEIVER"; -public static String ACTION_NEW_LOCATION_CHANGED ="com.qiyou.mb.android.receivers.LOCATION_CHANGED"; -public static String ACTION_NEW_COARSE_LOCATION ="com.qiyou.mb.android.receivers.COARSE_LOCATION"; -public static String ACTION_NEW_WAYPOINTS_TO_SAVE ="com.qiyou.mb.android.receivers.NEW_WAY_POINTS"; -public static String ACTION_NEW_LOCATION_GETBACK ="com.qiyou.mb.android.receivers.locationgot"; -//public static String ACTION_CONNECTIVITY_CHANGE ="android.net.conn.CONNECTIVITY_CHANGE"; -public static String ACTION_CONNECTIVITY_CHANGE ="android.net.conn.CONNECTIVITY_CHANGE"; -public static String PROXIMITY_INTENT_ACTION ="com.qiyou.mb.android.receivers.ALERTPROXIMITY"; -public static String ACTION_SYNC_STATISTICS ="com.qiyou.mb.android.ACTION_SYNC_STATISTICS"; -public static String SPLITOR="*&^,"; -public static String SPLITOR_KEY="\\*\\&\\^,"; - - -public static String EXTRA_KEY_BOOT="android.intent.action.BOOT_COMPLETED"; - -public static String DB_TRACKS_ACTION ="db_tracks_action"; // track table action -public static String NEW_LOCATION ="new_location"; // track recording -public static String NEW_NAVIFO_MSG ="NEW_NAVIFO_MSG"; // track recording -public static String NEW_NAVIFO_DIST_PROGRESS ="DIST_PROGRESS"; // track recording -public static String NEW_GPX_TRACK ="new_gpx_track"; // track recording -public static String INITIAL_GPXS ="INITIAL_GPXS"; // track recording -public static String UPDATE_CATE_TRACK ="UPDATE_CATE_TRACK"; // track recording -public static String UPDATE_TRACK_AVSTATUS ="UPDATE_TRACK_AVSTATUS"; // track recording - -public static String STOP_LOCATION_SERVICE ="STOP_LOCATION_SERVICE"; // track recording -public static String UPDATE_TRACK_GEO ="update_trackGEO"; // track recording -public static String UPDATE_TRACK ="update_track"; // -public static String EXTR_KEY_FINISH_RECORDING ="FINISH_RECORDING"; // -public static String UPDATE_RECORDING_TRACK ="update_rec_track"; // - -public static String IMPORT_TRACK ="import_track"; // -public static String QUERY_TRACKS ="query_track"; // - -public static String SHARED_PREFERENCE_FILE = "SHARED_PREFERENCE_FILE"; -public static String APPLICATION_PREFERENCE_FILE = "APPLICATION_PREFERENCE_FILE"; - - -public static int MAX_TIME_UPDATE_DB =20*2000 ; -public static int MAX_GPS_SPAN =2000; -public static int TIME_FOR_LIGHT_LINE=MAX_GPS_SPAN/2*60*4; //当两点时间间隔大于此值,画细线 -public static int GPS_CODE_START_WPS_CNT_SKIP =15; -//public static int MAX_GPS_DISTANCE =1; -public static int MAX_GEO_TIME =QiYouConstant.MAX_GPS_SPAN*60;//MAX_TIME_UPDATE_DB*2;//MAX_GPS_SPAN*60*10; //120000;//max time between two GEO points in a track ,2 Minutes - -public static int MAX_TRACK_RESTORE_TIME =60000;//max time to restore a track from an restart of Application,1 Minutes -public static int MAX_GPS_OFF_TIME =1*60*1000;//max time GPS OFF time, then cancel the gps request. - -public static int MAX_WPS_UPDATE_DB =30 ; -//最长20秒 请求一次数据库更新 -//public static int MAX_TIME_UPDATE_DB =MAX_GPS_SPAN* MAX_WPS_UPDATE_DB ; - -public static int MAX_TIME_FORCE_UDATE =MAX_TIME_UPDATE_DB ; -public static int MAX_TIME_GET_TRACK_FROM_DB =6000; -//最多10个wp 请求一次数据库更新 - -//distance between 2 wp is long than 10 m, can only be inserted to db. -public static int MIN_WPS_DISTANCE_FACTOR =2; //minDistance = MIN_WPS_DISTANCE_FACTOR*MAX_GPS_SPAN*speed -public static String PK_INT_WPS_KEEP_PERCENT ="PK_WPS_KEEP_PERCENT"; -public static String PK_BL_WPS_SAVE_ALL ="PK_WPS_SAVE_ALL"; -public static boolean WPS_SAVE_ALL =false; - - -public static int WPS_SAVE_PERCENT_FACTOR =5; //(100/x)% to keep. example,100/5=20% keep, 80% drop -public static int WPS_ROAD_BEARING =15; //how much bearing change can be take as a roadwp,35,2; 25,4;...30,4;35,3;20,4 -public static int WPS_ROAD_BEAR_CNT =3; //at least how much continued bear points can be counted as a valid roadbear - -public static String PK_INT_WPS_CNT_BEAR ="PK_INT_WPS_CNT_BEAR"; -public static String PK_INT_ANGLE_BEAR ="PK_INT_ANGLE_BEAR"; -public static String PK_BL_ONE_SHOT_BEAR ="PK_BL_ONE_SHOT_BEAR"; -public static String PK_BL_SPEAK_KM ="PK_BL_SPEAK_KM"; -public static Boolean BL_SPEAK_KM =true; -public static Boolean BL_ONE_SHOT_BEAR =false; - -public static String PK_BL_SHARE_LOCATION ="PK_BL_SHARE_LOCATION"; -public static Boolean PV_BL_SHARE_LOCATION =false; -// public static int PV_LG_SHARE_INTERVAL=60000; -// public static String PK_LG_SHARE_INTERVAL="PK_LG_SHARE_INTERVAL"; - -// public static String PK_BL_LIVE_LOCATION ="PK_BL_LIVE_LOCATION"; -// public static Boolean PV_BL_LIVE_LOCATION =true; - public static String PK_INT_LIVE_SPAN ="PK_INT_LIVE_SPAN"; - public static int PV_INT_LIVE_SPAN =60000; //1 minute interval for sending out live locaiton - - -public static String PK_STR_SHARE_MSG ="PK_STR_SHARE_MSG"; -public static String PV_STR_SHARE_MSG =""; - - -public static String PK_ST_OPEN_ID ="PK_ST_OPEN_ID"; -public static String PV_OPEN_ID =""; - - -public static String PK_STR_ACCESS_TOKEN ="PK_STR_ACCESS_TOKEN"; -public static String PV_ACCESS_TOKEN =""; - - -public static String PK_L_EXPIRES_IN ="PK_L_EXPIRES_IN"; -public static long PV_EXPIRES_IN =0; - -public static String PK_INT_LIVE_TERM ="PK_INT_LIVE_TERM"; -public static int PV_INT_LIVE_TERM =8; //1 minute interval for sending out live locaiton - -public static String PK_BL_NAVI_VIBRATOR_ON="PK_BL_NAVI_VIBRATOR_ON"; -public static Boolean PV_BL_NAVI_VIBRATOR_ON=true; - - -//海拔差的采样个数 -public static int MAX_WPS_EVERAGE_ELE_CNT =5 ; - -public static int TRACK_STATUS_PENDING = 0; -public static int TRACK_STATUS_TRACKING = 1; -public static int TRACK_STATUS_PAUSED = 2; -public static int TRACK_STATUS_FINISHED =3; - -public static int TRACK_SPLIT_DIST =1000; -public static float ELED_FACTOR =0.01f; -//public static int TRACK_TYPE_BIKE =0; -//public static int TRACK_TYPE_WALK =1; -//public static int TRACK_TYPE_CAR =2; -//public static int TRACK_TYPE_COPY =3; -//public static int TRACK_TYPE_PIC =4; - -public static String EXTRA_KEY_NETWORK_LOCATION = "EXTRA_KEY_NETWORK_LOCATION"; -//public static String EXTRA_KEY_GEO = "EXTRA_KEY_GEO"; -public static String EXTRA_KEY_OFFMAP = "EXTRA_KEY_OFFMAP"; -public static String EXTRA_KEY_GET_CURRENT_CITY = "EXTRA_KEY_GET_CURRENT_CITY"; -//public static String EXTRA_KEY_CITY_NAME = "EXTRA_KEY_CITY_NAME"; -public static String EXTRA_KEY_FORCE_UPDATE = "EXTRA_KEY_FORCE_UPDATE"; -public static String EXTRA_KEY_FINISH_RECORDING = "EXTRA_KEY_FINISH_RECORDING"; -public static String EXTRA_KEY_FORCE_UPDATE_STAT = "EXTRA_KEY_FORCE_UPDATE_STAT"; -public static String EXTRA_KEY_TICK_UPDATE = "EXTRA_KEY_TICK_UPDATE"; -public static String EXTRA_KEY_START_GPS = "EXTRA_KEY_START_GPS"; -public static String EXTRA_KEY_STOP_GPS = "EXTRA_KEY_STOP_GPS"; - -public static String EXTRA_KEY_UPLOAD_SHARED_LOCATION = "EXTRA_KEY_UPLOAD_SHARED_LOCATION"; - - -public static String EXTRA_KEY_REFERENCE = "reference"; -public static String EXTRA_KEY_GET_CURRENT_TRACK_BY_ID = "GET_CURRENT_TRACK_BY_ID"; -public static String EXTRA_KEY_GET_TRACK_BY_ID = "GET_TRACK_BY_ID"; -public static String EXTRA_KEY_GET_TRACK_BY_IDS = "GET_TRACK_BY_IDS"; -public static String EXTRA_KEY_GET_MAX_AV_TRACK = "EXTRA_KEY_GET_MAX_AV_TRACK"; -public static String EXTRA_KEY_TRACK_GEOS = "EXTRA_KEY_TRACK_GEOS"; -public static String EXTRA_KEY_GET_STSTICS_TRACKS = "EXTRA_KEY_GET_STAT_TRACK"; -public static String EXTRA_KEY_UPDATE_WAYPOINTS = "EXTRA_KEY_UPDATE_WAYPOINTS"; -public static String EXTRA_KEY_UPDATE_SVRNOS = "EXTRA_KEY_UPDATE_SVRNOS"; -public static String EXTRA_KEY_UPDATE_MEDIAS = "EXTRA_KEY_UPDATE_MEDIAS"; -public static String EXTRA_KEY_IS_MD = "EXTRA_KEY_IS_MD"; -//public static String EXTRA_KEY_GET_TYPE_USED_LST = "EXTRA_KEY_GET_TYPE_USED_LST"; -public static String EXTRA_KEY_ID = "_id"; -public static String EXTRA_KEY_TYPE = "_type"; -public static String EXTRA_KEY_WEB_REQUEST = "EXTRA_KEY_WEB_REQUEST"; -public static String EXTRA_KEY_LOCATION = "location"; -public static String EXTRA_KEY_RADIUS = "radius"; -public static String EXTRA_KEY_TIME_STAMP = "time_stamp"; -public static String EXTRA_KEY_PAUSING_TIME = "pausingTime"; -public static String EXTRA_KEY_NO_LOCCATION_SIGNAL = "NO_SIGNAL"; -public static String EXTRA_KEY_DISTANCE = "distance"; -public static String EXTRA_KEY_LOG_SHELL = "LOG"; -public static String EXTRA_VALUE_LOG_SHELL = "logcat | grep com.qiyou"; - - public static String EXTRA_KEY_GENERAL = "EXTRA_KEY_GENERAL"; - public static String EXTRA_KEY_QCODEDESC = "EXTRA_KEY_QCODEDESC"; - public static String EXTRA_KEY_RESTMETHOD = "EXTRA_KEY_RESTMETHOD"; - public static String EXTRA_KEY_SVRID = "EXTRA_KEY_SVRID"; - //public static String EXTRA_KEY_FORCEREFRESH = "force_refresh"; -//public static String EXTRA_KEY_IN_BACKGROUND = "EXTRA_KEY_IN_BACKGROUND"; -public static String EXTRA_KEY_START_PROXI_ALERT="START_PROXI_ALERT"; -public static String EXTRA_KEY_START_NAVI="START_PROXI_NAVI"; - - -public static String GPX_NAME = "reference"; - - - -public static String SPLASH_OKAY_TO_QUIT ="com.qiyou.mb.android.splash_okay_to_quit"; -public static String EXTRA_KEY_SPLASH ="OKAY_TO_QUIT"; - - -public static String PK_STR_USER ="PK_STR_USER"; -public static String PV_STR_USER =""; - -//preference key -//public static String PK_INT_USER_ID ="PK_INT_USER_ID"; -//public static String PK_STR_USER_TITLE ="PK_STR_USER_TITLE"; -//public static String PK_STR_USER_PAIMING ="PK_STR_USER_PAIMING"; -//public static String PK_STR_USER_SCORE ="PK_STR_USER_SCORE"; -//public static String PK_STR_USER_ACCOUNT ="PK_STR_USER_ACCOUNT"; -public static String PK_STR_USER_NAME ="PK_STR_USER_NAME"; -//public static String PK_STR_USER_EMAIL ="PK_STR_USER_EMAIL"; -public static String PK_FLOAT_USER_WEIGHT ="PK_FLOAT_USER_WEIGHT"; -//public static String PK_STR_USER_PASSWD ="PK_STR_USER_PASSWD"; -public static String PK_INT_APP_CNT="PK_INT_APP_CNT"; -public static String PK_LAST_BBS_CATE = "PK_LAST_BBS_CATE"; -public static String PV_LAST_BBS_CATE = ""; -public static String PK_LONG_LAST_START ="PK_INT_LAST_START"; -public static String PK_LONG_LAST_QUIT ="PK_INT_LAST_QUIT"; -public static String PK_LONG_TRACK_MANULE_PAUSED ="PK_LONG_TRACK_MANULE_PAUSED"; -public static String PK_LONG_LAST_MANULE_PAUSED ="PK_LONG_LAST_MANULE_PAUSED"; -public static String PK_DOU_LAST_LAT="PK_INT_LAST_LAT"; -public static String PK_DOU_LAST_LON="PK_INT_LAST_LON"; -public static String PK_INT_LAST_UNFINISHED_TRACKID="PK_INT_LAST_UNFINISHED_TRACKID"; -public static String PK_INT_LAST_UNFINISHED_NAVID="PK_INT_LAST_UNFINISHED_NAVID"; -public static String PK_INT_LAST_UNFINISHED_NAV_WEB="PK_INT_LAST_UNFINISHED_NAV_WEB"; -public static String PK_INT_LAST_SYNC_TIME="PK_INT_LAST_SYNC_TIME"; - -public static String PK_INT_LAST_TRACKTYPE="PK_INT_LAST_TRACKTYPE"; -public static String PK_LONG_LAST_TRACK_START="PK_LONG_LAST_TRACK_START"; -public static String PK_INT_LAST_NAVI_TRACK="PK_INT_LAST_NAVI_TRACK"; -public static String PK_STR_CITY="PK_STR_CITY"; -public static String PK_INT_GPS_SPAN ="PK_INT_GPS_SPAN"; -public static String PK_INT_SPORTS_SPEAK_MODEL ="PK_INT_SPORTS_SPEAK_MODEL"; -public static String PK_INT_NAVI_SPEAK_MODEL ="PK_INT_NAVI_SPEAK_MODEL"; -/** - * 0 精简,1标准,2关闭 - */ -public static int PV_INT_SPORTS_SPEAK_MODEL =0; -/** - * 0 精简,1标准,2关闭 - */ -public static int PV_INT_NAVI_SPEAK_MODEL =0; -public static boolean CAN_SPEAK = true; -public static String PK_INT_TAB_SLICED ="PK_INT_TAB_SLICED"; - -public static String PK_INT_MAX_WPS_EVERAGE_ELE_CNT ="PK_INT_MAX_WPS_EVERAGE_ELE_CNT"; - - -public static String PK_BL_PLAYBACK_PAUSE_WITH_UI ="PK_BL_PLAYBACK_PAUSE_WITH_UI"; -public static String PK_BL_PLAYBACK_CAN_RECORD ="PK_BL_PLAYBACK_CAN_RECORD"; -public static String PK_INT_PLAYBACK_TIME_INTERVAL ="PK_INT_PLAYBACK_TIME_INTERVAL"; - -//used in location service. -public static String PK_LONG_SUM_PAUSE ="PK_LONG_SUM_PAUSE"; -public static String PK_LONG_SUM_OFFTIME ="PK_LONG_SUM_OFFTIME"; -public static String PK_LONG_SUM_OFFTIMEWP ="PK_LONG_SUM_OFFTIMEWP"; -public static String PK_LAST_OFFTIME ="PK_LAST_OFFTIME"; -public static String PK_LAST_PAUSED ="PK_LAST_PAUSED"; -public static String PK_LONG_SUMDIST ="PK_LONG_SUMDIST"; -public static String PK_INT_RECORDINGID="PK_INT_RECORDINGID"; -public static String PK_LONG_MINTIME="PK_MINTIME"; -public static String PK_FLOAT_LOCDIST="PK_LOCDIST"; -public static String PK_FLOAT_SPDIST="PK_SPDIST"; -public static String PK_INT_PHONEID="PK_INT_PHONEID"; -public static String PK_INT_SCREEN_HEIGHT ="PK_INT_SCREEN_HEIGHT"; -public static String PK_INT_SCREEN_WIDTH ="PK_INT_SCREEN_WIDTH"; -public static int PV_INT_PHONEID=-1; -public static int PV_INT_SCREEN_HEIGHT=-1; -public static int PV_INT_SCREEN_WIDTH=-1 ; -//public static String PV_USER_EMAIL =""; -public static int PV_USER_ID =-1; -public static int PV_RECORDINGID ; -//public static String PV_USER_ACCOUNT =""; -public static String PV_USER_NAME =""; -//public static String PV_USER_PASSWD ="QPASSWDI"; -public static float PV_USER_WEIGHT =70; -public static int PV_APP_CNT=0; -public static long PV_LONG_LAST_START =0; -public static long PV_LONG_LAST_QUIT =0; - -public static int PLAYBACK_TIME_INTERVAL =1000; - -public static String PK_BL_PLAYBACK_RECORD_SCREEN_OFF ="PK_BL_PLAYBACK_RECORD_SCREEN_OFF"; -public static Boolean PV_BL_PLAYBACK_PAUSE_WITH_UI =true; //can play or simulator navi when screen is off - -public static String PK_BL_SAVE_POWER ="PK_BL_SAVE_POWER"; -public static Boolean PV_BL_SAVE_POWER =true; //智能调节gps频率 - - - - - - -//public static boolean PV_PLAYBACK_RECORD_SCREEN_OFF =true; -//beijing tain an men geo -public static float PV_LAST_LAT=39.90960456049752f; -public static float PV_LAST_LON=116.3972282409668f ; -public static String PV_LAST_CITY="北京市" ; - -public static int WEB_PIC_SIZE =480; //PIC SIZE UPLOAD TO WEB -public static int MAP_PIC_SIZE =PV_INT_SCREEN_WIDTH/15;//40;//PIC SHOW ON MAP -public static int SUBNAIL_PIC_SIZE =PV_INT_SCREEN_WIDTH/2;//400;//PIC SHOW ON MAP -public final static int SMALLPIC_SIZE_COMPRESS_REATE=70; -public final static String WATER_MARKER_SIGN="爱骑驴"; - -//public static final int WP_MEDIA_TYPE_PIC =0; -//public static final int WP_MEDIA_TYPE_VOICE2 =2; -//public static final int WP_MEDIA_TYPE_VIDEO =3; - -public static final int GEO_COUNTRY =0; -public static final int GEO_PROVINCE =1; -public final static int GEO_CITY =2; -public static final int GEO_DISTRICT =3; -public static final int GEO_STREET =4; -public static final int GEO_STREETNO =5; -public static String EXTRA_KEY_POPULATE_GEOS ="EXTRA_KEY_POPULATE_GEOS"; -public static String EXTRA_KEY_NEW_GEOS ="EXTRA_KEY_NEW_GEOS"; - -public static final int NETWORK_TYPE_OFF=-1; -public static final int NETWORK_TYPE_MOBILE=0; -public static final int NETWORK_TYPE_WIFII=1; -public static boolean NETWORK_CONNECTED=false; -public static final String LOCATION_FORCE_UPDATE="FORCE_UPDATE"; -public static final String LOCATION_BD_LOC="BD_LOC"; -public static final String LOCATION_RD_LOC="ROADB_LOC"; - -public static final String LOCATION_MONITOR="LOCATION_MONITOR"; - - -public static final float MAX_ELE=8888F; - -public static String FOOT_MARK_TITLE_TEMPLATE="
%s

"; - -public static String FOOT_MARK_TURN_TEMPLATE="%s

"; - -public static long LAST_GEO_UPDATE=0; -public static long LAST_OFFMAP_UPDATE=0; -public static long LAST_WIFI_TIME=0; -public static String PK_LONG_LAST_OFFMAP_UPDATE="PK_LONG_LAST_OFFMAP_UPDATE"; - -public static String PK_STRING_SHOWING_GPX="PK_STRING_SHOWING_GPX"; - -public static String PK_BL_CAN_UPDATE_UI="PK_BL_CAN_UPDATE_UI"; - -public static String PK_LONG_LAST_WIFI_TIME="PK_LONG_LAST_WIFI_TIME"; -public static String PK_LONG_LAST_GEO_UPDATE="PK_LONG_LAST_GEO_UPDATE"; -public static boolean CAN_GEO_UPDATE =false;//System.currentTimeMillis() -LAST_GEO_UPDATE > GEO_UPDATE_INTERVAL*1000*60; -public static boolean CAN_OFFMAP_UPDATE =false;//System.currentTimeMillis() -LAST_GEO_UPDATE > GEO_UPDATE_INTERVAL*1000*60; -public static boolean CAN_WIFI_PROCESS =false; -//public static long TIME_SINCE_LAST_GEO_UPDATE=System.currentTimeMillis() -LAST_GEO_UPDATE ; -public static boolean NETWORK_LOCATION_FOR_GEO=false; -public static boolean NETWORK_LOCATION_FOR_LOCATION=false; - -public static boolean IS_PROCESSING_GEO_FOOTMARK=false; - -public static int TRACK_NUMBERS_IN_STATISTICS_CHART=10; - - -public static int WIFI_CONNECT_CHANGE_INTERVAL =1;//1分钟内不接受WIFI接入事件 -public static int OFFMAP_UPDATE_INTERVAL =10;//20分钟内不接受因网络变化发生的geo地图数据更新. -public static int GEO_UPDATE_INTERVAL =DEVELOPER_MODE?1:5;//10分钟内不接受因网络变化发生的geo地图数据更新. -public static boolean PROCESS_ALLTRACK_GEO_FOOTMARK= false;//DEVELOPER_MODE; -public static boolean IS_TEST_NAV=true;//DEVELOPER_MODE; - - - -public static String JSONOBJECT_KEY="jokey"; -public static String MSG_KEY="msgkey"; -public static String SIGN_KEY="signkey"; -public static String SIMPLE_KEY="simplekey"; - -public static String MAP_PIC_WATER_MARK_WORDS="快乐运动,爱骑驴 \n www.i7lv.com"; -public static String MAP_PIC_WATER_MARK_PIC=" "; - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/.gitignore b/qy/src/main/java/com/qiyou/mb/android/beans/.gitignore deleted file mode 100644 index ee4c926..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/test diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/Footmark.java b/qy/src/main/java/com/qiyou/mb/android/beans/Footmark.java deleted file mode 100644 index c7d90fa..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/Footmark.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.qiyou.mb.android.beans; - -import java.util.ArrayList; - -import android.text.TextUtils; -import android.util.Log; - -import com.google.gson.Gson; -import com.qiyou.mb.android.beans.basic.Footmark_bean; -import com.qiyou.mb.android.utils.Utils; - -public class Footmark { - public static String TAG ="com.qiyou.beans.footmark"; - public static String dTAG ="com.qiyou"; - public Footmark() { - // TODO Auto-generated constructor stub - } - - private ArrayList fbs; - private String comment; - private int trackId; - private String name; - private long time; - - - public Footmark(String jsonFm){ - Gson gson = new Gson(); - try{ - if(!TextUtils.isEmpty(jsonFm)){ - Footmark fm = gson.fromJson(jsonFm, Footmark.class); - fbs = fm.getFbs(); - trackId=fm.getTrackId(); - name=fm.getName(); - time=fm.getTime(); - comment=fm.getComment(); - } - }catch(Exception e) { - Utils.logStackTrace(e, dTAG); - if(!TextUtils.isEmpty(jsonFm)){ - Log.e(dTAG,TAG + " Json to footmark error--------------as below json ----" ); - Log.e(dTAG ,TAG+ jsonFm ); - } - } - } - - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public ArrayList getFbs() { - return fbs; - } - - public void setFbs(ArrayList fbs) { - this.fbs = fbs; - } - - public int getTrackId() { - return trackId; - } - public void setTrackId(int trackId) { - this.trackId = trackId; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public long getTime() { - return time; - } - public void setTime(long time) { - this.time = time; - } - - public boolean toPdf(){ - - return true; - } - - public boolean tofile(){ - - return true; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/Group.java b/qy/src/main/java/com/qiyou/mb/android/beans/Group.java deleted file mode 100644 index 16f6cca..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/Group.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.qiyou.mb.android.beans; - -import java.util.ArrayList; - -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.Group_bean; - -public class Group { - - public Group() { - // TODO Auto-generated constructor stub - } - private ArrayList users; - private ArrayList activities; - private Group_bean group_bean; - - public boolean join(){ - return true; - } - - public boolean update(){ - return true; - } - - public boolean create(){ - return true; - } - - public boolean delete(){ - return true; - } - - - /** - * @return the users - */ - public ArrayList getUsers() { - return users; - } - /** - * @param users the users to set - */ - public void setUsers(ArrayList users) { - this.users = users; - } - /** - * @return the activities - */ - public ArrayList getActivities() { - return activities; - } - /** - * @param activities the activities to set - */ - public void setActivities(ArrayList activities) { - this.activities = activities; - } - /** - * @return the group_bean - */ - public Group_bean getGroup_bean() { - return group_bean; - } - /** - * @param group_bean the group_bean to set - */ - public void setGroup_bean(Group_bean group_bean) { - this.group_bean = group_bean; - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/Statistics.java b/qy/src/main/java/com/qiyou/mb/android/beans/Statistics.java deleted file mode 100644 index e1a0f45..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/Statistics.java +++ /dev/null @@ -1,431 +0,0 @@ -package com.qiyou.mb.android.beans; - -import java.util.ArrayList; -import java.util.HashMap; - -import com.qiyou.mb.android.beans.basic.BStatistics; -import com.qiyou.mb.android.beans.basic.CItem; -import com.qiyou.mb.android.beans.basic.StatTrack; -import com.qiyou.mb.android.beans.basic.Statics_bean; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.TypeStatistics; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.log.QLog; - -public class Statistics extends BStatistics { - public static String TAG ="com.qiyou.beans.Statistics"; - public static String dTAG ="com.qiyou"; - - - - - public void mergeTrack(Track track){ - if(track.getTrackBean().getAvStatus()==TrackAvStatus.ACTIVE){ - trackPlus( track); - return; - } - - //trackMinus(track); //when delete/inactive track,to reload the stats from db - - } - - - private void minusType(Integer typeToRemove,int trackId){ - if(typeToRemove>-1 &&statisticsTracks.get(typeToRemove)!=null){ //to remove from the old type list - statisticsTracks.get(typeToRemove).getSbs().remove(Integer.valueOf(trackId)); - cnt--; -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: statisticsTracks.get(location).getSbs().size()==0?:" +(statisticsTracks.get(typeToRemove).getSbs().size()==0)); - - Integer position =positionInTypeUsedLst(typeToRemove); - - if(statisticsTracks.get(typeToRemove).getSbs().size()==0){ - -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: before del getTypeUsedLst().size() ?:" + getTypeUsedLst().size()); -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: before del gStatisticsTracks.size() ?:" + statisticsTracks.size()); -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: type to delete,position to delete?:" + typeToRemove +","+positionInTypeUsedLst(typeToRemove)); - -// getTypeUsedLst().remove( new CItem(String.valueOf(typeToRemove),TrackType.valueOf(typeToRemove).toCHString())); - getTypeUsedLst().remove(getTypeUsedLst().get(position)); -// statisticsTracks.get(location).setStatTrack(new StatTrack()); - statisticsTracks.remove(typeToRemove); - -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: after del getTypeUsedLst().size() ?:" + getTypeUsedLst().size()); -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: after del gStatisticsTracks.size() ?:" + statisticsTracks.size()); - - }else if(position > 0 && getTypeUsedLst().get(position).getCnt()>1) { //sbs not blank - - getTypeUsedLst().get(position).setCnt(getTypeUsedLst().get(position).getCnt()-1); - } - } - } - - public void trackMinus(Track track){ - - Integer typeToRemove =track.getTrackBean().getType().toInt(); - int trackId=track.getTrackBean().getTrackId() ; - if(trackId<=0){ - return; - } - TypeStatistics stat =getStatisticsTracks().get(Integer.valueOf(typeToRemove)); - if(stat==null)return; - - minusType(typeToRemove,trackId); - - - //set last id - if(stat.getTrackIds().size()>0 && stat.getTrackIds().contains(Integer.valueOf(trackId)) && stat.getTrackIds().get(Integer.valueOf(trackId))!=null){ - - int miner =stat.getTrackIds().get(Integer.valueOf(trackId)); - int bigger =0; - for(int i:stat.getTrackIds().keySet()){ - if(i>trackId && trackId==stat.getTrackIds().get(Integer.valueOf(i))){ - bigger=i; - stat.getTrackIds().put(bigger, miner); - if(track.getTrackBean().getEndTime() ==lastTime) - lastTime=stat.getSbs().get(Integer.valueOf(bigger)).getEndTime(); - - break; - } - } - - - } - - - if(track.getTrackBean().getType()!=TrackType.GPX) - mergeTrackValues(stat ,track); - - stat.getSbs().remove(Integer.valueOf(trackId)); - - - - } - - public void trackPlus(Track track){ - if(track ==null || track.getTrackBean().getTrackId()==0)return; - int trackId=track.getTrackBean().getTrackId() ; - int type =track.getTrackBean().getType().toInt(); - - TypeStatistics stat =getStatisticsTracks().get(Integer.valueOf(type)); - QLog.getLogger().dLog(dTAG, TAG+" mergeTrack type " + track.getTrackBean().getType().toCHString()); - QLog.getLogger().dLog(dTAG, TAG+" mergeTrack Dist:trackId " + trackId); - QLog.getLogger().dLog(dTAG, TAG+" mergeTrack Dist: stat==null " + (stat==null)); - if(stat==null){ - stat = new TypeStatistics(100,track.getTrackBean().getStartTime(),type); - - } - - boolean isExist =stat.getSbs().get(Integer.valueOf(trackId))!=null; - -// QLog.getLogger().d(dTAG, TAG+" mergeTrack: isExist?" +isExist ); - - if(!isExist){ - - cnt++; - - Integer typeToRemove =-1; - for(Integer i:statisticsTracks.keySet()){ -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: type:" +TrackType.valueOf(i).toCHString() ); -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: track exist in type list?:" +statisticsTracks.get(i).getSbs().keySet().contains(Integer.valueOf(trackId)) ); - if(statisticsTracks.get(i).getSbs().keySet().contains(Integer.valueOf(trackId))){ - - stat.getSbs().put(trackId, statisticsTracks.get(i).getSbs().get(Integer.valueOf(trackId))); - - typeToRemove =Integer.valueOf(i); - break; - - } - - } -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: statisticsTracks.get(location)!=null?,location is" +typeToRemove+","+ (statisticsTracks.get(typeToRemove)!=null )); - - //in case track type changed from one type to another. - if(typeToRemove>-1 &&statisticsTracks.get(typeToRemove)!=null){ //to remove from the old type list - /*statisticsTracks.get(typeToRemove).getSbs().remove(Integer.valueOf(trackId)); - cnt--; - QLog.getLogger().d(dTAG, TAG+" MergeTrack: statisticsTracks.get(location).getSbs().size()==0?:" +(statisticsTracks.get(typeToRemove).getSbs().size()==0)); - - Integer position =positionInTypeUsedLst(typeToRemove); - - if(statisticsTracks.get(typeToRemove).getSbs().size()==0){ - - QLog.getLogger().d(dTAG, TAG+" MergeTrack: before del getTypeUsedLst().size() ?:" + getTypeUsedLst().size()); - QLog.getLogger().d(dTAG, TAG+" MergeTrack: before del gStatisticsTracks.size() ?:" + statisticsTracks.size()); - - QLog.getLogger().d(dTAG, TAG+" MergeTrack: type to delete,position to delete?:" + typeToRemove +","+positionInTypeUsedLst(typeToRemove)); - -// getTypeUsedLst().remove( new CItem(String.valueOf(typeToRemove),TrackType.valueOf(typeToRemove).toCHString())); - getTypeUsedLst().remove(getTypeUsedLst().get(position)); -// statisticsTracks.get(location).setStatTrack(new StatTrack()); - statisticsTracks.remove(typeToRemove); - - QLog.getLogger().d(dTAG, TAG+" MergeTrack: after del getTypeUsedLst().size() ?:" + getTypeUsedLst().size()); - QLog.getLogger().d(dTAG, TAG+" MergeTrack: after del gStatisticsTracks.size() ?:" + statisticsTracks.size()); - - }else if(getTypeUsedLst().get(position).getCnt()>1) { //sbs not blank - - getTypeUsedLst().get(position).setCnt(getTypeUsedLst().get(position).getCnt()-1); - }*/ - minusType(typeToRemove,trackId); - }else{ //just a new one. - - - } - - if(type!=TrackType.GPX.toInt()) { - - if(!typeExitsInTypeUsedLst(type)){ - CItem c =new CItem(String.valueOf(track.getTrackBean().getType().toInt()),track.getTrackBean().getType().toCHString()); - c.setCnt(1); - // if(typeUsedLst==null || !typeExitsInTypeUsedLst(track.getTrackBean().getType().toInt())){ - getTypeUsedLst().add(c); - // } - - if(firstTime==0 ||firstTime>0 && firstTime0 && !stat.getTrackIds().contains(Integer.valueOf(trackId))){ - - int max=0; - for(int i:stat.getTrackIds().keySet()){ - max=maxmax){ - stat.getTrackIds().put(trackId, max); - QLog.getLogger().dLog(dTAG, TAG+" 1 set last id: trackId>max:" + (trackId>max)); - } - - - } - - } - -// if(stat.getSbs().get(Integer.valueOf(trackId))==null){ - - - -// stat.getStatTrack().mergeTrack(track); - if(track.getTrackBean().getType()!=TrackType.GPX) - mergeTrackValues(stat ,track); - - if(!stat.getTrackIds().containsKey(Integer.valueOf(trackId))){ - QLog.getLogger().dLog(dTAG, TAG+"2 current track id:" + trackId); - QLog.getLogger().dLog(dTAG, TAG+"2 last track id:" + getLastTrackId()); - stat.getTrackIds().put(trackId, getLastTrackId()); - - } - - this.setLastTrackId(trackId); - - stat.getSbs().put(trackId, new Statics_bean(track.getTrackBean())); -// setMaxAvStat(stat.getStatTrack()); - if(lastTime==0 ||lastTime>0 && lastTime>changedCates,Boolean isNew){ - categoryList= getCategoryList(); - ArrayList cates; - boolean hasChg = false; - for(Integer trackId: changedCates.keySet()){ - cates =changedCates.get(trackId); - if(cates==null)continue; - if(trackId==0 && isNew){ - - } - - - for(String cate:categoryList.keySet()){ - if(!isNew &&cates.contains(cate)){ //del -// QLog.getLogger().d(dTAG, " .................removing cates trackId ?"+trackId); - categoryList.get(cate).remove(Integer.valueOf(trackId)); - hasChg=true; - continue; - } - if(isNew&&cates.contains(cate)){ - if(!categoryList.get(cate).contains(Integer.valueOf(trackId)) ||trackId==0){ - if(!categoryList.get(cate).contains(Integer.valueOf(trackId))) - categoryList.get(cate).add(Integer.valueOf(trackId)); - hasChg=true; -// QLog.getLogger().d(dTAG, " .................adding cates trackId ?"+trackId); - } - } - - } - } - return hasChg; -} - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/Track.java b/qy/src/main/java/com/qiyou/mb/android/beans/Track.java deleted file mode 100644 index 2284a20..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/Track.java +++ /dev/null @@ -1,2509 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.beans; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.alternativevision.gpx.beans.GPX; - -import android.location.Location; -import android.text.TextUtils; -import android.util.Log; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.beans.basic.Media; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.mediaStatus; -import com.qiyou.mb.android.utils.enums.mediaType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; -//import org.alternativevision.gpx.GPXParser; -//import com.baidu.a.a.a.a; - -/** - * @author mwang - * - *一次骑行/运动记录 - */ -public class Track { - public static String TAG ="com.qiyou.beans.Track"; - public static String dTAG ="com.qiyou"; - private Track_bean tb; - private Waypoint _lastWp; - private Waypoint _startWp; - private String _lastWpJson; - private String _startWpJson; - private StringBuffer wpsJson ; //wps 原始 Json ;和数据库里保存的track content字段内容一致. -// private Waypoint _lastRoadBear; - private String _lastRbJson=""; - private StringBuffer _roadBook = new StringBuffer(); - private StringBuffer _rdWpsJson = new StringBuffer(); - private StringBuffer _mdWpsJson = new StringBuffer(); -// public ArrayList roadWps = new ArrayList(); - private String _maxDistWpJson; - private Waypoint _maxDistWp; - private double maxR; - public StringBuffer newMdWpsJson = new StringBuffer(); - - public Track() - { - tb = new Track_bean(); - tb.setUserid(QiYouConstant.PV_USER_ID); - } - - public Track(String jsonTrack){ - Gson gson = new Gson(); - try{ - tb = gson.fromJson(jsonTrack, Track_bean.class); - }catch(Exception e) - { - Utils.logStackTrace(e, dTAG); - } - } - public Track(Track_bean track_bean) - { - if (track_bean == null) - { - this.tb = new Track_bean(); - this.tb.setUserid(QiYouConstant.PV_USER_ID); - return; - } - - this.tb = track_bean; - this._startWp = this.tb.getStartWp(); - this._lastWp = this.tb.getLastWp(); - this._maxDistWp = this.tb.getMaxDistWp(); - -// QLog.getLogger().d(dTAG, " mtrack_bean startwp: "+mTrack_bean.getStartWp().toString()); -// QLog.getLogger().d(dTAG, " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); -// QLog.getLogger().d(dTAG, " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); -// getTrackBean().getTrkseg().clear(); -// QLog.getLogger().d(dTAG, " loaded track is"+this.toGsonString()); - - - } -// public Track(GPX gpx){ -// pareseGpx( gpx); -// } - - public Track(int trackId, boolean isAssembleContent,String rdWpsJson,String mdWpsJson){ - getTrackBean().setTrackId(trackId); - if(isAssembleContent) - assemblyContent(); - if(TextUtils.isEmpty(rdWpsJson)){ - assemblyBearContent(); - } - pareseTrack(null, null, rdWpsJson, mdWpsJson); - - } - - public Track(int trackId,String jsonTrack, String jsonWps,String rdWpsJson,String mdWpsJson){ - getTrackBean().setTrackId(trackId); - if(TextUtils.isEmpty(rdWpsJson)){ - assemblyBearContent(); - } - pareseTrack(jsonTrack, jsonWps, rdWpsJson, mdWpsJson); - - } - /* - * jsonTrack can be null - */ - public Track(String jsonTrack, String jsonWps,String rdWpsJson,String mdWpsJson){ - - pareseTrack(jsonTrack, jsonWps, rdWpsJson, mdWpsJson); - - } - - void pareseTrack(String jsonTrack, String jsonWps,String rdWpsJson,String mdWpsJson){ - Gson gson = new Gson(); - try{ - if(!TextUtils.isEmpty(jsonTrack)){ - tb = gson.fromJson(jsonTrack, Track_bean.class); - return; - } - else getTrackBean();//tb = new Track_bean(); - String json=""; - //检查 json 格式,应该为[{...},{...}]格式 -// wpsJson = new StringBuffer(); -// wpsJson.append(jsonWps); //put it before convert to wps, in case failed, then recovery track will miss existed wps in db. - if(!TextUtils.isEmpty(jsonWps)){ -// json= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", ""); - json=getCleanJson(jsonWps); - - wpsJson = new StringBuffer(); - wpsJson.append(json); //put it before convert to wps, in case failed, then recovery track will miss existed wps in db. - // tb.setTrksegs(wps); - if(!json.startsWith("[")) - json ="["+json ; - if(!json.endsWith("]")){ - json =json+"]"; - } - tb.setTrksegs(getWPS(gson,json)); - wpsJson=new StringBuffer(); //TODO check if it will cause : //put it before convert to wps, in case failed, then recovery track will miss existed wps in db. - } - if(!TextUtils.isEmpty(rdWpsJson)){ -// json= rdWpsJson.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", "");; - json=getCleanJson(rdWpsJson); -// json= rdWpsJson.replace(" ",""); - if(!json.startsWith("[")) - json ="["+json ; - if(!json.endsWith("]")){ - json =json+"]"; - } -// roadWps =getWPS(gson,jsonWps); - tb.setRoadWps(getWPS(gson,json)); - } - if(!TextUtils.isEmpty(mdWpsJson) && mdWpsJson.length()>1){ -// _mdWpsJson.append(mdWpsJson); -// json= mdWpsJson.replace("[","").replace("]", "").replace(" ",""); - json= mdWpsJson.replace(" ","").replace("}{", "},{").replace("null", "").replace("}]{" ,"},{").replace("[]" ,""); - if(!json.startsWith("[")) - json ="["+json ; - if(!json.endsWith("]")){ - json =json+"]"; - } -// QLog.getLogger().d(dTAG, TAG+" setMdWps: "+ tb.getTrackId() +", track status is" +tb.getStatus()); - tb.setMdWps(getWPS(gson,json)); - } - - - - - //wpsJson 初始化,为继续采集/更新gps位置信息(wps)做准备. -// wpsJson = new StringBuffer(); -// wpsJson.append(jsonWps); - }catch(Exception e) - { - Utils.logStackTrace(e, dTAG); - if(!TextUtils.isEmpty(jsonTrack)){ - Log.e(dTAG,TAG + " Json to track error--------------as below jsonTrack----" ); - Log.e(dTAG ,TAG+ jsonTrack ); - } - if(!TextUtils.isEmpty(jsonWps)){ - Log.e(dTAG ,TAG+"below is wps jsonWps---------------"); - Log.e(dTAG ,TAG+ jsonWps ); - } - - - } - } - - String getCleanJson(String json){ - - json = json.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", ""); -// json = json.replace(" ","").replace("}{", "},{").replace("null", ""); -// json ="["+json+"]"; - return json; - } - /*CopyOnWriteArrayList getWPS(Gson gson, String jsonWps) throws Exception{ - CopyOnWriteArrayList wps = new CopyOnWriteArrayList(); - try{ - Type type = new TypeToken>(){}.getType(); - wps = gson.fromJson(jsonWps,type); - }catch(Exception e) - { - //throw e; - Log.e(dTAG,TAG+"Track "+ tb.getTrackId() +" getWPS error: "+ jsonWps); - wps =buildWps(jsonWps); - - } -// dwps =buildWps(jsonWps); - return wps; - - - }*/ - - ArrayList getWPS(Gson gson, String jsonWps) throws Exception{ - ArrayList wps = new ArrayList(); - try{ - Type type = new TypeToken< ArrayList>(){}.getType(); - wps = gson.fromJson(jsonWps,type); - }catch(Exception e) - { - //throw e; - Log.e(dTAG,TAG+"Track "+ tb.getTrackId() +" getWPS error: "+ jsonWps); - wps =buildWps(jsonWps); - - } -// dwps =buildWps(jsonWps); - return wps; - - - } - - /*CopyOnWriteArrayList buildWps(String jsonWps) { - - CopyOnWriteArrayList wps = new CopyOnWriteArrayList(); -// jsonWps= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{"); - jsonWps= jsonWps.replace(" ","").replace("}{", "},{"); - String[] wpsS = jsonWps.split("\\}\\,\\{"); - String tmp = null; - for(String json : wpsS){ - tmp = json; - json =json.endsWith("}")?json: json.endsWith("},")?json:json+"}"; - json =json.startsWith("[")?json.substring(1,json.length()):json.endsWith("]") ?json.substring(0,json.length()-1):json; - json =json.startsWith("{")?json:json.startsWith(",{")?json:"{"+json; - try{ -// tmp = json; - wps.add( new Waypoint(json).getWb()); - } - catch (Exception e){ - Log.e(dTAG,TAG+ " buildWps error for json: "+ tmp); - Log.e(dTAG,TAG+ " Track "+ tb.getTrackId() +" buildWps error: "+ json); - Utils.logStackTrace(e, TAG); - Log.e(dTAG,e.getLocalizedMessage()); - } - - } - return wps; - }*/ - - - ArrayList buildWps(String jsonWps) { - - ArrayList wps = new ArrayList(); -// jsonWps= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{"); - jsonWps= jsonWps.replace(" ","").replace("}{", "},{"); - String[] wpsS = jsonWps.split("\\}\\,\\{"); - String tmp = null; - for(String json : wpsS){ - tmp = json; - json =json.endsWith("}")?json: json.endsWith("},")?json:json+"}"; - json =json.startsWith("[")?json.substring(1,json.length()):json.endsWith("]") ?json.substring(0,json.length()-1):json; - json =json.startsWith("{")?json:json.startsWith(",{")?json:"{"+json; - try{ -// tmp = json; - wps.add( new Waypoint(json).getWb()); - } - catch (Exception e){ - Log.e(dTAG,TAG+ " buildWps error for json: "+ tmp); - Log.e(dTAG,TAG+ " Track "+ tb.getTrackId() +" buildWps error: "+ json); - Utils.logStackTrace(e, TAG); - Log.e(dTAG,e.getLocalizedMessage()); - } - - } - return wps; - } - - - public static Track newInstance(String gpxFile){ -// GPX gpx=Utils.pareseGpx(gpxFile); -// Track tr = new Track(Utils.pareseGpx(gpxFile)); -// tr.getTrackBean().setSrc(gpxFile); - - Track tr = new Track(); - /*if(tr.pareseGpx(gpx)){ - tr.getTrackBean().setSrc(gpxFile); - return tr; - }else return null;*/ - if(tr.pareseGpx(gpxFile)){ - return tr; - }else return null; - - } - public boolean pareseGpx(String gpxFileName){ -// public boolean pareseGpx(GPX gpx){ - try{ - - long t1 =System.currentTimeMillis(); - - GPX gpx=Utils.pareseGpx(gpxFileName); - long t2 =System.currentTimeMillis(); - // QLog.getLogger().d(dTAG, "pares gpx time 1: "+ Utils.getTimeCnt(t2-t1, true)); - if(gpx==null)return false; - org.alternativevision.gpx.beans.Track gpxTr = null; - while(gpx.getTracks().iterator().hasNext()){ - gpxTr =gpx.getTracks().iterator().next(); - if(gpxTr!=null) - break; //support only one track,currently. - } - if(gpxTr==null)return false; - - - tb =new Track_bean(); - tb.setCreator(gpx.getCreator());//gpx.getCreator()); - tb.setCreatTime(System.currentTimeMillis()); - tb.setName(gpxTr.getName()); - tb.setComment(gpxTr.getComment()); - tb.setDescription(gpxTr.getDescription()); - tb.setType(TrackType.GPX); - tb.setSrc(gpxFileName); - long t3 =System.currentTimeMillis(); - // QLog.getLogger().d(dTAG, "pares gpx time 2: "+ Utils.getTimeCnt(t3-t2, true)); - ArrayList gpxWps = gpxTr.getTrackPoints(); - Waypoint lastwp=null; - float dist=0f; - long sumdist=0; - float eDist=0f; - final float avSpeed=20f/3600f;//米/毫秒 - long lasttime=0; - for(org.alternativevision.gpx.beans.Waypoint gpxWp:gpxWps){ - Waypoint wp = new Waypoint(); - - wp.getWb().setDesc(gpxWp.getDescription()); - if(gpxWp.getLatitude()!=null) - wp.getWb().setLatitude( (gpxWp.getLatitude().floatValue())); - if(gpxWp.getLongitude()!=null) - wp.getWb().setLongitude( (gpxWp.getLongitude().floatValue())); - wp.getWb().setComment(gpxWp.getComment()); - if(gpxWp.getElevation()!=null) - wp.getWb().setElevation(gpxWp.getElevation().floatValue()); - if(gpxWp.getSpeed()!=null) - wp.getWb().setSpeed(gpxWp.getSpeed().floatValue()*3.6f); - if(gpxWp.getTime()!=null){ - if(gpxWp.getTime().getTime()>0) - wp.getWb().setTime(gpxWp.getTime().getTime()); - else{ - - long time_interval =(long)(dist/avSpeed); - // QLog.getLogger().d(dTAG,TAG+" interval is "+time_interval); - lasttime=lasttime>0?lasttime:System.currentTimeMillis(); - wp.getWb().setTime(lasttime+time_interval); - } - } - - if(lastwp!=null){ - dist =(float) Utils.getDistanceFromXtoY(wp.getWb().getLatitude(), wp.getWb().getLongitude(), lastwp.getWb().getLatitude(), lastwp.getWb().getLongitude()); - sumdist+=dist; - eDist=wp.getWb().getElevation()-lastwp.getWb().getElevation(); - lasttime=wp.getWb().getTime(); - } - - wp.getWb().setDistance(dist); - wp.getWb().setSumDist(sumdist); - wp.getWb().setEled(eDist); - - String gPics=gpxWp.getPics(); - if(!TextUtils.isEmpty(gPics)){ - String gpxPath=gpxFileName.substring(0,gpxFileName.lastIndexOf("/")+1); - - String[] pics; - if(gPics.contains(",")) - pics = gPics.split(","); - else if(gPics.contains(";")){ - pics = gPics.split(";"); - }else - pics = gPics.split(","); - - if(pics!=null && pics.length>0){ - for(String url :pics){ - this.setMd(gpxPath+url, null, mediaType.PIC); - // QLog.getLogger().d(dTAG,TAG+" added PIC to gpxTrack \n "+ gpxPath+url); - } - } - } - setLastWp( wp); - - /*_lastWpJson=wp.toJsonWp(); - if( setLastWp( wp) ){ - if (TextUtils.isEmpty(_startWpJson ) || wpsJson ==null){ - _startWpJson = _lastWpJson; - wpsJson = new StringBuffer(); - } - - wpsJson.append(_lastWpJson); - wpsJson.append(","); - }*/ - - lastwp =wp; - } - - - getJsonWps().append(wps2json(tb.getTrkseg())); - - long t4 =System.currentTimeMillis(); - // QLog.getLogger().d(dTAG, "pares gpx time 3: "+ Utils.getTimeCnt(t4-t3, true)); - if(_maxDistWp!=null){ - _maxDistWp.getWb().setTurnFlag(wpFlag.MAXR); - setLastRoadBear(_maxDistWp); - // QLog.getLogger().d(dTAG,TAG+" set marR WP to the roadbear \n "+ _maxDistWp.toString()); - } - - if(_lastWp!=null){ - _lastWp.getWb().setTurnFlag(wpFlag.END); - setLastRoadBear(_lastWp); - // QLog.getLogger().d(dTAG,TAG+" set last WP to the roadbear \n "+ _lastWp.toString()); - } - setBearWps(tb.getRoadWps()); - - long t5 =System.currentTimeMillis(); - - // QLog.getLogger().d(dTAG, "pares gpx time 4: "+ Utils.getTimeCnt(t5-t4, true)); - }catch(Exception e) - { - Utils.logStackTrace(e, dTAG); - return false; - } - return true; - } - - public boolean mergeTrack(int trackId){ - - - Utils.getContentPah(trackId); - StringBuffer wpsJson; - if(trackId<=0) - return false; - else{ - wpsJson=new StringBuffer(); - try { - - wpsJson.append(Utils.readSDFile(getContentPah())); - } catch (IOException e) { - Utils.logStackTrace(e, TAG); - } - } - - String json=wpsJson.toString(); -// CopyOnWriteArrayList inWps = null; - ArrayList inWps = null; - if(!TextUtils.isEmpty(json)){ - json=getCleanJson(json); - if(!json.startsWith("[")) - json ="["+json ; - if(!json.endsWith("]")){ - json =json+"]"; - } - try { - inWps = getWPS( new Gson(),json); - } catch (Exception e) { - Utils.logStackTrace(e, dTAG); - if(!TextUtils.isEmpty(json)){ - Log.e(dTAG ,TAG+" below is wps jsonWps---------------"); - Log.e(dTAG ,TAG+ json ); - } - } - } - - Waypoint wp; - float oDist=tb.getDistance(); - for(Waypoint_bean wb:inWps){ - wb.setSumDist(wb.getSumDist()+oDist); - wp=new Waypoint(); - wp.setWb(wb); - this.setLastWp(wp); - wpsJson.append(wp.toString()); - wpsJson.append(","); - } - -// return QiYouConstant.CONTENT_SD_DIR + getTrackBean().getTrackId()+".txt"; - - - - - return true; - } - - public boolean mergeTrack(Track mTrack){ - if(mTrack==null)return false; - - Waypoint wp; - float oDist=tb.getDistance(); - for(Waypoint_bean wb:mTrack.getTrackBean().getTrkseg()){ - wb.setSumDist(wb.getSumDist()+oDist); - wp=new Waypoint(); - wp.setWb(wb); - this.setLastWp(wp); - } - wpsJson.append(mTrack.getJsonWps()); - return true; - } - - - /** - * @return the tb - */ - public Track_bean getTrackBean() { - if(tb ==null) tb = new Track_bean(); - return tb; - } - - /** - * @param tb the tb to set - */ - public void setTrackBean(Track_bean tb) { - this.tb = tb; - } - - /* - * return string generated by Gson for the referenced track_bean - */ - public String toGsonString() - { -// long bfdbTime = System.currentTimeMillis(); - String strwb =""; - // if(null != tb.getNumber()) - { - Gson gson = new Gson(); - try{ - strwb = gson.toJson(tb); - /* if(QiYouConstant.DEVELOPER_MODE) - { - QLog.getLogger().d(dTAG ,TAG+" 准备 track to json 耗时: " +String.valueOf((System.currentTimeMillis()-bfdbTime)) + "毫秒"); - - }*/ - }catch(Exception e) - { - - Utils.logStackTrace(e, dTAG); - } - - } - // Log.e(TAG,strwb); - return strwb; - } - - /** - * Returns a JSON String representation of referenced track_bean. - */ - @Override - public String toString() { - return toGsonString(); - /*StringBuffer sb = new StringBuffer(); - sb.append("{"); - sb.append("name:"+tb.getName()+","); - sb.append("cmt:" + tb.getComment() + ","); - sb.append("desc"+tb.getDescription() + ","); - sb.append("src:"+tb.getSrc() +","); - sb.append("number:"+tb.getNumber()+ ","); - sb.append("type:"+tb.getType()+ ","); - sb.append("trkseg:"); - sb.append("["); - ArrayList wplst =tb.getTrkseg(); - if(null !=wplst ) - for(Waypoint wp:wplst) - { - sb.append(wp.toString()); - } - sb.append("]"); - sb.append("}"); - //return sb.toString(); - */ - - } - - public String toGpxString() - { - - - return null; - } - - /** - * @return the lastWp - */ - public Waypoint getLastWp() { - return _lastWp; - } - - - - /** - * add new waypoint to the track * - * @param lastWp the lastWp to set - * - * return false when the wp is null or not a new wp. - */ - public boolean setLastWp(Waypoint lastWp) { - if(lastWp == null ||lastWp.getWb().getTime()==0)return false; - -// if(lastWp.getWb().getTime()_lastWp.getWb().getTime()){// ||QiYouConstant.DEVELOPER_MODE){ - _lastWp = lastWp; - tb.setLastWp(_lastWp); - tb.getTrkseg().add(_lastWp.getWb()); -// if(lastWp.getWb().getDistance()>=0) -// tb.setDistance(tb.getDistance()+lastWp.getWb().getDistance()); //累加总里程, Meter - - if(lastWp.getWb().getSumDist()>tb.getDistance()) - tb.setDistance(lastWp.getWb().getSumDist()); //累加总里程, Meter - - tb.setPauseTime(tb.getPauseTime()+lastWp.getWb().getPauseTime());//累加暂停时间 -// if(lastWp.getWb().getTime()>tb.getEndTime()) - tb.setEndTime(lastWp.getWb().getTime());//更新 最后一个wp time - // tb.setOffTime(tb.getOffTime()+lastWp.getWb().getOfftime()); // track offtime will be handled by force update - if(lastWp.getWb().getElevation()!=0 && lastWp.getWb().getEled()>0){ - tb.seteUpDist(tb.geteUpDist()+lastWp.getWb().getEled()); //累加累积上升海拔高度 - - } - if(lastWp.getWb().getElevation()!=0 && lastWp.getWb().getEled()<0){ - tb.seteDownDist(tb.geteDownDist()+ lastWp.getWb().getEled()) ;//累加累积下降海拔高度 - } -// if(lastWp.getWb().getSpeed() >tb.getTopSpeed()) - tb.setTopSpeed(lastWp.getWb().getSpeed()); - // if(lastWp.getWb().getRoadBear()!=0)setLastRoadBear(lastWp); - -// QLog.getLogger().dLog(dTAG, "set lastwp,lastWp.getWb().getTurnFlag()"+ lastWp.getWb().getTurnFlag()); - if(!tb.getRoadWps().contains(lastWp) - && lastWp.getWb().getTurnFlag()!=wpFlag.NORMAL - &&lastWp.getWb().getTurnFlag()!=wpFlag.CUST - &&lastWp.getWb().getTurnFlag()!=wpFlag.TENT - &&lastWp.getWb().getTurnFlag()!=wpFlag.REST - ) - setLastRoadBear(lastWp); - if(tb.getType()==TrackType.GPX && !TextUtils.isEmpty(lastWp.getWb().getComment())){ - lastWp.getWb().setRoadBook(lastWp.getWb().getComment()); - lastWp.getWb().setComment(""); - tb.getRoadWps().add(lastWp.getWb()); - } - - maxR=Utils.getDistanceFromXtoY(_lastWp.getWb().getLatitude(), _lastWp.getWb().getLongitude(), _startWp.getWb().getLatitude(), _startWp.getWb().getLongitude()); - if(maxR>tb.getMaxR() && maxR0 && lastWp.getWb().getTime() == _lastWp.getWb().getTime() ){ - _lastWp = lastWp; - // wpsJson.replace(wpsJson., end, string) - _lastWpJson=_lastWp.toString(); - - int start = wpsJson.lastIndexOf("},{")+3; - int end =wpsJson.length(); - //wpsJson.append(_lastWpJson); - wpsJson.replace(start, end, _lastWpJson); - wpsJson.append(","); - // QLog.getLogger().d(dTAG ,TAG+" setLastWp, added medias"+_lastWpJson ); - return true; - } - else - { - Log.e(dTAG ,TAG+ " setLastWp, failed: new wp to set--->"+lastWp.toString()); - if(null != _lastWp){ - Log.e(dTAG ,TAG+ " track's _lastWp's time is: "+ _lastWp.getWb().getTime()); - } - return false; - } - } - - /* - * 新采集的wp加入到当前的轨迹中. - * 有一次装箱操作 - */ - public boolean setLastWp(String jsonWp) { - // Log.e(TAG +"set lastWp:" ,jsonWp); - try{ - Waypoint wpobj = new Waypoint(jsonWp); - _lastWpJson=jsonWp; - if( setLastWp( wpobj) ){ - if (TextUtils.isEmpty(_startWpJson ) || wpsJson ==null){ - _startWpJson = jsonWp; - wpsJson = new StringBuffer(); - } - - wpsJson.append(jsonWp); - wpsJson.append(","); - //Log.e(TAG +"track wps json:", wpsJson.toString()); - //Log.e(TAG +"set lastWp true:" ,jsonWp); - return true; - - }else { - // QLog.getLogger().d(dTAG,TAG +" set lastWp false:---->"+jsonWp); - } - }catch(Exception e){ - Log.e(dTAG ,TAG+ " setLastWp, failed: --->"+jsonWp ); - Utils.logStackTrace(e, dTAG); - } - return false; - } - - /* - * load last/first wp from db. - */ - public void loadLastWp(String jsonWp) { - // Log.e(TAG +"set lastWp:" ,jsonWp); - try{ - Waypoint wpobj = new Waypoint(jsonWp); - _lastWpJson=jsonWp; - if (TextUtils.isEmpty(_startWpJson ) ){ - _startWpJson = jsonWp; - - } - if(tb.getStartWp() ==null ||_startWp == null){ - _startWp =_startWp==null?wpobj:_startWp; - if(tb.getStartWp() ==null)tb.setStartWp(_startWp); - } - - _lastWp = wpobj; - tb.setLastWp(_lastWp); - - }catch(Exception e){ - Log.e(dTAG ,TAG+ " setLastWp, failed: --->"+jsonWp ); - Utils.logStackTrace(e, dTAG); - } - - } - - - - public Waypoint getStartWp() { - return _startWp; - } - public void setStartWp(Waypoint wp) { - _startWp =wp; - } - - - //TODO: check to use StringBuffer or just a String. - public StringBuffer getJsonWps() { - if (wpsJson ==null) wpsJson = new StringBuffer(); - return wpsJson; - } - - public String getLastJsonWp() { - - if(TextUtils.isEmpty(_lastWpJson)){ - if( _lastWp !=null){ - _lastWpJson = _lastWp.toString(); - } - } - return _lastWpJson; - } - - /*public void setLastWpJson(String lastWpJson) { - setLastWp(lastWpJson); - - } -*/ - public String getStartJsonWp() { - if(TextUtils.isEmpty(_startWpJson )){ - if( _startWp !=null){ - _startWpJson = _startWp.toString(); - // QLog.getLogger().d(dTAG,TAG+" Start wp is null, set value as _startWpJson = _startWp.toString()"); - }else if(getJsonWps().length()>0){ - _startWpJson =wpsJson.substring(0,wpsJson.indexOf("},", 0)+1 ); - // QLog.getLogger().d(dTAG,TAG+" Start wp is null, set value as _startWpJson = wpsJson.substring"); - }else if (getTrackBean().getTrkseg().size()>0){ - Gson gson = new Gson(); - wpsJson.append(gson.toJson(getTrackBean().getTrkseg())); - // QLog.getLogger().d(dTAG,TAG+" Start wp is null, set value as wpsJson = gson.toJson(getTrackBean().getTrkseg())"); - getStartJsonWp(); - }else if(!TextUtils.isEmpty(_lastWpJson )){ - _startWpJson =_lastWpJson; - } - - } - return _startWpJson; - } - - public void startNewTrack(TrackType trackType) - { - tb = new Track_bean(); - tb.setCreatTime(System.currentTimeMillis()); - this.tb.setStatus(TrackStatus.RECORDING); -// this.tb.setStartTime(System.currentTimeMillis()); - this.tb.setUserid(QiYouConstant.PV_USER_ID); - this.tb.setDistance(0); - this.tb.setGpsSpan(QiYouConstant.MAX_GPS_SPAN*QiYouConstant.WPS_SAVE_PERCENT_FACTOR); - tb.setType(trackType); -// this.tb.setComment("QiYouConstant.MAX_GPS_SPAN*QiYouConstant.WPS_SAVE_PERCENT_FACTORE: " +QiYouConstant.MAX_GPS_SPAN +","+ QiYouConstant.WPS_SAVE_PERCENT_FACTORE); - } - - - -public void setLastRoadBear(Waypoint wp) { -// QLog.getLogger().d(dTAG,TAG +" roadWps.size: "+roadWps.size()); - if(wp==null) return; - - - if(tb.getRoadWps().size()==0){ //wp.getWb().getTurnFlag() ==0){// && !TextUtils.isEmpty(getStartJsonWp())){//first start wp -// _lastRoadBear = wp; - _startWp.getWb().setTurnFlag(wpFlag.START); - tb.getRoadWps().add(_startWp.getWb()); - _lastRbJson =getStartJsonWp();// _startWpJson; - _rdWpsJson.append(_lastRbJson); -// saveBear(wp.getWb()); - return; - } - - wpFlag turnFlag =wp.getWb().getTurnFlag(); - -// QLog.getLogger().dLog(dTAG,"wp.getWb().getTurnFlag() is:" +turnFlag); - - if(turnFlag==wpFlag.TURNLEFT || turnFlag ==wpFlag.TURNRIGHT || turnFlag ==wpFlag.TURNBACK){ //针对普通左右掉头路点 - if(wp.getWb().getBearDist()==0) return; - } - - - - -// saveBear(wp.getWb()); - - -// String sb="\" "+ (tb.getRoadWps().size()-1 ) +". "+getBearMsg(wp.getWb().getRoadBear()); -// String sb="\" "+ (tb.getRoadWps().size()-1 ) +". " + getBearMsg(wp.getWb().getBearing()); - -// String turn= wp.getWb().getTurnFlag()>0?wp.getWb().getTurnFlag()==1?"左转":"反向":"右转"; -// int turnFlag =tb.getRoadWps().get(tb.getRoadWps().size()).getTurnFlag(); - - - - String sb=""; - if(turnFlag==wpFlag.TURNLEFT || turnFlag ==wpFlag.TURNRIGHT || turnFlag ==wpFlag.TURNBACK){ // turn bear wp - - if(wp.getWb().getBearDist()==0) return; - -// tb.getRoadWps().add(wp.getWb()); //add turn bear way point -// Waypoint_bean lastBear=tb.getRoadWps().get(tb.getRoadWps().size()-2); - Waypoint_bean lastBear=tb.getRoadWps().get(tb.getRoadWps().size()-1); - if(lastBear==null) return; - - - Location currentLocaiton = new Location("bear"); - currentLocaiton.setLatitude(wp.getWb().getLatitude()); - currentLocaiton.setLongitude(wp.getWb().getLongitude()); - - Location lastLocation = new Location("bear"); - lastLocation.setLatitude(lastBear.getLatitude()); - lastLocation.setLongitude(lastBear.getLongitude()); - - float bearDegree=lastLocation.bearingTo(currentLocaiton); - - String turn =turnFlag.toCHString(); - -// QLog.getLogger().dLog(dTAG,"wp.getWb().getTurnFlag().toCHString() is:" +turn); - - - String format = "\" 沿%s方向, 前行%s后%s";//,至%s处\""; - - sb =String.format(format -// ,Utils.getBearMsg(lastBear.getBearing(),false) - ,Utils.getBearMsg(bearDegree,false) - ,Utils.getFormatedDistance( wp.getWb().getBearDist() ) - ,turn -// ,Utils.getFormatedDistance( wp.getWb().getSumDist() ) - ); - - /* if(wp.getWb().getBearDist()>1000) - _roadBook.append(sb+"\n"); */ - -// QLog.getLogger().dLog(dTAG," roadbook is: " +sb); - -// wp.getWb().setRoadBook(sb); -// tb.getRoadWps().get(tb.getRoadWps().size()-1).setRoadBook(sb); - lastBear.setRoadBook(sb); - lastBear.setBearDist( wp.getWb().getBearDist() ); - tb.getRoadWps().add(wp.getWb()); //add turn bear way point - - - // tb.getRoadWps().add(_lastRoadBear.getWb()); -// QLog.getLogger().d(dTAG, TAG+" _lastRbJson" +_lastRbJson); - _lastRbJson = this._lastWpJson.replace("\"roadBook\":\"\",", ""); - _lastRbJson = _lastRbJson.substring(0, _lastRbJson.length()-1) + ",\"roadBook\":"+sb +"},"; -// QLog.getLogger().d(dTAG, TAG+" _lastRbJson" +_lastRbJson); -// QLog.getLogger().dLog(dTAG," _lastRbJson is: " +_lastRbJson); - _rdWpsJson.append(_lastRbJson); - - return; - - }else if(wp.getWb().getTurnFlag()==wpFlag.MAXR){ //maxR - int i=0; - for(Waypoint_bean wb:tb.getRoadWps()){ - if(wb==null)continue; - if(wb.getSumDist()1){ - - wp.getWb().setRoadBook("到达本次记录最远位置 \n距起点直线距离 " - +Utils.getFormatedDistance( getTrackBean().getMaxR()) - +",运动距离 " + Utils.getFormatedDistance( wp.getWb().getSumDist())); - tb.getRoadWps().add(i, wp.getWb()); - // QLog.getLogger().d(dTAG,TAG +" ......................到达本次记录最远位置" + Utils.getFormatedDistance( getTrackBean().getMaxR())); -// _lastRbJson =wp.toString(); - break; - }else{ - Log.e(dTAG,TAG+" Wrong wps...."); - i++; - } - - } - } else if(turnFlag==wpFlag.END){ //last wp - sb="\" 到达本次记录的终点位置(结束)"; - wp.getWb().setRoadBook(sb); - tb.getRoadWps().add(wp.getWb()); - _roadBook.append(sb); - - } - - -} - -/* - *gpx from aiqilv lushu - */ -public boolean isGpx(){ - return tb.getType()==TrackType.GPX; -} - -public boolean isLushu(){ - return tb.getCreator()!=null &&tb.getCreator().startsWith("爱骑驴路书"); - } - -private ArrayList mdList; -/* - * level : 0, standard GEO; 1: detail ; 2: pic only - */ -public List> getFootmark(int level,Boolean showMd) { - - - List> mData = new ArrayList>(); - QLog.getLogger().d(dTAG, TAG+String.format(" begin to get footmark....................")); - mdList =new ArrayList(); -// String filePath =QiYouConstant.PHOTO_PATH + tb.getTrackId()+"/" ; - int i=0; -// long last=0; - float last=0; - float end=0; - if(getTrackBean().getType()!=TrackType.GPX) - if(level ==2 ||getTrackBean().getTrackId()<=0 && getTrackBean().getMdWps().size()>0) { - if(showMd) - mData.addAll(getMdlist(last,end)); -// addNotes(mData,level); - return mData; - } - - if(getTrackBean().getType()!=TrackType.GPX && getTrackBean().getTrackId()<=0)return null; - -// boolean isGpx =tb.getCreator()!=null &&tb.getCreator().equalsIgnoreCase("爱骑驴路书"); -// long lastSptime=0; - long lastTime=0;//=this.getStartWp().getWb().getTime(); - long nextTime=0; - float lastSumdist=0; - Waypoint_bean nextWb = null; -// Waypoint_bean lastWb = null; - String last_currentGeo =""; - String last_nextGeo =""; - String current_district= ""; - String last_district = ""; - String current_street = ""; -// String last_street = ""; - String next_street = ""; - boolean isSkiped =false; - boolean isTheLastOne=false; - int j=0; - long begintime=0; - - /*CopyOnWriteArrayList wbs=Utils.getCleanWbs(tb.getRoadWps());*/ - ArrayList wbs=Utils.getCleanWbs(tb.getRoadWps()); -// tb.getRoadWps().add(0,_startWp.getWb()); -/* for(Waypoint_bean wb:tb.getRoadWps()){ - if(wb==null)continue; - if( wb.getTime()>lastTime){ -// if(nextWb ==null && _startWp!=null && wb.getTime()>_startWp.getWb().getTime()){ -// nextWb =wb; -// } - wbs.add(wb); - lastTime =wb.getTime(); - } - }*/ - - if(wbs.size()>0 && wbs.get(0).getTime()>_startWp.getWb().getTime()) - wbs.add(0,_startWp.getWb()); - if(wbs.size()>1 && wbs.get(wbs.size()-1).getTime()<_lastWp.getWb().getTime()) - wbs.add(wbs.size()-1,_lastWp.getWb()); - - tb.setRoadWps(wbs); - - lastTime =0; - String blank=" "; - String format = blank+"[当前时间]:%s \n" - +blank+"[区间用时]:%s [当前速度]:%.1f [区间均速]:%.1f"; - String sportData=""; - String nextGeo =""; - String passedInfo=""; - String title=""; - String roadInfo = ""; - String currentGeo =""; - Map data ; - - /* - data = new HashMap(); - data.put("time",_startWp.getWb().getTime()+","+_startWp.getWb().getTime()); - if(_startWp!=null &&nextWb!=null && (level ==0 || level==1 && _startWp.getWb().getGeo()!=null) ){ - -// if(nextWb!=null){ - sportData =nextWb.getSumDist()>0? String.format( format, - Utils.getFormatedTime(_startWp.getWb().getTime()), - Utils.getTimeCnt(nextWb.getTime()-_startWp.getWb().getTime(), true), - _startWp.getWb().getSpeed(), - 3600*(nextWb.getSumDist())/(nextWb.getTime()-_startWp.getWb().getTime() ) - ) :""; - roadInfo = "前行"+Utils.getFormatedDistance(nextWb.getDistance()) ; -// } - - if(_startWp.getWb().getGeo()!=null ) { - if ( nextWb.getGeo()!=null && !TextUtils.isEmpty(nextWb.getGeo().toString(","))){ - nextGeo = nextWb.getGeo().toString(","); - - - roadInfo = nextWb.getRoadBook().replace("\"", "") - + (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":(",将到达 " +nextGeo) ); - } - currentGeo =_startWp.getWb().getGeo().toString(","); - } - title=(TextUtils.isEmpty(currentGeo))?"": currentGeo ; - data.put("time",_startWp.getWb().getTime()+","+nextWb.getTime()); - } - title= title - + (TextUtils.isEmpty(sportData)?sportData:"\n"+sportData) - +(TextUtils.isEmpty(roadInfo)?roadInfo:"\n"+roadInfo) ; - data.put("title", "起点" +blank +Utils.getFormatedTime(_startWp.getWb().getTime()) +"\n"+title); -// data.put("cmnt",_startWp.getWb().getComment()); - data.put("cmnt", tb.getRoadWps().get(0).getComment()); - - mData.add(data); */ - - - if(end==0)last=-1; //to show pics taken before the first wp. - if(showMd) - mData.addAll(getMdlist(last,end)); - -// QLog.getLogger().d(dTAG, TAG+String.format("get footmark.tb.getRoadWps() size: "+tb.getRoadWps().size())); - for(Waypoint_bean wb:tb.getRoadWps() ){ //TODO: Check why roadwps 没有包含first,lastwp - j++; - isTheLastOne =(j==(tb.getRoadWps().size()))&&(level ==1)&& wb.getDistance()>0; -// if(wb!=null && !TextUtils.isEmpty(wb.getRoadBook()) -// && wb.getTime()>0 &&wb.getSpeed()>0 && wb.getDistance()>0 && -// (lastTime==0 ||wb.getTime()>lastTime) || isTheLastOne){ - if( i(); - data.put("time",wb.getTime()+","+wb.getTime()); - title=blank+"[当前时间]:" +Utils.getFormatedTime(wb.getTime()) + String.format("\n%s[当前速度]:%.1f" ,blank,wb.getSpeed())+"\n"+wb.getRoadBook(); - data.put("title",title ); - data.put("cmnt",wb.getComment()); - mData.add(data); - continue; - } - - - - - if (wb.getGeo()!=null && !TextUtils.isEmpty(wb.getGeo().toString(","))){ - currentGeo = wb.getGeo().toString(","); - current_district =wb.getGeo().getDistrict(); - current_street =wb.getGeo().getStreet(); - } - -// TextUtils.isEmpty(currentGeo) currentGeo lastGEO - -// int k=1; -// while ((nextWb==null || nextWb.getTime()(); -// String sportData =""; -// if(wb.getTime()>0 &&wb.getSpeed()>0) - - /* String sportData= wb.getTime()-lastTime==0?"":String.format( //blank+"总距离"+ - blank+"[当前时间]:%s \n" - +blank+"[区间用时]:%s [当前速度]:%.1f [区间均速]:%.1f", - Utils.getFormatedTime(wb.getTime()), - Utils.getTimeCnt(wb.getTime()-lastTime, true), - wb.getSpeed(), - 3600*(wb.getSumDist()-lastSumdist)/(wb.getTime()-lastTime)*/ - - /* - sportData= (nextWb==null && _lastWp.getWb().getTime()>wb.getTime())? - String.format( format, - Utils.getFormatedTime(wb.getTime()), - Utils.getTimeCnt(_lastWp.getWb().getTime() -wb.getTime(), true), - wb.getSpeed(), - 3600*(_lastWp.getWb().getSumDist()-wb.getSumDist())/(_lastWp.getWb().getTime() -wb.getTime()) - ) - : - String.format( format, - Utils.getFormatedTime(wb.getTime()), - Utils.getTimeCnt(nextTime -wb.getTime(), true), - wb.getSpeed(), - 3600*(nextWb.getSumDist()-wb.getSumDist())/(nextTime -wb.getTime()) - );*/ - if(tb.getType()!=TrackType.GPX && wb.getTime()>0) - sportData= (nextWb==null && _lastWp.getWb().getTime()>wb.getTime())? - String.format( format, - Utils.getFormatedTime(wb.getTime()), - Utils.getTimeCnt(_lastWp.getWb().getTime() -wb.getTime(), true), - wb.getSpeed(), - 3600*(_lastWp.getWb().getSumDist()-wb.getSumDist())/(_lastWp.getWb().getTime() -wb.getTime()) - ) - :( nextWb==null?"": - String.format( format, - Utils.getFormatedTime(wb.getTime()), - Utils.getTimeCnt(nextTime -wb.getTime(), true), - wb.getSpeed(), - 3600*(nextWb.getSumDist()-wb.getSumDist())/(nextTime -wb.getTime()) - ) - ); - - - title=""; - roadInfo =wb.getDistance()>0? - "前行"+Utils.getFormatedDistance(wb.getDistance()) + ",前方到达"+Utils.getFormatedDistance(wb.getSumDist())+"处" - :""; -// if(level ==0 || level ==1 && !TextUtils.isEmpty(nextGeo)){ - - if(level ==0 ){ - - begintime = wb.getTime() ; - /* title=(TextUtils.isEmpty(currentGeo)||currentGeo.equalsIgnoreCase(last_currentGeo))?"": currentGeo+"\n" ; - title= title+ sportData ;*/ - -// QLog.getLogger().d(dTAG, TAG +" currentGeo is :" + currentGeo); -// QLog.getLogger().d(dTAG, TAG +" title is :" + title); - - /* if(nextWb!=null && nextWb.getTime()>wb.getTime()) -// roadInfo = isGpx()? TextUtils.isEmpty(nextWb.getRoadBook())?nextWb.getComment().replace("\"", ""):nextWb.getRoadBook().replace("\"", "") -// :wb.getRoadBook().replace("\"", "") - roadInfo = tb.getType()==TrackType.GPX && TextUtils.isEmpty(wb.getRoadBook())? wb.getComment().replace("\"", "") - : nextWb.getRoadBook().replace("\"", "")// wb.getRoadBook().replace("\"", "") - + (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":(",将到达 " +nextGeo) );*/ - - if( tb.getType()==TrackType.GPX ){ - /* roadInfo = wb.getRoadBook().replace("\"", "")+( TextUtils.isEmpty(wb.getComment())?"":wb.getComment().replace("\"", ""));*/ - roadInfo =( TextUtils.isEmpty(wb.getComment())?"":wb.getComment().replace("\"", "")+"\n")+ wb.getRoadBook().replace("\"", ""); - }else/* if(nextWb!=null)*/{ - roadInfo = wb.getRoadBook().replace("\"", "")// wb.getRoadBook().replace("\"", "") - + (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":(",将到达 " +nextGeo) ); - } - - -// roadInfo = isGpx() && TextUtils.isEmpty(nextWb.getRoadBook())? nextWb.getComment().replace("\"", "") -// : nextWb.getRoadBook().replace("\"", "")// wb.getRoadBook().replace("\"", "") -// + (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":(",将到达 " +nextGeo) ); - -// title =title + (TextUtils.isEmpty(roadInfo)?"":"\n"+ roadInfo) ; - - -// } else if( level ==1 && (!TextUtils.isEmpty(currentGeo)||isTheLastOne)){ -// } else if( level ==1 && (!TextUtils.isEmpty(currentGeo) ||nextWb==null)){ - } else if( level ==1 && !TextUtils.isEmpty(currentGeo)||isSkiped ||i==1){ -// } else if( level ==1 && currentGeo!=null ){ -// } else if( level ==1 ||isTheLastOne ){ - - - - if(( current_district==null ||last_district==null ||current_district.equalsIgnoreCase(last_district)) -// && (current_street.equalsIgnoreCase(next_street)|| TextUtils.isEmpty(next_street)) -// || (currentGeo.equalsIgnoreCase(nextGeo) || currentGeo.equalsIgnoreCase(last_currentGeo) && nextGeo.equalsIgnoreCase(last_nextGeo)) - - && (current_street==next_street|| TextUtils.isEmpty(next_street)) - || (currentGeo==nextGeo || (currentGeo==last_currentGeo) && (nextGeo==last_nextGeo)) - - ){ - isSkiped =true; -// isTheLastOne =isTheLastOne&&(wb.getTime()>lastTime); - if(!isTheLastOne ) - { - begintime = begintime==0?wb.getTime():begintime; - continue; - } - } -// String title=(currentGeo.equalsIgnoreCase(last_currentGeo)?"":currentGeo) -// + sportData + "\n" +wb.getRoadBook().replace("\"", "") -// + (nextGeo.equalsIgnoreCase(last_nextGeo)?"":nextGeo ); - -// String roadInfo = isSkiped?("延 " +wb.getGeo().toString(",") +" 前行" + Utils.getFormatedDistance(wb.getSumDist()-lastSumdist)):wb.getRoadBook().replace("\"", ""); -// String title= currentGeo -// + sportData + "\n" -// + roadInfo -// + nextGeo ; - -// String roadInfo = "延 " +wb.getGeo().toString(",") +"前行" + Utils.getFormatedDistance(wb.getSumDist()-lastSumdist) ; -// String roadInfo = ""; - passedInfo=""; - if(nextWb!=null && nextWb.getTime()>wb.getTime()) { - passedInfo=isSkiped?"[延" + current_street +"累计运动" + Utils.getFormatedDistance(wb.getSumDist()-lastSumdist) +"后]\n" :""; - - roadInfo= (isTheLastOne ? "" : nextWb.getRoadBook().replace("\"", "") ) - + (TextUtils.isEmpty(next_street)?"":(",将到达 " +next_street)); - } - /* title= passedInfo ; - title +=(TextUtils.isEmpty(currentGeo)||currentGeo.equalsIgnoreCase(last_currentGeo))?"": currentGeo+"\n" ; - title += sportData ;*/ -// + (TextUtils.isEmpty(roadInfo)?"\n将到达终点附近.":"\n"+ roadInfo) ; - - - - isSkiped=false; - } else{ - continue; - } -// QLog.getLogger().d(dTAG, TAG +" title is :" + title); - - - - - - -// if(i==1) - if(i<2 && wb.getTime()<=_startWp.getWb().getTime()){ - title ="起点" +blank +(isGpx()?"":Utils.getFormatedTime(_startWp.getWb().getTime())) +(isGpx()?"\n\n":"\n"); - } - title += passedInfo ; - title +=(TextUtils.isEmpty(currentGeo)||currentGeo.equalsIgnoreCase(last_currentGeo))?"": currentGeo+"\n" ; - title += sportData ; - - if(wb.getTurnFlag()==wpFlag.END ||nextWb==null) - roadInfo= ( _lastWp.getWb().getSumDist()>last? - ("前行"+Utils.getFormatedDistance(_lastWp.getWb().getSumDist()-last) +"," - +" 到达"+Utils.getFormatedDistance(tb.getDistance())+"处\n") - :"" - ) - +"\n"+"终点 "+ (_lastWp.getWb().getGeo()!=null?_lastWp.getWb().getGeo().toString(","):"") - - +(isGpx()?"":"\n" +Utils.getFormatedTime(_lastWp.getWb().getTime())) -// +Utils.getFormatedTime(tb.getEndTime()) -// +Utils.getFormatedTime(_lastWp.getWb().getTime()) - ; - - - title += TextUtils.isEmpty(roadInfo)?"":"\n"+ roadInfo ; - - - - - - - - if(!TextUtils.isEmpty(title)){ - -// QLog.getLogger().d(dTAG, TAG +" title is :" + 1+title+1); - begintime =begintime>0?begintime:wb.getTime(); - - data.put("title",title) ; - // data.put("uri",null); - /*data.put("cmnt",(nextWb!=null?nextWb.getComment():wb.getComment() ));*/ - data.put("cmnt",(wb.getComment() )); - // data.put("time",lastTime+","+String.valueOf(wb.getTime())); - data.put("time",begintime+","+ (nextWb!=null?nextTime:_lastWp.getWb().getTime() )); - mData.add(data); - } - - //build the wp pics if there is any. - if(nextWb!=null ){ -// end =wb.getSumDist(); -// if(end==0)last=-1; //to avoid showing all the pics for the first wp. -// QLog.getLogger().d(dTAG, TAG+String.format(" get mdlist start is %s, end is %s",last,end)); -// -// if(showMd) -// mData.addAll(getMdlist(last,end)); - - - last =wb.getSumDist(); - end =nextWb.getSumDist(); - if(end==0)last=-1; //to avoid showing all the pics for the first wp. -// QLog.getLogger().d(dTAG, TAG+String.format(" get mdlist start is %s, end is %s",last,end)); - - if(showMd) - mData.addAll(getMdlist(last,end)); - } - begintime =0; -// lastWb=wb; - last =wb.getSumDist(); - lastTime=wb.getTime(); - lastSumdist=wb.getSumDist(); -// lastSptime =wb.getSportTime(); - - last_currentGeo =currentGeo; - last_nextGeo =nextGeo; - last_district=current_district; -// last_street=current_street; - } - } - - - if(i==0 && showMd){ - - mData.addAll(getMdlist(last,end)); - } - - - /* if( _lastWp.getWb().getGeo()!=null || tb.getStatus()==QiYouConstant.TRACK_STATUS_FINISHED){ - lastTime=nextTime>lastTime?nextTime:lastTime; - nextTime= _lastWp.getWb().getTime(); - sportData= (nextTime>lastTime)? - String.format( format, - Utils.getFormatedTime(lastTime), - Utils.getTimeCnt(nextTime-lastTime, true), - _lastWp.getWb().getSpeed(), - 3600*(_lastWp.getWb().getSumDist()-last)/(nextTime-lastTime ) - ):""; - -// roadInfo= String.format("前行"+Utils.getFormatedDistance(_lastWp.getWb().getSumDist()-last) +"," -// +" 到达"+Utils.getFormatedDistance(tb.getDistance())+"处\n" -// +"终点 "+ _lastWp.getWb().getGeo().toString(",") ) -// +Utils.getFormatedTime(tb.getEndTime()) -// ; - roadInfo= ( _lastWp.getWb().getSumDist()>last? - ("前行"+Utils.getFormatedDistance(_lastWp.getWb().getSumDist()-last) +"," - +" 到达"+Utils.getFormatedDistance(tb.getDistance())+"处\n") - :"" - ) - +"\n"+"终点 "+ (_lastWp.getWb().getGeo()!=null?_lastWp.getWb().getGeo().toString(","):"") - +"\n" +Utils.getFormatedTime(_lastWp.getWb().getTime()) -// +Utils.getFormatedTime(tb.getEndTime()) -// +Utils.getFormatedTime(_lastWp.getWb().getTime()) - ; - - title= (!TextUtils.isEmpty(nextGeo)? nextGeo+"\n":nextGeo) + - (!TextUtils.isEmpty(sportData)?sportData+ "\n":"") + - roadInfo; - - - data = new HashMap(); - data.put("title", title); - data.put("time",lastTime+","+nextTime); - data.put("cmnt",_lastWp.getWb().getComment()); - mData.add(data); - }*/ - -// data = new HashMap(); -// data.put("title", String.format("终点位置 " +(_lastWp!=null && _lastWp.getWb().getGeo()!=null? _lastWp.getWb().getGeo().toString(",") :"" ))); -// data.put("time",_lastWp.getWb().getTime()+","+_lastWp.getWb().getTime()); -// mData.add(data); - if(_lastWp!=null) - end=_lastWp.getWb().getSumDist(); //show pics that before the last new waypoint created. - if(end==0)last=-1; - if(showMd) - mData.addAll(getMdlist(last,end)); -// GenFootmark(true,_roadBook.toString()); //when new geo populated, the footmark file content will be cleared.force to fill the the content. - -// addNotes(mData,level); - /* for(Waypoint_bean wb1:tb.getRoadWps()){ - - QLog.getLogger().d(dTAG, "30 cust wp turn flag" + wb1.getTurnFlag().toCHString()); - } */ - - return mData; -} - - -public List> getMdlist(float start,float end){ - List> mData = new ArrayList>(); - Map data ; -// String filePath ; - for(Waypoint_bean mwb:tb.getMdWps()){ - -// if(wb!=null && wb.getTime()>=start && wb.getTime()<=end){ - if(mwb!=null && (mwb.getSumDist()>=start && mwb.getSumDist()<=end || start==end && start==0)){ - GEOaddress geo =getGeo(mwb.getTime()); - String title=geo==null?"":geo.toString(","); - for(Media md: mwb.getMedias()){ - if(md.getStatus()==mediaStatus.DELETED||md.getStatus()==mediaStatus.HIDED) - continue; - -// QLog.getLogger().d(dTAG, TAG+String.format("PICS met condition, start is %s, end is %s",start,end)); - -// filePath =this.getMediaPah(md.getType()); - data = new HashMap(); - title +=" "+Utils.getFormatedTime(md.getTime()); - data.put("title",title); - -// String path = QiYouConstant.BASE_MD_URL+md.getSvrUri();//getValidMdUrl(md);//md.getUri(); - - String path = getValidMdUrl(md,true); - - - -// QLog.getLogger().d(dTAG, TAG+ " footmark web pic url is " +path); - - - if(mdList.contains(path))continue; - mdList.add(path); -// path =path.contains(QiYouConstant.PHOTO_PATH)?path:filePath +path; //to remove. -// path = filePath +path; //to remove. - data.put("uri",path); - data.put("mdType",md.getType().toString()); - - if(!TextUtils.isEmpty( md.getComment())) - data.put("cmnt",md.getComment()); - data.put("time",String.valueOf(md.getTime())); - mData.add(data); - - /*switch( md.getType() ){ - case PIC: - break; - case MAP: - break; - case SOUND: - break; - case VIDEO: - break; - default: - break; - - }*/ - } - } - - } -/* - data = new HashMap(); - data.put("title","") ; - data.put("cmnt",""); - data.put("time",""); - data.put("uri",""); - data.put("mdType",mediaType.PIC.toString()); - mData.add(data); */ - - return mData; - -} - -GEOaddress getGeo(long time){ - for(Waypoint_bean wb:tb.getRoadWps()){ - if(wb==null)continue; - if( wb.getTime()==time){ - return wb.getGeo(); - } - } - return null; -} - - - public String getValidMdUrl(Media md,boolean isThumb){ - if(md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){ - File f = new File(md.getUri()); - // QLog.getLogger().d(dTAG,TAG+" getting valid md url: "+ md.getUri()); - if(f.exists()){ - return md.getUri(); - - }else{ -// if(tb.getSvrNumber()>0 && tb.getUserid()!=QiYouConstant.PV_USER_ID){ - if(tb.getSvrNumber()>0 ){ -// return QiYouConstant.BASE_MD_URL+md.getSvrUri() ; - return QiYouConstant.BASE_MD_URL+(isThumb?md.getSvrThumbUrl():md.getSvrUri()) ; - - } - } - } - return ""; -} - /*void addNotes(List> mData,int level){ - String notice=""; - if(mData.size()==0 ){ - notice="还没有发现小脚印..."; - if(level ==1){ - notice ="没找到详细地址数据...连接wifi后会自动生成详细地址数据..."; - }else if(level==2){ - notice ="没找到照片...快去拍些亮丽的片片吧" ; - } - }else{ - notice ="提示: 长按足迹条目可在地图定位"; -// if(level ==1){ -// notice ="提示: 长按可地图定位"; -// }else - if(level==2){ - notice ="提示: 点击图片可进入浏览模式,长按图片可地图定位" ; - } - } - - HashMap data = new HashMap(); - data.put("title",notice ) ; - data.put("picUrl",null); - data.put("picCmnt",null); - mData.add(0,data); -}*/ - - - -//public String[] getPicList(){ -// return getPicList(0,false,true); -//} -public String[] getPicList(int cnt){ - return getPicList(cnt,true,true); - } -public String[] getValidPicList(boolean isThumbs){ - return getPicList(0,true,isThumbs); - } - - -public String[] getPicList(int cnt,boolean validOnly,boolean isThumbs){ - - ArrayList al = new ArrayList(); - int i=0; - String protocol ="file://"; - String webUrl =QiYouConstant.BASE_MD_URL; - File f ; - for(Waypoint_bean mwb:tb.getMdWps()){ - if(mwb!=null ){ - if(cnt>0 && i>=cnt)break; - - for(Media md: mwb.getMedias()){ - if(cnt==0|| cnt>0 && i<=cnt){ - - if(validOnly ){ - if( md.getStatus()==mediaStatus.DELETED || md.getStatus()==mediaStatus.HIDED){ - continue; - } - } - - if(tb.getSvrNumber()>0 ){ - f = new File(md.getUri()); - if(f.exists()){ - al.add(protocol+md.getUri()); - i++; - }else{ - al.add(webUrl+(isThumbs?md.getSvrThumbUrl():md.getSvrUri())); - i++; - } - }else{ - al.add(protocol+md.getUri()); - i++; - } - - - /* if(validOnly){ - if(md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){ - f = new File(md.getUri()); - if(f.exists()){ - al.add(protocol+md.getUri()); - i++; - }else{ -// if(tb.getSvrNumber()>0 && tb.getUserid()!=QiYouConstant.PV_USER_ID){ - if(tb.getSvrNumber()>0 ){ - al.add(webUrl+md.getSvrUri()); - i++; - } - } - } - }else{ - if(tb.getSvrNumber()>0 && tb.getUserid()!=QiYouConstant.PV_USER_ID){ - al.add(webUrl+md.getUri()); - i++; - }else{ - i++; - al.add(protocol+md.getUri()); - } - }*/ - - } -// QLog.getLogger().d(dTAG,TAG+" protocol+md.getUri() "+ protocol + md.getUri()); - - /*switch( md.getType()){ - case PIC: - break; - case MAP: - break; - case SOUND: - break; - case VIDEO: - break; - default: - break; - }*/ - } - } - } - String[] picUrls = new String[al.size()]; - al.toArray(picUrls); - return picUrls; -} - -public String[] getWebPicList(int cnt,boolean validOnly){ - - ArrayList al = new ArrayList(); - int i=0; - String webUrl =QiYouConstant.BASE_MD_URL; -// File f ; - for(Waypoint_bean mwb:tb.getMdWps()){ - if(mwb!=null ){ - if(cnt>0 && i>=cnt)break; - for(Media md: mwb.getMedias()){ - if(!TextUtils.isEmpty(md.getSvrUri())) - if(cnt==0|| cnt>0 && i<=cnt){ - if(validOnly){ - if(md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){ - al.add(webUrl+md.getSvrThumbUrl()); - i++; - // QLog.getLogger().d(dTAG,TAG+" get web md url is:"+ webUrl+md.getSvrThumbUrl()); - } - }else{ - al.add(webUrl+md.getSvrUri()); - i++; - // QLog.getLogger().d(dTAG,TAG+" get web md url is:"+ webUrl+md.getSvrThumbUrl()); - } - } - - } - } - } - String[] picUrls = new String[al.size()]; - al.toArray(picUrls); - return picUrls; -} - -public String getMediaPah(mediaType mdType){ - String picPath=QiYouConstant.MEDIA_PATH +mdType +"/"; - picPath+=mdType==mediaType.MAP?"i7lv": - getTrackBean().getTrackId()>0? - QiYouConstant.MEDIA_FOLDER_PREFIX+getTrackBean().getTrackId() - :"i7lv"; - - return picPath+"/"; -} - -public boolean isContentExist(){ - if(getTrackBean().getTrackId()<=0) - return false; - File file = new File(getContentPah()); - return file.exists(); - -} - -public boolean readContent(){ - if(getTrackBean().getTrackId()<=0) - return false; - else{ - wpsJson=new StringBuffer(); - try { - - wpsJson.append(Utils.readSDFile(getContentPah())); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - return true; -} - - -public String getContentPah(){ -// return QiYouConstant.CONTENT_SD_DIR + getTrackBean().getTrackId()+".txt"; - return Utils.getContentPah(getTrackBean().getTrackId()); -} -public boolean saveContent(){ - return saveContent(true); -} - -public boolean saveContent(boolean isAppend){ - if(getTrackBean().getTrackId()<=0) - return false; - else{ - try { - - if(TextUtils.isEmpty(getJsonWps().toString())) - getJsonWps().append(wps2json(getTrackBean().getTrkseg())); - - // QLog.getLogger().dLog(dTAG, "saved trackseg content is: "+getJsonWps().toString()); - Utils.writeSDFile(getContentPah(), getJsonWps().toString(), isAppend); -// Utils.writeSDFile(getContentPah(), wpsJson.toString(), isAppend);getJsonWps() - wpsJson=new StringBuffer(); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - return true; -} -public String getBearContentPah(){ -// return QiYouConstant.CONTENT_SD_DIR + getTrackBean().getTrackId()+"b.txt"; - return Utils.getBearContentPah(getTrackBean().getTrackId()); -} -public boolean saveBearContent(){ - return saveBearContent(true); -} -public boolean saveBearContent(boolean isAppend){ - if(getTrackBean().getTrackId()<=0) - return false; - else{ - try { - - if(TextUtils.isEmpty(this.getRdWpsJson() )){ - getRdWpsJson().append(wps2json(getTrackBean().getRoadWps())); - // QLog.getLogger().dLog(dTAG, "saved RoadWps content is: "+getRdWpsJson().toString()); - Utils.writeSDFile(getBearContentPah(), getRdWpsJson().toString(), false); - return true; - } - if(!TextUtils.isEmpty(_rdWpsJson )){ - Utils.writeSDFile(getBearContentPah(), getRdWpsJson().toString(), isAppend); - _rdWpsJson=new StringBuffer(); - } - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - return true; -} - -public boolean isBearContentExist(){ - if(getTrackBean().getTrackId()<=0) - return false; - File file = new File(getBearContentPah()); - return file.exists(); - -} - -public boolean readBearContent(){ - if(getTrackBean().getTrackId()<=0) - return false; - else{ - _rdWpsJson=new StringBuffer(); - try { - - _rdWpsJson.append(Utils.readSDFile(getBearContentPah())); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - return true; -} - - -public static boolean saveBear(Waypoint_bean wb){ - if(wb.getLatitude()==0||wb.getLongitude()==0)return false; - - try { -// Utils.writeSDFile(QiYouConstant.BEAR_TEXT,((int)(Utils.getbdLat(wb.getLatitude(),wb.getLongitude()))*1E6 ) + -// ","+(int)(Utils.getbdLon(wb.getLatitude(),wb.getLongitude()))*1E6+";", true); -// String strlatlon= wb.getLatitude() + ","+wb.getLongitude(); -// String bearString=""; -// bearString = Utils.readSDFile(QiYouConstant.BEAR_TEXT); -// if(TextUtils.isEmpty(bearString)||!bearString.contains(strlatlon)) - - //TODO: to record each track in itsown bear text. - Utils.writeSDFile(QiYouConstant.BEAR_TEXT,wb.getLatitude() + ","+wb.getLongitude()+";", true); - - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - return false; - - } - - return true; -} - - - -public void assemblyContent(){ - if(readContent()){ - String json=wpsJson.toString(); - if(!TextUtils.isEmpty(json)){ - // json= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", ""); - json=getCleanJson(json); - // tb.setTrksegs(wps); - if(!json.startsWith("[")) - json ="["+json ; - if(!json.endsWith("]")){ - json =json+"]"; - } - try { - getTrackBean().setTrksegs(getWPS( new Gson(),json)); - } catch (Exception e) { - Utils.logStackTrace(e, dTAG); - if(!TextUtils.isEmpty(json)){ - Log.e(dTAG ,TAG+" below is wps jsonWps---------------"); - Log.e(dTAG ,TAG+ json ); - } - } - } - wpsJson=new StringBuffer(); //TODO check if it will cause : //put it before convert to wps, in case failed, then recovery track will miss existed wps in db. - } - -} - - - -private void assemblyBearContent(){ - if(readBearContent()){ - String json=_rdWpsJson.toString(); - if(!TextUtils.isEmpty(json)){ - // json= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", ""); - json=getCleanJson(json); - // tb.setTrksegs(wps); - if(!json.startsWith("[")) - json ="["+json ; - if(!json.endsWith("]")){ - json =json+"]"; - } - try { - getTrackBean().setRoadWps(getWPS( new Gson(),json)); - // QLog.getLogger().d(dTAG, TAG +" "+" Loading bear content from bear text "+ getBearContentPah() +"........................................"); - } catch (Exception e) { - Utils.logStackTrace(e, dTAG); - if(!TextUtils.isEmpty(json)){ - Log.e(dTAG ,TAG+" below is wps bearRoadWps---------------"); - Log.e(dTAG ,TAG+ json ); - } - } - } - _rdWpsJson=new StringBuffer(); //TODO check if it will cause : //put it before convert to wps, in case failed, then recovery track will miss existed wps in db. - } - -} - - - -public String getStaticMapPath(){ - return getMediaPah(mediaType.MAP); -} - -public String getStaticMap(){ - - String staticMapPath ="file://"+getStaticMapPath() + getStaticMapUrl().hashCode()+".png" ; - File staticMap = new File(staticMapPath); - try { - if(!staticMap.exists()){ //to get it from http://api.map.baidu.com/staticimage - staticMapPath = getStaticMapUrl(); - } - } catch (Exception e1) { - // TODO Auto-generated catch block - Utils.logStackTrace(e1, TAG); - } - - return staticMapPath ; -} -public String getStaticMapUrl(){ - -// String webStaticUrl=Utils.getBaiduStaticMapUrl(this); - -/* if(this.getTrackBean().getRoadWps().size()<2) - return getStaticMapPath()+getTrackBean().getTrackId()+".png" ; - else - return Utils.getBaiduStaticMapUrl(this); - */ - String staticDir=getStaticMapPath(); - File dir = new File(staticDir); - if(!dir.exists()) dir.mkdirs();// 创建文件夹 - - String static_url_file=staticDir + String.valueOf(this.getTrackBean().getEndTime()); - String static_url=""; - - File staticMap = new File(static_url_file); - try { - if(!staticMap.exists()){ //to get it from http://api.map.baidu.com/staticimage - if(getTrackBean().getTrackId()>0 && getTrackBean().getTrkseg().size()==0){ - assemblyContent(); - } - static_url = Utils.getBaiduStaticMapUrl(this); - staticMap.createNewFile(); - Utils.writeSDFile(static_url_file,static_url,false); - }else - { - static_url = Utils.readSDFile(static_url_file); - } - } catch (Exception e1) { - // TODO Auto-generated catch block - Utils.logStackTrace(e1, TAG); - } - - return static_url; - -} - - -public boolean isStaticMapExist(){ - - File myFile = new File(getStaticMap()); - return myFile.exists(); - -} - - -/*public StringBuffer getRoadBook(Boolean showMd) { - - if(_roadBook.length()==0 && tb.getRoadWps()!=null) - { - _roadBook = new StringBuffer(); - String fm = getFootmark(); - if(!TextUtils.isEmpty(fm)){ - _roadBook.append( getFootmark()); - return _roadBook; - } - -// _roadBook.append(""); - _roadBook.append(""); - _roadBook.append(String.format(QiYouConstant.FOOT_MARK_TITLE_TEMPLATE,"我的足迹")); - - if(_startWp.getWb().getGeo()!=null ) - _roadBook.append(String.format("起点:" + QiYouConstant.FOOT_MARK_TURN_TEMPLATE,_startWp.getWb().getGeo().toString(","))+"\n"); - - int i=0; -// long last=0; - float last=0; - for(Waypoint_bean wb:tb.getRoadWps() ){ - if(wb!=null && !TextUtils.isEmpty(wb.getRoadBook())){ - - _roadBook.append(++i+ ") " - +String.format(QiYouConstant.FOOT_MARK_TURN_TEMPLATE,wb.getRoadBook())//.replace("\"", "")) - +"\n"); - -// if(showMd)_roadBook.append(getMds(last,wb.getTime())); - if(showMd)_roadBook.append(getMds(last,wb.getSumDist())); - - -// last =i==0?0:wb.getTime(); - last =i==0?0:wb.getSumDist(); - - } - } - - if( _lastWp.getWb().getGeo()!=null ) - _roadBook.append(String.format("终点:" + QiYouConstant.FOOT_MARK_TURN_TEMPLATE,_lastWp.getWb().getGeo().toString(","))+"\n"); - - GenFootmark(true,_roadBook.toString()); //when new geo populated, the footmark file content will be cleared.force to fill the the content. - - -// for(int i=0;i"); - } - - - return _roadBook; -} -*/ - - -//String getMds(long start,long end){ -/*String getMds(float start,float end){ - - - String rt=""; - String filePath;// =QiYouConstant.PHOTO_PATH + tb.getTrackId()+"/" ; - for(Waypoint_bean wb:tb.getMdWps()){ -// if(wb!=null && wb.getTime()>=start && wb.getTime()<=end){ - if(wb!=null && wb.getSumDist()>=start && wb.getSumDist()<=end){ - for(Media md: wb.getMedias()){ - filePath =this.getMediaPah(md.getType()); - String path = md.getUri(); - path = filePath +path; //to remove. - rt += "

" - + "" - + "

"; - if(!TextUtils.isEmpty( md.getComment())) - rt += "图片说明: " +"

" - +md.getComment() - +"

"; - - switch( md.getType()){ - case PIC: - break; - case MAP: - break; - case SOUND: - break; - case VIDEO: - break; - default: - break; - - } - } - } - - } - - return rt; -}*/ -/* - * create the foomark html file content - */ -public void GenFootmark(boolean byForce,String roadbook){ - - File myFile = new File(getFootMarkfileName()); - FileOutputStream fOut =null; - try { - if(!myFile.exists()){ - myFile.createNewFile(); - fOut = new FileOutputStream(myFile,false); //override - fOut.write(roadbook.getBytes()); - fOut.close(); - }else if(byForce){ - fOut = new FileOutputStream(myFile,false); //override - fOut.write(roadbook.getBytes()); - fOut.close(); - } - } catch (IOException e1) { - // TODO Auto-generated catch block - Utils.logStackTrace(e1, TAG); - } -// finally{ -// if(fOut!=null){ -// fOut.close(); -// } - - } - -//读文件 - -public String getFootmark(){ - String res=null; - try { - - res = Utils.readSDFile(getFootMarkfileName()); - - - }catch (IOException e1) { - // TODO Auto-generated catch block - Utils.logStackTrace(e1, TAG); - } - return res; -} -public String getFootMarkfileName(){ - - File dir = new File(QiYouConstant.FOOTMARK_PATH); - if(!dir.exists()) dir.mkdirs();// 创建文件夹 - - return QiYouConstant.FOOTMARK_PATH+tb.getTrackId() +".html"; - -} -/* - * clear the footmark file - */ -public void TruncateFootMark(){ - File file = new File(getFootMarkfileName()); - if(file.exists()){ - try { - FileOutputStream fOut = new FileOutputStream(file); //override - fOut.write(new String().getBytes()); - fOut.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - } -} - - -public void setRoadBook(StringBuffer _roadBook) { - this._roadBook = _roadBook; -} -/* - * temporaly json wps for roadbear - */ -public StringBuffer getRdWpsJson() { - return _rdWpsJson; -} -public void setRdWpsJson(StringBuffer sb) { - _rdWpsJson =sb; -} - - - -/*public ArrayList getBearWps(){ - return roadWps; -}*/ - - -/* - * generate _rdWpsJson - * initialize roadbook - */ -//public void setBearWps( CopyOnWriteArrayList wbs){ -public void setBearWps( ArrayList wbs){ - tb.setRoadWps(wbs); - - Gson gson = new Gson(); - try{ - _rdWpsJson =new StringBuffer(); - _rdWpsJson.append(gson.toJson(wbs)); - }catch(Exception e) - { - Utils.logStackTrace(e, dTAG); - } - _roadBook = new StringBuffer(); -} -public void finishRecording(){ -// getTrackBean().setStatus(QiYouConstant.TRACK_STATUS_FINISHED); -// if(_startWp!=null) -// setLastRoadBear(_startWp); - if(TrackStatus.FINISHED == tb.getStatus())return; //already be finished. - try{ - if(_maxDistWp!=null){ - _maxDistWp.getWb().setTurnFlag(wpFlag.MAXR); - setLastRoadBear(_maxDistWp); - // QLog.getLogger().d(dTAG,TAG+" set marR WP to the roadbear \n "+ _maxDistWp.toString()); - } - - if(_lastWp!=null){ - _lastWp.getWb().setTurnFlag(wpFlag.END); - setLastRoadBear(_lastWp); - // QLog.getLogger().d(dTAG,TAG+" set last WP to the roadbear \n "+ _lastWp.toString()); - } - - this.setBearWps(tb.getRoadWps()); //apply the maxR,Lastwp change to the jsonBear and reset the roadbook - }catch(Exception er){ - Utils.logStackTrace(er, TAG); - } - -// tb.setEndTime(System.currentTimeMillis()); - /* long ttime=tb.getTotalTime()-(tb.getEndTime()-tb.getStartTime()); - if( ttime>0){ - tb.setOffTime(tb.getOffTime()-ttime); - }*/ -} - -public String getMaxRdistWpJson() { - return _maxDistWpJson; -} - -public void setMaxRdistWpJson(String maxDistWpJson) { - _maxDistWpJson = maxDistWpJson; - _maxDistWp = new Waypoint(maxDistWpJson); - tb.setMaxDistWp(_maxDistWp); - -} - -public Waypoint getMaxDistWp() { - return _maxDistWp; -} - -public void setMaxDistWp(Waypoint maxDistWp) { - _maxDistWp = maxDistWp; -} -private String summary =""; -public String getSummary(){ - if(tb.getType()==TrackType.GPX)return getGPXSummary(); - - - String startEndGeos = ""; - final String blankStr=""; - if(_startWp==null ||_lastWp ==null) return summary; - - int picCnt=0; - for(Waypoint_bean wb:tb.getMdWps()){ - if(wb!=null){ - Media md =wb.getMedias().get(0); - if(md!=null && md.getType() == mediaType.PIC){ - picCnt++; - } - - } - } - - String medias=String.format("%s运动过程没有记录拍摄照片。",blankStr);//;=String.format("\n拍照片%s张",); - if(picCnt>0) - medias =String.format("%s期间拍照片%s张。",blankStr,picCnt); - String speedData=String.format("%s期间最高速度%.2f公里/每小时,平均运动速度%.2f公里/小时,全程均速%.2f公里/小时,", - blankStr, - tb.getTopSpeed(), - tb.getAvs(), - tb.getTavs() - ); - String overall=String.format("共%s%s。", - "运动了",//getTrackBean().getType().toCHString(), - Utils.getFormatedDistance(tb.getDistance()) - ); - if(_startWp.getWb().getGeo()!=null && _lastWp.getWb().getGeo()!=null ) - startEndGeos =String.format(" %s%s 从%s出发,%s 到达%s,", - blankStr, - Utils.getFormatedTimeMonthDay(tb.getStartTime()), - _startWp.getWb().getGeo().toString(","), - Utils.getFormatedTimeMonthDay(tb.getEndTime()), - _lastWp.getWb().getGeo().toString(_startWp.getWb().getGeo(),",") - ); - else{ - startEndGeos =String.format(" %s自%s至%s,", - blankStr, - Utils.getFormatedTimeMonthDay(tb.getStartTime()), - Utils.getFormatedTimeMonthDay(tb.getEndTime()) - ); - } - - String distTime =String.format("历时%s,其中运动时间%s,", - Utils.getTimeCnt4Read(tb.getEndTime()- tb.getStartTime(), true), - Utils.getTimeCnt4Read(tb.getSportTime(), true) - ); - - String eup =String.format("累计爬升%.0f米,累计下降%.0f米,", - tb.geteUpDist(), - tb.geteDownDist()*-1 - ); - - String cost =String.format("%s本次运动共消耗%.1f卡路里,继续加油~o~",blankStr,getCalBurn());//String.format("\n消耗%.0f大卡",tb.getCost()); - - summary = Utils.getWeather() - + startEndGeos - + distTime - + overall - + speedData - + eup - + medias - + cost - ; - - return summary; -} - -public String getGPXSummary(){ - String summary =""; - String startEndGeos = ""; - final String blankStr=" "; - if(_startWp==null ||_lastWp ==null) return summary; - -// int picCnt=0; -// for(Waypoint_bean wb:tb.getMdWps()){ -// if(wb!=null){ -// Media md =wb.getMedias().get(0); -// if(md!=null && md.getType() == mediaType.PIC){ -// picCnt++; -// } -// -// } -// } -// -// String medias=String.format("\n%s本次运动过程中没有拍照记录。",blankStr);//;=String.format("\n拍照片%s张",); -// if(picCnt>0) -// medias =String.format("\n%s期间拍照片%s张。",blankStr,picCnt); - String speedData=isGpx()?"":String.format("\n%s期间最高速度%.2f公里/每小时,全程均速%.2f公里/小时。", - blankStr, - tb.getTopSpeed(), -// tb.getAvs(), - tb.getTavs() - ); - - if(_startWp.getWb().getGeo()!=null && _lastWp.getWb().getGeo()!=null ) - startEndGeos =String.format("%s%s从%s出发,\n%s到达%s,", - blankStr, - Utils.getFormatedTime(tb.getStartTime()), - _startWp.getWb().getGeo().toString(","), - Utils.getFormatedTime(tb.getEndTime()), - _lastWp.getWb().getGeo().toString(",") - ); - else{ - startEndGeos =isGpx()?"":String.format("%s自%s至%s,", - blankStr, - Utils.getFormatedTime(tb.getStartTime()), - Utils.getFormatedTime(tb.getEndTime()) - ); - } - - - - String creator =String.format("%s\n", - tb.getCreator() -// Utils.getTimeCnt(tb.getSportTime()) - ); - -// String cost =String.format("\n%s本次运动共消耗%.2f卡路里,继续加油~o~",blankStr,getCalBurn());//String.format("\n消耗%.0f大卡",tb.getCost()); -// if(isGpx()){ -// -// } - - summary = Utils.getWeather() - +(TextUtils.isEmpty(tb.getCreator())?"": creator) - + startEndGeos - + getGpxDistTime() - + speedData -// + medias -// + cost - ; - - - - return summary; -} - -public String getGpxDistTime(){ -/* String overall=String.format("全程%s,", - Utils.getFormatedDistance(tb.getDistance()) - ); - String distTime =String.format("预计历时%s。", - Utils.getTimeCnt4Read(tb.getEndTime()- tb.getStartTime(), true) -// Utils.getTimeCnt(tb.getSportTime()) - ); - return overall +distTime;*/ - - return String.format("全程%s,", Utils.getFormatedDistance(tb.getDistance())); -} - -public StringBuffer getMdWpsJson() { - return _mdWpsJson; -} - -public void setMdWpsJson(String mdWps ) { - this._mdWpsJson.append(mdWps); -// getWPS(new Gson(),mdWps); - -} -/* - * generate _rdWpsJson - * initialize roadbook - */ -/*public void setMdWps( ArrayList wbs){ - tb.setRoadWps(wbs); - _mdWpsJson =new StringBuffer(); - Gson gson = new Gson(); - try{ - _mdWpsJson.append(gson.toJson(wbs)); - }catch(Exception e) - { - Utils.logStackTrace(e, dTAG); - } - -}*/ -public float getCalBurn(){ - return getCalBurn(tb.getType()); -} - -public float getCalBurn(TrackType type){ -/* float mets =Utils.getMets(type,tb.getAvs()); - float weight=QiYouConstant.PV_USER_WEIGHT; - float hours =tb.getSportTime()/(3600f*1000f); - float calories =mets*weight*(hours); - float eUp =tb.getEsumUp() ; - float mgh =0; - if(calories>0 && eUp>0){ - mgh =weight*9.8f*eUp; - mgh =mgh/4.184f; - - } -// calories +=mgh; - calories =calories>0?calories:0;*/ - float avs=tb.getAvs(); - avs=avs>0?avs:tb.getTavs(); - long sptime=tb.getSportTime(); - sptime=sptime>0?sptime:tb.getTotalTime(); - float calories=(float) Utils.getCalories(type,avs,sptime,tb.getEsumUp()); - - tb.setBurn(calories); - return calories; -} - -//public ArrayList roadWbs = new ArrayList(); -//public String wps2json( CopyOnWriteArrayList wbs){ - public String wps2json( ArrayList wbs){ - String json=""; - Gson gson = new Gson(); - try{ - json=gson.toJson(wbs); - }catch(Exception e) - { - Utils.logStackTrace(e, dTAG); - } - return json; -} - -public void setMd(String picName,Waypoint wp,mediaType mdType){ - -// QLog.getLogger().d(dTAG, TAG+String.format(" begin to insert new mdiea,distanceis %s",distance)); - - - /*Waypoint wp = new Waypoint(); - if(distance>0){//for map - wp.getWb().setSumDist(distance); - } - else if( getLastWp()!=null){*/ - if(wp==null && getLastWp()!=null){ - wp = new Waypoint(); - wp.getWb().setLatitude( getLastWp().getWb().getLatitude()); - wp.getWb().setLongitude( getLastWp().getWb().getLongitude()); - wp.getWb().setTime( getLastWp().getWb().getTime()); - wp.getWb().setSumDist( getLastWp().getWb().getSumDist()); - wp.getWb().setSpeed( getLastWp().getWb().getSpeed()); - wp.getWb().setElevation( getLastWp().getWb().getElevation()); - } - - if(wp == null)wp = new Waypoint(); -// wp.getWb().getMedias().clear();//each md with a wb, //TODO: to update to let wb can have more medias, - - boolean isExist=false; - for(Media m: wp.getWb().getMedias()){ - if(m.getUri().equalsIgnoreCase(picName)){ - isExist=true; - break; - } - } - if(!isExist){ - Media md = new Media(); - md.setTime(System.currentTimeMillis()); - md.setType(mdType); - md.setUri(picName); - wp.getWb().getMedias().add(md); - } - newMdWpsJson.append(wp.toJsonWp()+","); -// activity.app.getRecordingTrack().setLastWp(wp); -// activity.app.getRecordingTrack().getTrackBean().getMdWps().add(wp.getWb()); - tb.getMdWps().add(wp.getWb()); - -} - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/User.java b/qy/src/main/java/com/qiyou/mb/android/beans/User.java deleted file mode 100644 index c5ec504..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/User.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.qiyou.mb.android.beans; - -import java.util.ArrayList; - -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.User_bean; - -public class User { -public User(){} - -private User_bean user_bean; -private ArrayList groups; -private ArrayList activities; -private Statistics statistics; -private Track lastTrack; -private ArrayList tracks; - - -public boolean login(){ - return true; -} - -public boolean update(){ - return true; -} - -public boolean create(){ - return true; -} - -public boolean logout(){ - return true; -} - -public boolean delete(){ - return true; -} - - - -/** - * @return the user_bean - */ -public User_bean getUserbean() { - if(user_bean==null)user_bean =new User_bean(); - return user_bean; -} -/** - * @param user_bean the user_bean to set - */ -public void setUserbean(User_bean user_bean) { - this.user_bean = user_bean; -} -/** - * @return the groups - */ -public ArrayList getGroups() { - return groups; -} -/** - * @param groups the groups to set - */ -public void setGroups(ArrayList groups) { - this.groups = groups; -} -/** - * @return the activities - */ -public ArrayList getActivities() { - return activities; -} -/** - * @param activities the activities to set - */ -public void setActivities(ArrayList activities) { - this.activities = activities; -} -/** - * @return the statistics - */ -public Statistics getStatistics() { - return statistics; -} -/** - * @param statistics the statistics to set - */ -public void setStatistics(Statistics statistics) { - this.statistics = statistics; -} -/** - * @return the lastTrack - */ -public Track getLastTrack() { - return lastTrack; -} -/** - * @param lastTrack the lastTrack to set - */ -public void setLastTrack(Track lastTrack) { - this.lastTrack = lastTrack; -} - -public ArrayList getTracks() { - return tracks; -} - -public void setTracks(ArrayList tracks) { - this.tracks = tracks; -} - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Activity_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Activity_bean.java deleted file mode 100644 index d2e3080..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Activity_bean.java +++ /dev/null @@ -1,271 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import java.util.ArrayList; - -import android.text.TextUtils; - -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.ActivityStatus; -import com.qiyou.mb.android.utils.enums.ActivityType; - -public class Activity_bean { - -//private int id; -private int svrNumber; -private String name; -public int getSvrNumber() { - return svrNumber; -} -public void setSvrNumber(int svrNumber) { - this.svrNumber = svrNumber; -} -public String getName() { - return name; -} -public void setName(String name) { - this.name = name; -} - -public long getStartDate() { - return startDate; -} -public void setStartDate(long startDate) { - this.startDate = startDate; -} -public long getEndDate() { - return endDate; -} -public void setEndDate(long endDate) { - this.endDate = endDate; -} -public String getLocation() { - return location; -} -public void setLocation(String location) { - this.location = location; -} -public ActivityType getType() { - return type; -} -public void setType(ActivityType type) { - this.type = type; -} -public String getDescription() { - return description; -} -public void setDescription(String description) { - this.description = description; -} -public ArrayList getRoadbooks() { - if(roadbooks==null){ - roadbooks=new ArrayList(); - } - return roadbooks; -} -public void setRoadbooks(ArrayList roadbooks) { - this.roadbooks = roadbooks; -} -public GEO_bean getStartGeo() { - if(startGeo==null ){ - if(!TextUtils.isEmpty(startJsonString )){ - startGeo =(GEO_bean) Utils.getGsonObject(startJsonString, GEO_bean.class); - } - if(startGeo==null){ - startGeo= new GEO_bean(); - } - } - return startGeo; -} -public void setStartGeo(GEO_bean startGeo) { - this.startGeo = startGeo; -} -public GEO_bean getEndGeo() { - if(endGeo==null){ - if(!TextUtils.isEmpty(endJsonString )){ - endGeo =(GEO_bean) Utils.getGsonObject(endJsonString, GEO_bean.class); - } - if(endGeo==null){ - endGeo= new GEO_bean(); - } - } - return endGeo; -} -public void setEndGeo(GEO_bean endGeo) { - this.endGeo = endGeo; -} -public ActivityStatus getStatus() { - if(status==null){ - status =ActivityStatus.ACTIVE; - } - return status; -} -public void setStatus(ActivityStatus status) { - this.status = status; -} -public long getLastupdated() { - return lastupdated; -} -public void setLastupdated(long lastupdated) { - this.lastupdated = lastupdated; -} -public String getStartJsonString() { - return startJsonString; -} -public void setStartJsonString(String startJsonString) { - this.startJsonString = startJsonString; -} -public String getEndJsonString() { - return endJsonString; -} -public void setEndJsonString(String getEndJsonString) { - this.endJsonString = getEndJsonString; -} -//private float distrange=-1f; -private int userId; -private String userName; -private long startDate; -private long endDate; -private String location; -private ActivityType type =ActivityType.PUBLIC ; -private String description; -private ArrayList roadbooks; -private GEO_bean startGeo; -private GEO_bean endGeo; -private ActivityStatus status =ActivityStatus.ACTIVE; -private long lastupdated; -private String startJsonString; -private String endJsonString; -private String startPlace; -private String startAddress; -private String endPlace; -private String endAddress; -private String startAddressUrl; -private String endAddressUrl; -private float rateLevel; -private float lat; -private float lon; -private String album; -private float distance; -private float avSpeed; -private ArrayList days; -private boolean repeatable; -private int userCnt; - -public String getStartPlace() { - return startPlace; -} -public void setStartPlace(String startPlace) { - this.startPlace = startPlace; -} -public String getStartAddress() { - return startAddress; -} -public void setStartAddress(String startAddress) { - this.startAddress = startAddress; -} -public String getEndPlace() { - return endPlace; -} -public void setEndPlace(String endPlace) { - this.endPlace = endPlace; -} -public String getEndAddress() { - return endAddress; -} -public void setEndAddress(String endAddress) { - this.endAddress = endAddress; -} -public float getRateLevel() { - return rateLevel; -} -public void setRateLevel(float rateLevel) { - this.rateLevel = rateLevel; -} -public float getLat() { - return lat; -} -public void setLat(float lat) { - this.lat = lat; -} -public float getLon() { - return lon; -} -public void setLon(float lon) { - this.lon = lon; -} -/*public float getDistrange() { - return distrange; -} -public void setDistrange(float distrange) { - this.distrange = distrange; -}*/ -public String getUserName() { - return userName; -} -public void setUserName(String userName) { - this.userName = userName; -} -public float getDistance() { - return distance; -} -public void setDistance(float distance) { - this.distance = distance; -} -public float getAvSpeed() { - return avSpeed; -} -public void setAvSpeed(float avSpeed) { - this.avSpeed = avSpeed; -} -public ArrayList getDays() { - if(days==null){ - days= new ArrayList(); - } - return days; -} -public void setDays(ArrayList days) { - this.days = days; -} - -public boolean isRepeatable() { - return repeatable; -} -public void setRepeatable(boolean repeatable) { - this.repeatable = repeatable; -} -public int getUserId() { - return userId; -} -public void setUserId(int userId) { - this.userId = userId; -} -public String getStartAddressUrl() { - return startAddressUrl; -} -public void setStartAddressUrl(String startAddressUrl) { - this.startAddressUrl = startAddressUrl; -} -public String getEndAddressUrl() { - return endAddressUrl; -} -public void setEndAddressUrl(String endAddressUrl) { - this.endAddressUrl = endAddressUrl; -} -public int getUserCnt() { - return userCnt; -} -public void setUserCnt(int userCnt) { - this.userCnt = userCnt; -} -public String getAlbum() { - return album; -} -public void setAlbum(String album) { - this.album = album; -} - - - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/BStatistics.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/BStatistics.java deleted file mode 100644 index 0c70635..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/BStatistics.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - - -public class BStatistics { - public static String TAG ="com.qiyou.beans.Statistics"; - public static String dTAG ="com.qiyou"; - protected long firstTime=0; - protected long lastTime=0; - protected int cnt; - protected int userId; - protected float sumBurn =0.0f; //累积消耗卡路里 - protected float sumeUpDist =0.0f; //累积上升 - protected float sumeDownDist =0.0f; //累积下降 - protected float sumTopSpeed =0.0f; - protected float sumDist =0.0f; - protected long sumPause=0 ; - protected long sumSportTime =0; - protected long sumOffTime =0; //no gps time - protected long sumTotalTime=0 ; - protected float sumUpDist=0.0f; - protected float maxEle=0.0f; - protected float minEle=0.0f; - protected long lastGeo=0; - protected int lastTrackId=0; - protected float sumDownDist=0.0f; - protected HashMap> categoryList; - protected HashMap gpList; - protected TypeStatistics lastStrack; - protected ConcurrentHashMap statisticsTracks; - protected List typeUsedLst; - protected List existedSvrNos; - - public float getSumUpDist() { - return sumUpDist; - } - - - public float getSumDownDist() { - return sumDownDist; - } - - - - public int getUserId() { - return userId; - } - - public void setUserId(int userId) { - this.userId = userId; - } - - - public float getSumCost() { - return sumBurn; - } - - public void setSumCost(float sumBurn) { - this.sumBurn += sumBurn; - } - - public float getSumeUpDist() { - return sumeUpDist; - } - - /*public void setSumUpDist(float sumUpDist) { - this.sumeUpDist += sumUpDist; - }*/ - - public float getSumeDownDist() { - return sumeDownDist; - } - - public void setSumDownDist(float sumeDownDist) { - this.sumeDownDist += sumeDownDist; - } - - public float getSumTopSpeed() { - return sumTopSpeed; - } - - public void setSumTopSpeed(float sumTopSpeed) { - this.sumTopSpeed += sumTopSpeed; - } - - public long getSumPause() { - return sumPause; - } - - public void setSumPause(long sumPause) { - this.sumPause += sumPause; - } - - public long getSumSportTime() { - return sumSportTime; - } - - public void setSumSportTime(long sumSportTime) { - this.sumSportTime += sumSportTime; - } - - public long getSumOffTime() { - return sumOffTime; - } - - public void setSumOffTime(long sumOffTime) { - this.sumOffTime += sumOffTime; - } - - public long getSumTotalTime() { - return sumTotalTime; - } - - public void setSumTotalTime(long sumTotalTime) { - this.sumTotalTime += sumTotalTime; - } - -// private SparseArray StatisticsTracks; - - - public List getTypeUsedLst() { - if(typeUsedLst==null)typeUsedLst =new ArrayList(); - return typeUsedLst; - } - - public void setTypeUsedLst(List typeUsedLst) { - this.typeUsedLst = typeUsedLst; - } - - public long getLastTime() { - return lastTime; - } - - public void setLastTime(long lTime) { - lastTime = lastTimestime?stime:firstTime); - } - - public ConcurrentHashMap getStatisticsTracks() { - if( statisticsTracks==null) statisticsTracks =new ConcurrentHashMap(); - return statisticsTracks; - } - - public void setStatisticsTracks(ConcurrentHashMap _statisticsTracks) { - statisticsTracks = _statisticsTracks; - } - - public int getCnt() { - return cnt; - } - - public void setCnt(int cnt) { - this.cnt = cnt; - } - - public void setMaxAvStat(StatTrack maxAvTrack){ - if(maxAvTrack==null)return; - - TypeStatistics stt= getStatisticsTracks().get(Integer.valueOf(maxAvTrack.getType())); - StatTrack st; - if(stt!=null &&stt.getStatTrack()!=null){ - st =stt.getStatTrack(); - sumBurn -=st.getSumBurn(); //累积消耗卡路里 - sumeUpDist -=st.getSumEup(); //累积上升 - sumeDownDist -=st.getSumEdown(); //累积下降 - sumPause -= st.getSumPause(); - sumSportTime -=st.getSumSportTime(); - sumOffTime -=st.getSumOff(); //no gps time - sumTotalTime -=st.getSumTotalTime() ; - sumDist -=st.getSumDist(); - sumUpDist-=st.getSumUpDist(); - sumDownDist-=st.getSumDownDist(); -// cnt--; - } - - sumBurn +=maxAvTrack.getSumBurn(); //累积消耗卡路里 - sumeUpDist +=maxAvTrack.getSumEup(); //累积上升 - sumeDownDist +=maxAvTrack.getSumEdown(); //累积下降 - sumPause += maxAvTrack.getSumPause(); - sumSportTime +=maxAvTrack.getSumSportTime(); - sumOffTime +=maxAvTrack.getSumOff(); //no gps time - sumTotalTime +=maxAvTrack.getSumTotalTime() ; - sumDist +=maxAvTrack.getSumDist(); - sumUpDist +=maxAvTrack.getSumUpDist() ; - sumDownDist +=maxAvTrack.getSumDownDist(); -// cnt++; - } - - public float getSumDist() { - return sumDist; - } - - public void setSumDist(float sumDist) { - this.sumDist = sumDist; - } - - - -public TypeStatistics getLastStrack() { - if(lastStrack==null)lastStrack= new TypeStatistics(); - return lastStrack; -} - -public void setLastStrack(TypeStatistics lastStrack) { - this.lastStrack = lastStrack; -} - -public HashMap> getCategoryList() { - if(categoryList==null)categoryList= new HashMap> (); - return categoryList; -} -public void setCategoryList(HashMap> categoryList) { - this.categoryList = categoryList; -} - -public HashMap getGpList() { - if(gpList==null)gpList=new HashMap(); - return gpList; -} - - -public void setGpList(HashMap gpList) { - this.gpList = gpList; -} - -// ArrayList mergedTracks =new ArrayList(); -// HashMap mergedTracks =new HashMap(); - -/* - * km/h - */ - public float getAVS(){ - return getSumSportTime()>0? 3600*getSumDist()/ getSumSportTime():0; - } - -public List getExistedSvrNos() { - if(existedSvrNos==null)existedSvrNos =new ArrayList(); - return existedSvrNos; -} - -public void setExistedSvrNos(List existedSvrNos) { - this.existedSvrNos = existedSvrNos; -} - -public float getMaxEle() { - return maxEle; -} - -public void setMaxEle(float maxEle) { - this.maxEle = maxEle; -} - -public float getMinEle() { - return minEle; -} - -public void setMinEle(float minEle) { - this.minEle = minEle; -} - -public long getLastGeo() { - return lastGeo; -} - -public void setLastGeo(long lastGeo) { - this.lastGeo = lastGeo; -} - -public int getLastTrackId() { - return lastTrackId; -} - -public void setLastTrackId(int lastTrackId) { - this.lastTrackId = lastTrackId>this.lastTrackId?lastTrackId:this.lastTrackId; -} - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/CItem.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/CItem.java deleted file mode 100644 index 9407f88..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/CItem.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -public class CItem { - private String id = ""; - private String value = ""; - private int cnt=0; - public CItem () { - id = ""; - value = ""; - } - - public CItem (String _ID, String _Value) { - id = _ID; - value = _Value; - } - - @Override - public String toString() { //为什么要重写toString()呢?因为适配器在显示数据的时候,如果传入适配器的对象不是字符串的情况下,直接就使用对象.toString() - // TODO Auto-generated method stub - return value; - } - - public String getId() { - return id; - } - - public String getValue() { - return value; - } - - public int getCnt() { - return cnt; - } - - public void setCnt(int cnt) { - this.cnt = cnt; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Footmark_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Footmark_bean.java deleted file mode 100644 index 72da583..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Footmark_bean.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -public class Footmark_bean { - - public Footmark_bean() { - // TODO Auto-generated constructor stub - } -private String fbTitle; -private String fbComment; -private String picUrl; -private String picComment; -public String getFbTitle() { - return fbTitle; -} -public void setFbTitle(String fbTitle) { - this.fbTitle = fbTitle; -} -public String getFbComment() { - return fbComment; -} -public void setFbComment(String fbComment) { - this.fbComment = fbComment; -} -public String getPicUrl() { - return picUrl; -} -public void setPicUrl(String picUrl) { - this.picUrl = picUrl; -} -public String getPicComment() { - return picComment; -} -public void setPicComment(String picComment) { - this.picComment = picComment; -} - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEO_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEO_bean.java deleted file mode 100644 index f6d1164..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEO_bean.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -public class GEO_bean { - - public GEO_bean() { - // TODO Auto-generated constructor stub - } - public GEO_bean(int id,int parentId,int geoType,String name,String address) { - // TODO Auto-generated constructor stub - _id =id; - this.parentId = parentId; - this.name = name; - this.geoType =geoType; - this.address=address; - } - - public GEO_bean(GEOaddress gaddress) { - // TODO Auto-generated constructor stub - - if(gaddress==null)return; - this.name = gaddress.getName(); - this.address=gaddress.getAddress(); - this.lat=gaddress.getLat(); - this.lon=gaddress.getLon(); - } - - private int _id; - private int parentId; - private int geoType; - private String name; - private String comment; - private float lat; - private float lon; - - public GEO_bean(int geoId, int parentId, int geoType, String value) { - } - - public String getProName() { - return proName; - } - public void setProName(String proName) { - this.proName = proName; - } - public String getCityName() { - return cityName; - } - public void setCityName(String cityName) { - this.cityName = cityName; - } - public String getDistrictName() { - return districtName; - } - public void setDistrictName(String districtName) { - this.districtName = districtName; - } - public String getStreetName() { - return streetName; - } - public void setStreetName(String streetName) { - this.streetName = streetName; - } - private int city; - private String address; - private String proName; - private String cityName; - private String districtName; - private String streetName; - private String sharedAddressUrl; - - public int getId() { - return _id; - } - public void setId(int id) { - this._id = id; - } - public int getParentId() { - return parentId; - } - public void setParentId(int parentId) { - this.parentId = parentId; - } - public int getGeoType() { - return geoType; - } - public void setGeoType(int geoType) { - this.geoType = geoType; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getComment() { - return comment; - } - public void setComment(String comment) { - this.comment = comment; - } - public float getLat() { - return lat; - } - - public void setLat(float lat) { - this.lat = lat; - } - - public float getLon() { - return lon; - } - - public void setLon(float lon) { - this.lon = lon; - } - public String getAddress() { - return address; - } - public void setAddress(String address) { - this.address = address; - } - public String getSharedAddressUrl() { - return sharedAddressUrl; - } - public void setSharedAddressUrl(String sharedAddressUrl) { - this.sharedAddressUrl = sharedAddressUrl; - } - public int getCity() { - return city; - } - public void setCity(int city) { - this.city = city; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEOaddress.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEOaddress.java deleted file mode 100644 index 26b04bc..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEOaddress.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import android.text.TextUtils; - -public class GEOaddress { - -public GEOaddress(){ - -} -private String cityId; //bd geo cityId -private String province; -private String city; -private String district; -private String street; -private String streetNo; -private Media GEOpic; -private float lat; -private float lon; -private String address; -private String name; - - -public GEOaddress( GEO_bean geo){ - if(geo==null)return; - province =geo.getProName(); - city=geo.getCityName(); - street =geo.getStreetName(); - streetNo=geo.getName(); -} - - -public Media getGEOpic() { - return GEOpic; -} - -public void setGEOpic(Media gEOpic) { - GEOpic = gEOpic; -} -public String getProvince() { - return province; -} -public void setProvince(String province) { - this.province = province; -} -public String getCity() { - return city; -} -public void setCity(String city) { - this.city = city; -} -public String getDistrict() { - return district; -} -public void setDistrict(String district) { - this.district = district; -} -public String getStreet() { - return street; -} -public void setStreet(String street) { - this.street = street; -} -public String getStreetNo() { - return streetNo; -} -public void setStreetNo(String streetNo) { -// if(TextUtils.isEmpty(streetNo)) -// streetNo ="未知地点"; - this.streetNo = streetNo; -} -public String toString(GEOaddress geo,String split){ - - String address =""; - - if(!TextUtils.isEmpty(province) && !TextUtils.isEmpty(geo.getProvince()) && province.equalsIgnoreCase(geo.getProvince()) ){ - - if(!TextUtils.isEmpty(city) && !TextUtils.isEmpty(geo.getCity()) && city.equalsIgnoreCase(geo.getCity()) ){ - if(!TextUtils.isEmpty(district) && !TextUtils.isEmpty(geo.getDistrict()) && district.equalsIgnoreCase(geo.getDistrict()) ){ - if(!TextUtils.isEmpty(street)) - address =address + street + " "; - - if(!TextUtils.isEmpty(streetNo)) - address =address + streetNo; - }else{ - if(!TextUtils.isEmpty(district)) - address =address+ district + split; - } - - }else{ //not same city - if(!TextUtils.isEmpty(city)) - address =address+ city + split; - - if(!TextUtils.isEmpty(district)) - address =address + district+ split; - - if(!TextUtils.isEmpty(street)) - address =address + street + " "; - - if(!TextUtils.isEmpty(streetNo)) - address =address + streetNo; - - } - - - }else{ //not same province - - if(!TextUtils.isEmpty(province)) - address =address+ province + split; - - if(!TextUtils.isEmpty(city)) - address =address+ city + split; - - if(!TextUtils.isEmpty(district)) - address =address + district+ split; - - if(!TextUtils.isEmpty(street)) - address =address + street + " "; - - if(!TextUtils.isEmpty(streetNo)) - address =address + streetNo; - } - return address; -} - -public String toString(String split){ - - String address =""; - if(!TextUtils.isEmpty(province)) - address =address+ province + split; - - if(!TextUtils.isEmpty(city)) - address =address+ city + split; - - if(!TextUtils.isEmpty(district)) - address =address + district+ split; - - if(!TextUtils.isEmpty(street)) - address =address + street + " "; - - if(!TextUtils.isEmpty(streetNo)) - address =address + streetNo; - - if(TextUtils.isEmpty(name)) - return address; - else{ - return name+"\n" +address; - } -} - -public String getCityId() { - return cityId; -} - -public void setCityId(String cityId) { - this.cityId = cityId; -} - -public float getLat() { - return lat; -} - -public void setLat(float lat) { - this.lat = lat; -} - -public float getLon() { - return lon; -} - -public void setLon(float lon) { - this.lon = lon; -} - -public String getName() { - return name; -} - -public void setName(String name) { - this.name = name; -} - -public String getAddress() { - return address; -} - -public void setAddress(String address) { - this.address = address; -} - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEOs.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEOs.java deleted file mode 100644 index 53e8fab..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GEOs.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import java.util.concurrent.ConcurrentHashMap; - -import com.qiyou.mb.android.QiYouConstant; - -public class GEOs { - - public GEOs() { - // TODO Auto-generated constructor stub - } - public ConcurrentHashMap GEOprovinces = new ConcurrentHashMap(); - public ConcurrentHashMap GEOcities= new ConcurrentHashMap(); - public ConcurrentHashMap GEOdistricts = new ConcurrentHashMap(); - public ConcurrentHashMap GEOstreets = new ConcurrentHashMap(); - public ConcurrentHashMap GEOstreetNos = new ConcurrentHashMap(); - - public ConcurrentHashMap provinces = new ConcurrentHashMap(); - public ConcurrentHashMap cities= new ConcurrentHashMap(); - public ConcurrentHashMap districts = new ConcurrentHashMap(); - public ConcurrentHashMap streets = new ConcurrentHashMap(); - public ConcurrentHashMap streetNos = new ConcurrentHashMap(); - - public void putValues(GEO_bean gb){ - - int id = gb.getId(); - String name =gb.getName(); - switch (gb.getGeoType()){ - case QiYouConstant.GEO_PROVINCE: { - GEOprovinces.put(name,gb); - provinces.put(name,id); - break; - } - case QiYouConstant.GEO_CITY: { - GEOcities.put(name, gb); - cities.put(name,id); - break; - } - case QiYouConstant.GEO_DISTRICT: { - GEOdistricts.put(name, gb); - districts.put(name,id); - break; - } - case QiYouConstant.GEO_STREET: { - GEOstreets.put(name, gb); - streets.put(name,id); - break; - } - case QiYouConstant.GEO_STREETNO: { - GEOstreetNos.put(name, gb); - streetNos.put(name,id); - break; - } - } - } -} - diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GPItem.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/GPItem.java deleted file mode 100644 index 4697f2e..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/GPItem.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import com.baidu.mapapi.model.LatLng; - -//import com.baidu.platform.comapi.basestruct.GeoPoint; - -public class GPItem { - - private LatLng gp = null; - private int cnt=0; - private int ah; - private double lat; - private double lng; - - public GPItem () { - - } - - /* public GPItem (int _cnt,LatLng _gp,int _ah) { - gp=_gp; - cnt = _cnt; - ah=_ah; - } */ - - public GPItem (int _cnt,double _lat,double _lng,int _ah) { - lat=_lat; - lng=_lng; - cnt = _cnt; - ah=_ah; - } - - - - public int getCnt() { - return cnt; - } - - public void setCnt(int cnt) { - this.cnt = cnt; - } - - public LatLng getGp() { - return gp; - } - - public void setGp(LatLng gp) { - this.gp = gp; - } - - public int getAh() { - return ah; - } - - public void setAh(int ah) { - this.ah = ah; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLng() { - return lng; - } - - public void setLng(double lng) { - this.lng = lng; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Group_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Group_bean.java deleted file mode 100644 index c7e88c5..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Group_bean.java +++ /dev/null @@ -1,208 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import android.text.TextUtils; - -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.ActivityType; - -public class Group_bean { - - /* private int id; - private int svrNumber; - private String name; - private int type; - private int level; - private int score; - private GEOaddress location; - private String desc; - private User_bean owner; - private ArrayList admins; - private ArrayList users; - private Media photoAblbum; - - private float lat; - private float lon; - */ - private int userId; - private String userName; - private int id; - private String name; - private ActivityType type; - private int level; - private int score; - private float distance; -// private String location; -// private GEOaddress address; - private String desc; - private User_bean owner; - private GEO_bean geo; - private String place; - private String address; - private String album; - private Media photoAblbum; - private long created; - private long lastupdated; -// private float distrange; //距离范围查询参数 - private long sportTime; - private String startJsonString; - private float lat; - private float lon; - private int userCnt; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - - public ActivityType getType() { - return type; - } - public void setType(ActivityType type) { - this.type = type; - } - public int getLevel() { - return level; - } - public void setLevel(int level) { - this.level = level; - } - public int getScore() { - return score; - } - public void setScore(int score) { - this.score = score; - } - public float getDistance() { - return distance; - } - public void setDistance(float distance) { - this.distance = distance; - } -// public String getLocation() { -// return location; -// } -// public void setLocation(String location) { -// this.location = location; -// } -// public GEOaddress getAddress() { -// return address; -// } -// public void setAddress(GEOaddress address) { -// this.address = address; -// } - public String getDesc() { - return desc; - } - public void setDesc(String desc) { - this.desc = desc; - } - public User_bean getOwner() { - return owner; - } - public void setOwner(User_bean owner) { - this.owner = owner; - } - public GEO_bean getGeo() { - if(geo==null ){ - if(!TextUtils.isEmpty(startJsonString )){ - geo =(GEO_bean) Utils.getGsonObject(startJsonString, GEO_bean.class); - } - if(geo==null){ - geo= new GEO_bean(); - } - } - return geo; - } - public void setGeo(GEO_bean geo) { - this.geo = geo; - } - public float getLat() { - return lat; - } - public void setLat(float lat) { - this.lat = lat; - } - public float getLon() { - return lon; - } - public void setLon(float lon) { - this.lon = lon; - } - public String getAlbum() { - return album; - } - public void setAlbum(String album) { - this.album = album; - } - public Media getPhotoAblbum() { - return photoAblbum; - } - public void setPhotoAblbum(Media photoAblbum) { - this.photoAblbum = photoAblbum; - } - public int getUserId() { - return userId; - } - public void setUserId(int userId) { - this.userId = userId; - } - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public long getCreated() { - return created; - } - public void setCreated(long created) { - this.created = created; - } - public long getLastupdated() { - return lastupdated; - } - public void setLastupdated(long lastupdated) { - this.lastupdated = lastupdated; - } -// public float getDistrange() { -// return distrange; -// } -// public void setDistrange(float distrange) { -// this.distrange = distrange; -// } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public long getSportTime() { - return sportTime; - } - public void setSportTime(long sportTime) { - this.sportTime = sportTime; - } - public int getUserCnt() { - return userCnt; - } - public void setUserCnt(int userCnt) { - this.userCnt = userCnt; - } - public String getPlace() { - return place; - } - public void setPlace(String place) { - this.place = place; - } - public String getAddress() { - return address; - } - public void setAddress(String address) { - this.address = address; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/MaxTrack.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/MaxTrack.java deleted file mode 100644 index 13be5f1..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/MaxTrack.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - - -public class MaxTrack { - - public MaxTrack() { - // TODO Auto-generated constructor stub - } - private float dist =0.0f; - private float eUpDist =0.0f; //累积上升 - private float eDownDist =0.0f; //累积下降 - private float topSpeed =0.0f; - private long pause=0 ; - private int type; //0,1,2...(bike,walk,car) - private long sportTime =0; - private long offTime =0; //no gps time - private long toTalTime=0 ; - private float maxR =0;//max radius - private float avSpeed=0; - - private float upDist; - private float downDist; - private float maxEle; - private float minEle; - public float getDist() { - return dist; - } - public void setDist(float dist) { - if(dist >this.dist) - this.dist = dist; - } - public float geteUpDist() { - return eUpDist; - } - public void seteUpDist(float eUpDist) { - if(eUpDist >this.eUpDist) - this.eUpDist = eUpDist; - } - public float geteDownDist() { - return eDownDist; - } - public void seteDownDist(float eDownDist) { - if(Math.abs(eDownDist) >this.eDownDist) - this.eDownDist = Math.abs(eDownDist); - } - public float getTopSpeed() { - return topSpeed; - } - public void setTopSpeed(float topSpeed) { - if(topSpeed >this.topSpeed) - this.topSpeed = topSpeed; - } - public long getPause() { - return pause; - } - public void setPause(long pause) { - if(pause >this.pause) - this.pause = pause; - } - public int getType() { - return type; - } - public void setType(int type) { - - this.type = type; - } - public long getSportTime() { - return sportTime; - } - public void setSportTime(long sportTime) { - if(sportTime >this.sportTime) - this.sportTime = sportTime; - } - public long getOffTime() { - return offTime; - } - public void setOffTime(long offTime) { - if(offTime >this.offTime) - this.offTime = offTime; - } - public float getMaxR() { - return maxR; - } - public void setMaxR(float maxR) { - if(maxR >this.maxR) - this.maxR = maxR; - } - public float getAvSpeed() { - return avSpeed; - } - public void setAvSpeed(float avSpeed) { - if(avSpeed >this.avSpeed) - this.avSpeed = avSpeed; - } - public long getTotalTime() { - return toTalTime; - } - public void setTotalTime(long toTalTime) { - if(toTalTime >this.toTalTime) - this.toTalTime = toTalTime; - } - - public float getUpDist() { - return upDist ; - - } - public float getDownDist() { - - return downDist; - } - public float getMaxEle() { - return maxEle; - - } - public float getMinEle() { - - return minEle; - } - - public void setUpDist(float upDist) { - if(Float.isInfinite(upDist) ||Float.isNaN(upDist) ||upDist<=0)return; - - if(upDist >this.upDist) - this.upDist = upDist; - } - - - public void setDownDist(float downDist) { - if(Float.isInfinite(downDist) ||Float.isNaN(downDist) ||downDist<=0)return; - if(downDist >this.downDist) - this.downDist = downDist; - } - - - public void setMaxEle(float maxEle) { - if(Float.isInfinite(maxEle) ||Float.isNaN(maxEle) ||maxEle<=0)return; - - if(maxEle >this.maxEle) - this.maxEle = maxEle; - } - - - - public void setMaxMinEle(float minEle) { - if(Float.isInfinite(minEle) ||Float.isNaN(minEle) ||minEle<=0)return; - - if(minEle < this.minEle) - this.minEle = minEle; - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Media.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Media.java deleted file mode 100644 index a8312fd..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Media.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import com.qiyou.mb.android.utils.enums.mediaStatus; -import com.qiyou.mb.android.utils.enums.mediaType; - - -public class Media { - - public Media() { - } - private mediaType type; - private String uri;//source file - private String svrUri;//source file - private String svrThumbUrl; - private String cmt;//comment - private long time; - private int trackSvrNumber; - private int trackId; - private mediaStatus status =mediaStatus.NORMAL; - - public mediaType getType() { - if(type==null) type=mediaType.PIC; - return type; - } - - public void setType(mediaType type) { - this.type = type; - } - - public String getUri() { - return uri; - } - public void setUri(String uri) { - this.uri = uri; - } - public String getComment() { - return cmt; - } - public void setComment(String cmt) { - this.cmt = cmt; - } - public long getTime() { - return time; - } - public void setTime(long time) { - this.time = time; - } - - public mediaStatus getStatus() { - return status; - } - - public void setStatus(mediaStatus status) { - this.status = status; - } - - public String getSvrUri() { - return svrUri; - } - - public void setSvrUri(String svrUri) { - this.svrUri = svrUri; - } - - public int getTrackSvrNumber() { - return trackSvrNumber; - } - - public void setTrackSvrNumber(int trackSvrNumber) { - this.trackSvrNumber = trackSvrNumber; - } - - public int getTrackId() { - return trackId; - } - - public void setTrackId(int trackId) { - this.trackId = trackId; - } - - public String getSvrThumbUrl() { - return svrThumbUrl; - } - - public void setSvrThumbUrl(String svrThumbUrl) { - this.svrThumbUrl = svrThumbUrl; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Note.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Note.java deleted file mode 100644 index 61c4ed1..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Note.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -public class Note { - private int id; - private int userId; - private String userName; -// private User_bean owner; - private String title; - private String body; - private long created; - private long lastupdated; - private String lastReplyer; - private int replyCnt; - private int lastReplyerId; - - private int category; - private int subCate; - private String subCateName ; - private int cateOwnerId ; - private int priority; - private int mainPriority ; - private int catePriority ; - private String userAlbum; - private String lastEditBy; - private int status;//0,normal;1,can not reply set by author;2 can not reply set by cateowner;3,can not reply by power - - public int getCategory() { - return category; - } - public void setCategory(int category) { - this.category = category; - } - public int getSubCate() { - return subCate; - } - public void setSubCate(int subCate) { - this.subCate = subCate; - } - public String getSubCateName() { - return subCateName; - } - public void setSubCateName(String subCateName) { - this.subCateName = subCateName; - } - public int getCateOwnerId() { - return cateOwnerId; - } - public void setCateOwnerId(int cateOwnerId) { - this.cateOwnerId = cateOwnerId; - } - public int getPriority() { - return priority; - } - public void setPriority(int priority) { - this.priority = priority; - } - public int getMainPriority() { - return mainPriority; - } - public void setMainPriority(int mainPriority) { - this.mainPriority = mainPriority; - } - public int getCatePriority() { - return catePriority; - } - public void setCatePriority(int catePriority) { - this.catePriority = catePriority; - } - - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public int getUserId() { - return userId; - } - public void setUserId(int userId) { - this.userId = userId; - } - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } - - public String getBody() { - return body; - } - public void setBody(String body) { - this.body = body; - } - public long getCreated() { - return created; - } - public void setCreated(long created) { - this.created = created; - } - public long getLastupdated() { - return lastupdated; - } - public void setLastupdated(long lastupdated) { - this.lastupdated = lastupdated; - } - - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public String getLastReplyer() { - return lastReplyer; - } - public void setLastReplyer(String lastReplyer) { - this.lastReplyer = lastReplyer; - } - public int getReplyCnt() { - return replyCnt; - } - public void setReplyCnt(int replyCnt) { - this.replyCnt = replyCnt; - } - public int getLastReplyerId() { - return lastReplyerId; - } - public void setLastReplyerId(int lastReplyerId) { - this.lastReplyerId = lastReplyerId; - } - public String getUserAlbum() { - return userAlbum; - } - public void setUserAlbum(String userAlbum) { - this.userAlbum = userAlbum; - } - public String getLastEditBy() { - return lastEditBy; - } - public void setLastEditBy(String lastEditBy) { - this.lastEditBy = lastEditBy; - } - public int getStatus() { - return status; - } - public void setStatus(int status) { - this.status = status; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/NoteMessage.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/NoteMessage.java deleted file mode 100644 index d37f4c2..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/NoteMessage.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -public class NoteMessage { - - private int id; - - private int noteId; - private int userId; - private int parentId;//reply to, the parent can be note or note message,parentid==0 :reply to note, else reply to msg - private String title; - private String body; - private long created; - private long lastupdated; - private String userName; - private String userAlbum; - private String lastEditBy; - private int cateOwnerId ; - private int noteOwnerId; - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public int getUserId() { - return userId; - } - public void setUserId(int userId) { - this.userId = userId; - } - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } - - public String getBody() { - return body; - } - public void setBody(String body) { - this.body = body; - } - public int getNoteId() { - return noteId; - } - public void setNoteId(int noteId) { - this.noteId = noteId; - } - public int getParentId() { - return parentId; - } - public void setParentId(int parentId) { - this.parentId = parentId; - } - public long getLastupdated() { - return lastupdated; - } - public void setLastupdated(long lastupdated) { - this.lastupdated = lastupdated; - } - public long getCreated() { - return created; - } - public void setCreated(long created) { - this.created = created; - } - public String getUserAlbum() { - return userAlbum; - } - public void setUserAlbum(String userAlbum) { - this.userAlbum = userAlbum; - } - public String getLastEditBy() { - return lastEditBy; - } - public void setLastEditBy(String lastEditBy) { - this.lastEditBy = lastEditBy; - } - public int getCateOwnerId() { - return cateOwnerId; - } - public void setCateOwnerId(int cateOwnerId) { - this.cateOwnerId = cateOwnerId; - } - public int getNoteOwnerId() { - return noteOwnerId; - } - public void setNoteOwnerId(int noteOwnerId) { - this.noteOwnerId = noteOwnerId; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/StatTrack.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/StatTrack.java deleted file mode 100644 index 19aaf7e..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/StatTrack.java +++ /dev/null @@ -1,478 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import com.qiyou.mb.android.utils.log.QLog; - - -public class StatTrack { - public static String TAG ="com.qiyou.beans.StatTrack"; - public static String dTAG ="com.qiyou"; - public StatTrack() { - // TODO Auto-generated constructor stub - } - //max values begin... - private float dist =0.0f; - private float upDistE =0.0f; //累积上升 -// private float eDownDist =0.0f; //累积下降 - private float topSpeed =0.0f; - private long pause=0 ; - private int type; //0,1,2...(bike,walk,car) - private long sportTime =0; - private long offTime =0; //no gps time - private long totalTime=0 ; - private float maxR =0;//max radius - private float avSpeed=0; - private float tavSpeed=0; - private float burn=0; - private float upDist; - private float downDist; - private float maxEle; - private float minEle; - private long kmTime=0 ; - //average values.begin... - private float sumDist =0.0f; - private float sumBurn =0.0f; //累积消耗卡路里 - private float sumEup =0.0f; //累积上升 - private float sumEdown =0.0f; //累积下降 - private float sumTopSpeed =0.0f; - private long sumPause=0 ; - private long sumSportTime =0; - private long sumOff =0; //no gps time - private long sumTotalTime=0 ; - private float sumMaxR =0;//max radius - private float sumAvSpeed=0; - private float sumtAvSpeed=0; - private float sumUpDist; - private long sumKmTime; - - public float getSumTopSpeed() { - return sumTopSpeed; - } - - public float getSumMaxR() { - return sumMaxR; - } - - public float getSumAvSpeed() { - return sumAvSpeed; - } - - public float getSumtAvSpeed() { - return sumtAvSpeed; - } - - public long getSumKmTime() { - return sumKmTime; - } - - public float getSumMaxEle() { - return sumMaxEle; - } - - public float getSumMinEle() { - return sumMinEle; - } - private float sumDownDist; - private float sumMaxEle; - private float sumMinEle; - private long start=System.currentTimeMillis(); - private long end =0; - - private int cnt=0; - protected boolean isAVcnt=true; - public boolean getIsAVcnt() { - return isAVcnt; - } - - public void setIsAVcnt(boolean isAVcnt) { - this.isAVcnt = isAVcnt; - } - private long minKmTime; - - public float getAvdist() { - return cnt>0? sumDist/cnt:0; - } - - public float getAveUpDist() { - return cnt>0? sumEup/cnt:0; - - } - public long getAvKmTime() { - return cnt>0? sumKmTime/cnt:0; - - } - public float getAveDownDist() { - - return cnt>0? sumEdown/cnt:0; - } - public float getAvtopSpeed() { - - return cnt>0? sumTopSpeed/cnt:0; -// return topSpeed; - } - public long getAvpause() { - - return cnt>0? sumPause/cnt:0; - } - public long getAvsportTime() { - return cnt>0? sumSportTime/cnt:0; - - } - public long getAvoffTime() { - - return cnt>0? sumOff/cnt:0; - } - public long getAvtotalTime() { - return cnt>0? sumTotalTime/cnt:0; - - } - public float getAvmaxR() { - return cnt>0? sumMaxR/cnt:0; - } - public float getAvavSpeed() { - return cnt>0? sumAvSpeed/cnt:0; - } - public float getAvTavSpeed() { - return cnt>0? sumtAvSpeed/cnt:0; - } - public float getAvBurn() { - return cnt>0? sumBurn/cnt:0; - } - - public float getAvUpDist() { - return cnt>0? sumUpDist/cnt:0; - - } - public float getAvDownDist() { - - return cnt>0? sumDownDist/cnt:0; - } - public float getAvMaxEle() { - return cnt>0? sumMaxEle/cnt:0; - - } - public float getAvMinEle() { - - return cnt>0?Math.abs(sumMinEle)>cnt?sumMinEle/cnt:0:0; - } - - - - public float getUpDist() { - return upDist ; - - } - public float getDownDist() { - - return downDist; - } - public float getMaxEle() { - return maxEle; - - } - public float getMinEle() { - - return minEle; - } - - - public void setUpDist(float upDist) { - if(Float.isInfinite(upDist) ||Float.isNaN(upDist) ||upDist<=0)return; - sumUpDist+=upDist; - if(upDist >this.upDist) - this.upDist = upDist; - } - - - public void setDownDist(float downDist) { - if(Float.isInfinite(downDist) ||Float.isNaN(downDist) ||downDist<=0)return; - sumDownDist+=downDist; - if(downDist >this.downDist) - this.downDist = downDist; - } - - - public void setMaxEle(float maxEle) { - if(Float.isInfinite(maxEle) ||Float.isNaN(maxEle) ||maxEle<-1000 )return; - sumMaxEle+=maxEle; - if(maxEle >this.maxEle) - this.maxEle = maxEle; - } - - - public void setMinTimeKm(long minKmTime) { - if(minKmTime<=0)return; - sumKmTime+=minKmTime; - if(this.minKmTime==0 || this.minKmTime >minKmTime) - this.minKmTime = minKmTime; -// QLog.getLogger().d(dTAG, "sumKmTime is "+ sumKmTime +", minKmTime is " +this.minKmTime +", current KmTime is " + minKmTime); -// QLog.getLogger().d(dTAG, "current KmTime is " + minKmTime); - } - - - public void setMinEle(float minEle) { - if(Float.isInfinite(minEle) ||Float.isNaN(minEle) )return; - sumMinEle+=minEle; - if(minEle < this.minEle) - this.minEle = minEle; - } - - - public float getDist() { - return dist; - } - public void setDist(float dist) { - if(Float.isInfinite(dist) ||Float.isNaN(dist) ||dist<=0)return; - if(isAVcnt){ - cnt++; - } - sumDist+=dist; - if(dist >this.dist) - this.dist = dist; - } - /*public boolean isAVcnt() { - return isAVcnt; - } - public void setAVcnt(boolean isAVcnt) { - this.isAVcnt = isAVcnt; - }*/ - public float getUpDistE() { - return upDistE; - } - public void setUpDistE(float upDistE) { - if(Float.isInfinite(upDistE)||Float.isNaN(upDistE))return; - sumEup+=upDistE; - if(upDistE >this.upDistE) - this.upDistE = upDistE; - } -// public float geteDownDist() { -// return eDownDist; -// } -// public void seteDownDist(float eDownDist) { -// if(Float.isInfinite(eDownDist)||Float.isNaN(eDownDist))return; -// sumDownDist+=eDownDist; -// if(Math.abs(eDownDist) >this.eDownDist) -// this.eDownDist = Math.abs(eDownDist); -// } - public float getTopSpeed() { - return topSpeed; - } - public void setTopSpeed(float topSpeed) { - if(Float.isInfinite(topSpeed)||Float.isNaN(topSpeed) ||topSpeed<0)return; - sumTopSpeed+=topSpeed; - if(topSpeed >this.topSpeed) - this.topSpeed = topSpeed; - } - public long getPause() { - return pause; - } - public void setPause(long pause) { - if(Float.isInfinite(pause)|| Float.isNaN(pause)||pause<0 )return; - sumPause+=pause; - if(pause >this.pause) - this.pause = pause; - } - public int getType() { - return type; - } - public void setType(int type) { - - this.type = type; - } - public long getSportTime() { - return sportTime; - } - public void setSportTime(long sportTime) { - if(Float.isInfinite(sportTime)||Float.isNaN(sportTime)||sportTime<0)return; - sumSportTime+=sportTime; - if(sportTime >this.sportTime) - this.sportTime = sportTime; - } - public long getOffTime() { - return offTime; - } - public void setOffTime(long offTime) { - if(Float.isInfinite(offTime)||Float.isNaN(offTime)||offTime<0)return; - sumOff+=offTime; - if(offTime >this.offTime) - this.offTime = offTime; - } - public float getMaxR() { - return maxR; - } - public void setMaxR(float maxR) { - if(Float.isInfinite(maxR)||Float.isNaN(maxR) ||maxR<0)return; - sumMaxR+=maxR; - if(maxR >this.maxR) - this.maxR = maxR; - } - - public void setBurn(float burn) { - if(Float.isInfinite(burn)||Float.isNaN(burn) ||burn<0)return; - sumBurn+=burn; - if(burn >this.burn) - this.burn = burn; - } - - public float getBurn(){ - return burn; - } - - public float getAvSpeed() { - return avSpeed; - } - - public long getMinKmTime() { - return this.minKmTime; - } - - public float getTavSpeed() { - return tavSpeed; - } - - public void setAvSpeed(float avSpeed) { -// if(avSpeed == Float.NaN)return; - if(Float.isInfinite(avSpeed)||Float.isNaN(avSpeed)|| !(avSpeed>0) )return; -// Log.e("com.qiyou", "statTrack set avspeed:"+ avSpeed); - sumAvSpeed+=avSpeed; - if(avSpeed >this.avSpeed) - this.avSpeed = avSpeed; - } - - public void setTavSpeed(float tavSpeed) { -// if(avSpeed == Float.NaN)return; - if(Float.isInfinite(avSpeed)||Float.isNaN(avSpeed)|| !(avSpeed>0) )return; -// Log.e("com.qiyou", "statTrack set avspeed:"+ avSpeed); - sumtAvSpeed+=tavSpeed; - if(tavSpeed >this.tavSpeed) - this.tavSpeed = tavSpeed; - } - - - public long getTotalTime() { - return totalTime; - } - public void setTotalTime(long totalTime) { - if(Float.isInfinite(totalTime)||Float.isNaN(totalTime) ||totalTime<0)return; - sumTotalTime+=totalTime; - if(totalTime >this.totalTime) - this.totalTime = totalTime; - } - - /*public void mergeTrack(Track tr){ - - QLog.getLogger().d(dTAG, TAG+" MergeTrack: begin to merge track:" +tr.getTrackBean().getTrackId()); - - if(tr==null || tr.getTrackBean()==null) return; - - isAVcnt=false; - Track_bean tb =tr.getTrackBean(); -// isAVcnt = !mergedTracks.contains(tb.getTrackId()); - isAVcnt = mergedTracks.get(Integer.valueOf(tb.getTrackId()))==null; - Track_bean tb0= mergedTracks.get(Integer.valueOf(tb.getTrackId())); - isAVcnt = tb0==null; - - QLog.getLogger().d(dTAG, TAG+" MergeTrack: track alread exist?" + isAVcnt); - - QLog.getLogger().d(dTAG, TAG+" MergeTrack: Last merge distance:?" + tb0.getDistance()); - QLog.getLogger().d(dTAG, TAG+" MergeTrack: Current merge distance:?" + tb.getDistance()); - - QLog.getLogger().d(dTAG, TAG+" MergeTrack: Last merge totalTime:?" + (tb0.getSportTime()+tb0.getPauseTime())); - QLog.getLogger().d(dTAG, TAG+" MergeTrack: Current merge totalTime:?" + (tb.getSportTime()+tb.getPauseTime())); - -// if(tb.getDistance() -tb0.getDistance()<=0)return; - if( (tb.getSportTime()+tb.getPauseTime()) - (tb0.getSportTime()+tb0.getPauseTime()) <=0)return; - this.setAvSpeed(tb.getAvs() - tb0.getAvs()); - this.setDist(tb.getDistance()-tb.getDistance() ); - this.seteDownDist(tb.geteDownDist() -tb0.geteDownDist()); - this.seteUpDist(tb.geteUpDist() - tb0.geteUpDist()); - this.setMaxR(tb.getRdist() - tb0.getRdist()); - this.setOffTime(tb.getOffTime() - tb0.getOffTime()); - this.setPause(tb.getPauseTime() -tb0.getPauseTime()); - this.setSportTime(tb.getSportTime()-tb0.getSportTime()); - this.setTopSpeed(tb.getTopSpeed() -tb0.getTopSpeed()); - this.setTotalTime((tb.getSportTime()+tb.getPauseTime()) - (tb0.getSportTime()+tb0.getPauseTime())); - this.setCost(tb.getCost() -tb0.getCost()); - mergedTracks.put(tb.getTrackId(),tb); - isAVcnt=true; - QLog.getLogger().d(dTAG, TAG+" MergeTrack: DONE."); - } -// ArrayList mergedTracks =new ArrayList(); - HashMap mergedTracks =new HashMap(); - */ - - - - public int getCnt(){ - return cnt; - } - - public float getSumDist(){ - return this.sumDist; - } - - public long getSumTotalTime(){ - return this.sumTotalTime; - } - - public long getSumSportTime(){ - return this.sumSportTime; - } - - public float getSumEup(){ - return this.sumEup; - } - - public float getSumEdown(){ - return this.sumEdown; - } - - public float getSumBurn(){ - return this.sumBurn; - } - - public long getSumPause(){ - return this.sumPause; - } - - public long getSumOff(){ - return this.sumOff; - } - - public float getSumUpDist() { - return sumUpDist; - } - - public float getSumDownDist() { - return sumDownDist; - } - - public long getStart() { - return start; - } - - public void setStart(long start) { - if(startthis.end) - this.end = end; - } - - public long getKmTime() { - return kmTime; - } - - public void setKmTime(long kmTime) { - this.kmTime = kmTime; - } - - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Statics_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Statics_bean.java deleted file mode 100644 index 4c885d5..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Statics_bean.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; - - -public class Statics_bean { - public Statics_bean() { - // TODO Auto-generated constructor stub - } - public Statics_bean(Track_bean tb) { - // TODO Auto-generated constructor stub - if(tb==null)return; - - svrNo =tb.getSvrNumber(); - trackid =tb.getTrackId(); - name=tb.getName(); - dist =tb.getDistance(); - eUpDist =tb.geteUpDist(); //累积上升 - eDownDist =tb.geteDownDist(); //累积下降 - topSpeed =tb.getTopSpeed(); - userid=tb.getUserid(); - pause=tb.getPauseTime() ; - type=tb.getType().toInt(); //0,1,2...(bike,walk,car) - sportTime=tb.getSportTime(); - isCheckedIn=tb.getIsCheckedIn(); //0,1 ( false,true) - status =tb.getStatus(); //0,1,2,3,...(pending,recording,paused,finished,...) - offTime=tb.getOffTime(); //no gps time - maxR=tb.getMaxR();//max radius - avs =tb.getAvs();//max radius - tavs=tb.getTavs();//max radius - startTime=tb.getStartTime(); - endTime=tb.getEndTime(); - burn =tb.getBurn(); - lastdbTime=tb.getLastdbTime(); - totalTime=tb.getTotalTime(); - creator=tb.getCreator(); - src=tb.getSrc(); - upDist=tb.getUpDist(); - downDist=tb.getDownDist(); - maxEle=tb.getMaxEle(); - minEle=tb.getMinEle(); - kmTime =tb.getKmTime(); - } - - - private int trackid; - private String name; - private float dist =0.0f; - private float eUpDist =0.0f; //累积上升 - private float eDownDist =0.0f; //累积下降 - private float topSpeed =0.0f; - private int userid; - private long pause=0 ; - private int type; //0,1,2...(bike,walk,car) - private long sportTime; - private int isCheckedIn; //0,1 ( false,true) - private TrackStatus status =TrackStatus.PENING; //0,1,2,3,...(pending,recording,paused,finished,...) - private long offTime; //no gps time - private float maxR;//max radius - private float avs; - private float tavs; - private long startTime; - private long endTime; - private float burn; - private long lastdbTime; - private long totalTime; - private String creator; - private String src; - private int svrNo; - private float upDist; - private float downDist; - private float maxEle; - private float minEle; - private long kmTime; - - public int getTrackid() { - return trackid; - } - public void setTrackid(int trackid) { - this.trackid = trackid; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public float getDist() { - return dist; - } - public void setDist(float dist) { - this.dist = dist; - } - public float geteUpDist() { - return eUpDist; - } - public void seteUpDist(float eUpDist) { - this.eUpDist = eUpDist; - } - public float geteDownDist() { - return eDownDist; - } - public void seteDownDist(float eDownDist) { - this.eDownDist = eDownDist; - } - public float getTopSpeed() { - return topSpeed; - } - public void setTopSpeed(float topSpeed) { - this.topSpeed = topSpeed; - } - public int getUserid() { - return userid; - } - public void setUserid(int userid) { - this.userid = userid; - } - public long getPause() { - return pause; - } - public void setPause(long pause) { - this.pause = pause; - } - public int getType() { - return type; - } - public void setType(int type) { - this.type = type; - } - public long getSportTime() { - return sportTime; - } - public void setSportTime(long sportTime) { - this.sportTime = sportTime; - } - public int getIsCheckedIn() { - return isCheckedIn; - } - public void setIsCheckedIn(int isCheckedIn) { - this.isCheckedIn = isCheckedIn; - } - public TrackStatus getStatus() { - return status; - } - public void setStatus(TrackStatus status) { - this.status = status; - } - public long getOffTime() { - return offTime; - } - public void setOffTime(long offTime) { - this.offTime = offTime; - } - public float getMaxR() { - return maxR; - } - public void setMaxR(float maxR) { - this.maxR = maxR; - } - public float getAvs() { - return avs; - } - public void setAvs(float avs) { - this.avs = avs; - } - public float getTavs() { - return tavs; - } - public void setTavs(float tavs) { - this.tavs = tavs; - } - public long getStartTime() { - return startTime; - } - public void setStartTime(long startTime) { - this.startTime = startTime; - } - public long getEndTime() { - return endTime; - } - public void setEndTime(long endTime) { - this.endTime = endTime; - } - public float getBurn() { - return burn; - } - public void setBurn(float burn) { - this.burn = burn; - } - public long getLastdbTime() { - return lastdbTime; - } - public void setLastdbTime(long lastdbTime) { - this.lastdbTime = lastdbTime; - } - public long getTotalTime() { - return totalTime; - } - public void setTotalTime(long totalTime) { - this.totalTime = totalTime; - } - public String getCreator() { - return creator; - } - public void setCreator(String creator) { - this.creator = creator; - } - public String getSrc() { - return src; - } - public void setSrc(String src) { - this.src = src; - } - public int getSvrNo() { - return svrNo; - } - public void setSvrNo(int svrNo) { - this.svrNo = svrNo; - } - public float getUpDist() { - return upDist; - } - public void setUpDist(float upDist) { - this.upDist = upDist; - } - public float getDownDist() { - return downDist; - } - public void setDownDist(float downDist) { - this.downDist = downDist; - } - public float getMaxEle() { - return maxEle; - } - public void setMaxEle(float maxEle) { - this.maxEle = maxEle; - } - public float getMinEle() { - return minEle; - } - public void setMinEle(float minEle) { - this.minEle = minEle; - } - public long getKmTime() { - return kmTime; - } - public void setKmTime(long kmTime) { - this.kmTime = kmTime; - } - - - - - - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Track_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Track_bean.java deleted file mode 100644 index 4ad46ef..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Track_bean.java +++ /dev/null @@ -1,706 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import java.util.ArrayList; -import java.util.concurrent.CopyOnWriteArrayList; - -import android.text.TextUtils; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.log.QLog; - -public class Track_bean { - public Track_bean() { - // TODO Auto-generated constructor stub - - } - private long creatTime; - private String creator; - private String name=""; - private String cmt; - private String desc; - private float distance =0.0f; - private float eUpDist =0.0f; //累积上升 - private float eDownDist =0.0f; //累积下降 - private float topSpeed =0.0f; - private int userid; - private Waypoint startWp; - private Waypoint lastWp; - private long startTime; - private long endTime; - private int trackId; - private long pause=0 ; - private String src; - private int svrNumber; //编号,服务器端的记录编号 -// private int type; //0,1,2...(bike,walk,car) - private TrackType type; - private long sportTime; - private long lastdbTime; - private int isCheckedIn; //0,1 ( false,true) -// private CopyOnWriteArrayList trkseg; - private ArrayList trkseg; - private TrackStatus status =TrackStatus.PENING; //0,1,2,3,...(pending,recording,paused,finished,...) - private long offTime; //no gps time - private int gpsSpan =2000; -// private CopyOnWriteArrayList roadWps = new CopyOnWriteArrayList(); - private ArrayList roadWps = new ArrayList(); - private Waypoint maxDistWp; - private float maxR;//max radius - private float burn;//卡路里 -// private CopyOnWriteArrayList mdWps = new CopyOnWriteArrayList(); - private ArrayList mdWps = new ArrayList(); - private long totalTime=0; - private TrackAvStatus avStatus =TrackAvStatus.ACTIVE; - private String summary; - private String userName; - private int userScore; - private String staticMapUrl; -// private ArrayList thumbUrls; - /** - * Returns the name of this track. - * @return A String representing the name of this track. - */ - public String getName() { - - if(TextUtils.isEmpty(name) && trackId>0) - name =/*"No."+*/ getType().toCHString() + trackId; - return name; - } - - /** - * Setter for track name property. This maps to <name> tag value. - * @param name A String representing the name of this track. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the comment of this track. - * @return A String representing the comment of this track. - */ - public String getComment() { - return cmt; - } - - /** - * Setter for track comment property. This maps to <comment> tag value. - * @param comment A String representing the comment of this track. - */ - public void setComment(String comment) { - cmt = comment; - } - - /** - * Returns the description of this track. - * @return A String representing the description of this track. - */ - public String getDescription() { - return desc; - } - - /** - * Setter for track description property. This maps to <description> tag value. - * @param description A String representing the description of this track. - */ - public void setDescription(String description) { - desc = description; - } - - /** - * Returns the src of this track. - * @return A String representing the src of this track. - */ - public String getSrc() { - return src; - } - - /** - * Setter for src type property. This maps to <src> tag value. - * @param src A String representing the src of this track. - */ - public void setSrc(String src) { - this.src = src; - } - -/* *//** - * Returns the number of this track. - * @return A String representing the number of this track. - *//* - public int getNumber() { - return svrNumber; - } - - *//** - * Setter for track number property. This maps to <number> tag value. - * @param number An int representing the number of this track. - *//* - public void setNumber(int number) { - this.svrNumber = number; - } - */ - /** - * Returns the type of this track. - * @return A String representing the type of this track. - */ - public TrackType getType() { - if(type==null) type=TrackType.BIKE; - return type; - } - - /** - * Setter for track type property. This maps to <type> tag value. - * @param type A String representing the type of this track. - */ - public void setType(TrackType type) { - this.type = type; - } - - /** - * Getter for the list of waypoints of a track. - * @return an ArrayList of {@link Waypoint} representing the points of the track. - */ - -/* public CopyOnWriteArrayList getTrkseg() { - if(trkseg == null) trkseg= new CopyOnWriteArrayList(); - return trkseg; - }*/ - public ArrayList getTrkseg() { - if(trkseg == null) trkseg= new ArrayList(); - return trkseg; - } - - /** - * Setter for the list of waypoints of a track. - * @param trackPoints an ArrayList of {@link Waypoint} representing the points of the track. - */ - /*public void setTrksegs(CopyOnWriteArrayList trkseg) { - this.trkseg = trkseg; - }*/ - - public void setTrksegs( ArrayList trkseg) { - this.trkseg = trkseg; - } - -/* public String toGsonString() - { - String strwb =""; - if(null != number) - { - Gson gson = new Gson(); - try{ - strwb = gson.toJson(this); - }catch(Exception e) - { - Log.e( e.getStackTrace().toString()); - } - - } - return strwb; - }*/ - - /** - * @return the dist - */ - public float getDistance() { -// dist=getAvs()>0?dist:0; -// return distance; -// return getSportTime() >0?dist:0; -// distance =this.getLastWp().getWb().getSumDist(); - return distance; - } - - /** - * @param dist the dist to set - */ - public void setDistance(float dist) { -// this.distance = dist>distance?dist:distance; - this.distance = dist; - } - - /** - * @return the pause - */ - public long getPauseTime() { - -// pause= dist>0?pause: endTime - getStartTime() - offTime; - -// pause =endTime-startTime-getSportTime()-offTime; -// pause =getTotalTime()-getSportTime(); -// pause =getTotalTime()-getSportTime()-offTime; - return pause >0?pause:0; - } - public long getDeltaPause(){ - return getPauseTime()-pause; - } - - /** - * @param pause the pause to set - */ - public void setPauseTime(long pause) { - if(pause<=0)return; - - long old= this.pause; - this.pause = pause; - - if(this.getAvs()>this.topSpeed){ - this.pause= old; - } - - - } - - /** - * @return the userid - */ - public int getUserid() { - return userid; - } - - /** - * @param userid the userid to set - */ - public void setUserid(int userid) { - this.userid = userid; - } - - /** - * @return the startTime - */ - public long getStartTime() { -// if(startTime ==0){ -// if(startWp !=null) -// startTime =startWp.getWb().getTime(); -// else -// startTime = System.currentTimeMillis(); -// -// -// } - startTime=startTime>0?startTime:(startWp!=null?startWp.getWb().getTime():0); -// if(type==TrackType.GPX){ -// startTime=startWp!=null?startWp.getWb().getTime():1; -// } - return startTime; - } - - /** - * @param startTime the startTime to set - */ - public void setStartTime(long stTime) { - startTime =startTime==0?stTime:startTime; -// startTime>stTime?stTime:startTime;//取小 - } - - /** - * @return the endTime - */ - public long getEndTime() { - - return endTime>=this.getLastWp().getWb().getTime()?endTime:this.getLastWp().getWb().getTime(); - } - - /** - * @return - */ - public long getTotalTime() { - totalTime =getEndTime() -getStartTime(); - return totalTime; -// return endTime -getStartTime();// +this.getOffTime(); -/*// totalTime =totalTime>this.sportTime+this.pause+this.offTime?totalTime: this.sportTime+this.pause+this.offTime; - totalTime =sportTime+pause+offTime; - totalTime=totalTime>(endTime -getStartTime()) ||type==TrackType.GPX ?endTime -getStartTime():totalTime; -// if(type==TrackType.GPX){ -// totalTime=endTime -getStartTime(); -// } - return totalTime;//this.sportTime+this.pause+this.offTime; -*/ } - - - -// public void setTotalTime(long totalTime) { -// this.totalTime = totalTime; -// } - - /** - * @param endTime the endTime to set - */ - public void setEndTime(long endTime) { - this.endTime = endTime>this.endTime?endTime:this.endTime; - } - - /** - * @return the isCheckedIn - */ - public int getIsCheckedIn() { - return isCheckedIn; - } - - /** - * @param isCheckedIn the isCheckedIn to set - */ - public void setIsCheckedIn(int isCheckedIn) { - this.isCheckedIn = isCheckedIn; - } - - /** - * @return the trackid - */ - public int getTrackId() { - return trackId; - } - - /** - * @param trackid the trackid to set - */ - public void setTrackId(int trackId) { - this.trackId = trackId; - } - - public Waypoint getLastWp() { - if(lastWp ==null )lastWp = new Waypoint(); - return lastWp; - } - - public void setLastWp(Waypoint lastWp) { - this.lastWp = lastWp; - } - - public Waypoint getStartWp() { - return startWp; - } - - public void setStartWp(Waypoint startWp) { - if(startWp==null)return; - - this.startWp = startWp; -// long stTime=System.currentTimeMillis(); -// stTime = stTime>=startWp.getWb().getTime()?stTime:startWp.getWb().getTime(); -// setStartTime(stTime); -// setStartTime(System.currentTimeMillis()); - setStartTime(startWp.getWb().getTime()); -// startTime =startTime==0?System.currentTimeMillis():startTime; - - } - - public long getSportTime() { -// sportTime = getLastWp().getWb().getTime() - getStartTime() - pause -offTime; - -// sportTime =sportTime==0?getLastWp().getWb().getSportTime():sportTime; - -// return getLastWp().getWb().getSportTime()>0?getLastWp().getWb().getSportTime():sportTime;//getLastWp().getWb().getSportTime(); -// return getLastWp().getWb().getSportTime()>60*1000?getLastWp().getWb().getSportTime():0; - sportTime =sportTime0? sportTime:getLastWp().getWb().getSportTime();//getLastWp().getWb().getSportTime(); - sportTime=sportTime >getTotalTime()?getTotalTime():sportTime; - return sportTime; - } - - public long getLastdbTime() { - return lastdbTime; - } - - public void setLastdbTime(long lastdbTime) { - this.lastdbTime = lastdbTime; - } - - public float geteUpDist() { - return eUpDist; - } - - public float getEsumUp() { - return eUpDist ;//+ eDownDist; - } - - - public void seteUpDist(float eUpDist) { - this.eUpDist = eUpDist; - } - - public float geteDownDist() { - - return eDownDist ; - - } - - public void seteDownDist(float eDownDist) { - this.eDownDist = eDownDist; - } - - public float getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(float topSpeed) { - if(topSpeed>this.topSpeed) - this.topSpeed = topSpeed; - } - - public TrackStatus getStatus() { - return status; - } - - public void setStatus(TrackStatus status) { - this.status = status; - } - - public long getOffTime() { - return offTime; - } - - public void setOffTime(long offTime) { - this.offTime = offTime; - } - - public int getGpsSpan() { - return gpsSpan; - } - - public void setGpsSpan(int gpsSpan) { - this.gpsSpan = gpsSpan; - } - - /* - * km/h - */ - public float getAvs() { - if(getCreator()!=null && getCreator().startsWith("爱骑驴路书"))return getTavs(); -// float avs =TrackType.COPY==this.getType()?0:getSportTime()>1000? 3600f*dist/getSportTime():0; - float avs = getSportTime()>10000? 3600f*distance/getSportTime():0; -// QLog.getLogger().dLog("com.qiyoutop.qnaviSvc","com.qiyou.qnaviSvc", " getSportTime: "+getSportTime() ); -// QLog.getLogger().dLog("com.qiyoutop.qnaviSvc","com.qiyou.qnaviSvc", " dist: "+dist ); - if(type==TrackType.GPX &&avs>topSpeed){ - topSpeed=avs; - return avs; - } - if(avs>topSpeed) avs =3600f*distance/getTotalTime();// topSpeed; -// QLog.getLogger().dLog("com.qiyoutop.qnaviSvc","com.qiyou.qnaviSvc", " app.getCurrentTrack().getTrackBean().getAvs(): "+avs ); -// if(avs>topSpeed) return topSpeed; - return avs; - } - - public float getCAvs() { - - float avs = getSportTime()>10000? 3600f*distance/getSportTime():0; -// if(avs>topSpeed) return 0; -// QLog.getLogger().dLog("com.qiyoutop.qnaviSvc","com.qiyou.qnaviSvc", " app.getCurrentTrack().getTrackBean().getAvs(): "+avs ); - return avs; - - } - - public float getTavs() { -// float tavs =getSportTime()>1000? 3600f*dist/(endTime-getStartTime()):0; - float tavs =getTotalTime()>10000 || getType()==TrackType.GPX? 3600f*distance/getTotalTime():0; - - if(type==TrackType.GPX &&tavs>topSpeed){ -// topSpeed=tavs; - return tavs; - } - -// if(type!=TrackType.GPX &&(tavs>topSpeed ||(type!=TrackType.GPX && tavs> getAvs())||tavs<0)) tavs=0; - - return tavs; -// return getAvs(); - } - - - /*public CopyOnWriteArrayList getRoadWps() { - if(roadWps!=null && roadWps.size()>1000) - roadWps=Utils.getCleanWbs(roadWps); - return roadWps; - } - - public void setRoadWps(CopyOnWriteArrayList roadWps) { - try{ - this.roadWps = roadWps; - }catch(Exception e){ - Utils.logStackTrace(e, "trackbean"); - - } - }*/ - - public ArrayList getRoadWps() { - if(roadWps!=null && roadWps.size()>1000) - roadWps=Utils.getCleanWbs(roadWps); - return roadWps; - } - - public void setRoadWps( ArrayList roadWps) { - try{ - this.roadWps = roadWps; - }catch(Exception e){ - Utils.logStackTrace(e, "trackbean"); - - } - } - public Waypoint getMaxDistWp() { - if(maxDistWp==null) maxDistWp =new Waypoint(); - return maxDistWp; - } - - public void setMaxDistWp(Waypoint maxDistWp) { - this.maxDistWp = maxDistWp; - } - - public float getMaxR() { - return maxR; - } - - public void setMaxR(float maxRdist) { - maxR = maxRdist; - } - - /*public CopyOnWriteArrayList getMdWps() { - return mdWps; - } - - public void setMdWps(CopyOnWriteArrayList mdWps) { - this.mdWps = mdWps; - } */ - - public ArrayList getMdWps() { - return mdWps; - } - - public void setMdWps( ArrayList mdWps) { - this.mdWps = mdWps; - } - - public void setSportTime(long sportTime) { - this.sportTime = sportTime; - } - - public float getBurn() { - return burn; - } - - public void setBurn(float burn) { - this.burn = burn; - } - - public long getNonSportTime(){ - return getTotalTime() - getSportTime(); - } - - public String getCreator() { - return creator; - } - - public void setCreator(String creator) { - if(!TextUtils.isEmpty(creator) && !creator.equalsIgnoreCase("null")) - this.creator = creator; - } - - public TrackAvStatus getAvStatus() { - return avStatus; - } - - public void setAvStatus(TrackAvStatus avStatus) { - this.avStatus = avStatus; - } - - public long getCreatTime() { - return creatTime; - } - - public void setCreatTime(long creatTime) { - this.creatTime = creatTime; - } - - public String getSummary() { - return summary; - } - - public void setSummary(String summary) { - this.summary = summary; - } - - public int getSvrNumber() { - return svrNumber; - } - - public void setSvrNumber(int svrNumber) { - this.svrNumber = svrNumber; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public int getUserScore() { - - return userScore; - } - - public void setUserScore(int userScore) { - this.userScore = userScore; - } - public String getStaticMapUrl() { - return staticMapUrl; - } - - public void setStaticMapUrl(String staticMapUrl) { - this.staticMapUrl = staticMapUrl; - } - private String[] thumbUrls; - public String[] getThumbUrls() { -// if(thumbUrls==null)thumbUrls=new String[1]; - return thumbUrls; - } - - public void setThumbUrls(String[] thumbUrls) { - this.thumbUrls = thumbUrls; - } -/* - public ArrayList getThumbUrls() { - if(thumbUrls==null)thumbUrls=new ArrayList(); - return thumbUrls; - } - - public void setThumbUrls(ArrayList thumbUrls) { - this.thumbUrls = thumbUrls; - } -*/ - - public float getUpDist() { - return this.getLastWp().getWb().getUpDist(); - } - - public float getDownDist() { -// return downDist<-1*distance*0.07f? downDist - -1*distance*0.07f:0f; - return this.getLastWp().getWb().getDownDist(); - } - - - public float getMaxEle() { - return this.getLastWp().getWb().getMaxEle(); - } - - public float getMinEle() { - float minEle=this.getLastWp().getWb().getMinEle(); -// minEle=minEle>getMaxEle()?getMaxEle():minEle; -// return this.getLastWp().getWb().getMinEle(); - float max=getMaxEle(); - minEle=(max>QiYouConstant.MAX_ELE*-1 &&minEle>max)?max:minEle; - return minEle; -// return minEle>getMaxEle()?getMaxEle():minEle; - } - - public long getKmTime(){ - -// long v=(long)(this.getTotalTime()/this.getDistance()/1000); -// return Utils.getTimeCnt(v); -// return (long)(this.getTotalTime()/this.getDistance()*1000); - if(getDistance()<100) - return 0; - return (long)(this.getSportTime()/this.getDistance()*1000); - } -} - diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/TypeStatistics.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/TypeStatistics.java deleted file mode 100644 index 25998e8..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/TypeStatistics.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - - -import java.util.concurrent.ConcurrentHashMap; - - - -public class TypeStatistics { - - public TypeStatistics() { - // TODO Auto-generated constructor stub - } - public TypeStatistics(long mStart,long mEnd,int mType) { - start =mStart; - end =mEnd; - type=mType; - } -private ConcurrentHashMap sbs; -//private ArrayList asbs; -private long start=0; -private long end ; -private int type ; -private StatTrack statTrack; -private ConcurrentHashMap trackIds; - - public ConcurrentHashMap getTrackIds() { - if(trackIds==null)trackIds=new ConcurrentHashMap(); - return trackIds; -} -public void setTrackIds(ConcurrentHashMap trackIds) { - this.trackIds = trackIds; -} -public ConcurrentHashMap getSbs() { - if (sbs==null) sbs =new ConcurrentHashMap(); - return sbs; - } - public void setSbs(ConcurrentHashMap sbs) { - this.sbs = sbs; - } - public long getStart() { - return start; - } - public void setStart(long start) { - this.start = this.start==0?start - :startthis.end ?end:this.end ; - } - public int getType() { - return type; - } - public void setType(int type) { - this.type = type; - } - public StatTrack getStatTrack() { - if(statTrack==null)statTrack =new StatTrack(); - return statTrack; - } - public void setStatTrack(StatTrack statTrack) { - this.statTrack = statTrack; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/User_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/User_bean.java deleted file mode 100644 index 14c6d4c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/User_bean.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import android.text.TextUtils; - -import com.qiyou.mb.android.utils.Utils; - - -public class User_bean { - - private int id; -// private int svrNumber; - private String qqOpenId; - public String getQqOpenId() { - return qqOpenId; - } - public void setQqOpenId(String qqOpenId) { - this.qqOpenId = qqOpenId; - } - public String getQqToken() { - return qqToken; - } - public void setQqToken(String qqToken) { - this.qqToken = qqToken; - } - public long getQqExprires() { - return qqExprires; - } - public void setQqExprires(long qqExprires) { - this.qqExprires = qqExprires; - } - public String getQqName() { - return qqName; - } - public void setQqName(String qqName) { - this.qqName = qqName; - } - public String getQqAbulmUrl() { - return qqAbulmUrl; - } - public void setQqAbulmUrl(String qqAbulmUrl) { - this.qqAbulmUrl = qqAbulmUrl; - } - private String qqToken; - private long qqExprires; - private String qqName; - private String qqAbulmUrl; - private String userName; - private String account; - private String password; - private int userLevel; - private int userType; - private int score; - private int genda; - - private GEOaddress address; - private String mail; - private long birthday; -// private ArrayList groups; -// private Media album; - private String album; - private String userDesc; - private String sign; - private int paiming; - private String title; - private GEO_bean geo; - private String geoJsonString; - private float lat; - private float lon; - private long regtime; - private float distance; - private int phoneId; - private String token; - private long exprires; - private int loginType;//0 mail/passwd; 1 qq - private float calorie; - private boolean power; - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public String getAccount() { - return account; - } - public void setAccount(String account) { - this.account = account; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public int getUserLevel() { - return userLevel; - } - public void setUserLevel(int userlevel) { - this.userLevel = userlevel; - } - public int getUserType() { - return userType; - } - public void setUserType(int userType) { - this.userType = userType; - } - public int getScore() { - return score; - } - public void setScore(int score) { - this.score = score; - } - public int getGenda() { - return genda; - } - public void setGenda(int genda) { - this.genda = genda; - } - public GEOaddress getAddress() { - return address; - } - public void setAddress(GEOaddress address) { - this.address = address; - } - public String getMail() { - return mail; - } - public void setMail(String mail) { - this.mail = mail; - } - public long getBirthday() { - return birthday; - } - public void setBirthday(long birthday) { - this.birthday = birthday; - } -// public Media getAlbum() { -// return album; -// } -// public void setAlbum(Media album) { -// this.album = album; -// } - public String getUserDesc() { - return userDesc; - } - public void setUserDesc(String userDesc) { - this.userDesc = userDesc; - } - public String getSign() { - return sign; - } - public void setSign(String sign) { - this.sign = sign; - } - public int getPaiming() { - return paiming; - } - public void setPaiming(int paiming) { - this.paiming = paiming; - } - - public float getLat() { - return lat; - } - public void setLat(float lat) { - this.lat = lat; - } - public float getLon() { - return lon; - } - public void setLon(float lon) { - this.lon = lon; - } - public GEO_bean getGeo() { - if(geo==null ){ - if(!TextUtils.isEmpty(geoJsonString )){ - geo =(GEO_bean) Utils.getGsonObject(geoJsonString, GEO_bean.class); - } - if(geo==null){ - geo= new GEO_bean(); - } - } - return geo; - } - public void setGeo(GEO_bean geo) { - this.geo=geo; - } - - - public String getGeoJsonString() { - return geoJsonString; - } - public void setGeoJsonString(String geoJsonString) { - this.geoJsonString = geoJsonString; - } - - public float getDistance() { - return distance; - } - public void setDistance(float distance) { - this.distance = distance; - } - public long getRegtime() { - return regtime; - } - public void setRegtime(long regtime) { - this.regtime = regtime; - } - public int getPhoneId() { - return phoneId; - } - public void setPhoneId(int phoneId) { - this.phoneId = phoneId; - } - public String getToken() { - return token; - } - public void setToken(String token) { - this.token = token; - } - public long getExprires() { - return exprires; - } - public void setExprires(long exprires) { - this.exprires = exprires; - } - public int getLoginType() { - return loginType; - } - public void setLoginType(int loginType) { - this.loginType = loginType; - } - public float getCalorie() { - return calorie; - } - public void setCalorie(float calorie) { - this.calorie = calorie; - } - public boolean isPower() { - return power; - } - public void setPower(boolean power) { - this.power = power; - } - public String getAlbum() { - return album; - } - public void setAlbum(String album) { - this.album = album; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Vender_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Vender_bean.java deleted file mode 100644 index 0b877cc..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Vender_bean.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -/** - * Created by wangmi on 17/1/7. - */ - -public class Vender_bean extends Group_bean { - - - - - - - - - - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Waypoint.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Waypoint.java deleted file mode 100644 index d02381b..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Waypoint.java +++ /dev/null @@ -1,134 +0,0 @@ - - -package com.qiyou.mb.android.beans.basic; - -import android.util.Log; -import com.google.gson.Gson; -import com.qiyou.mb.android.utils.Utils; - - -/* -48.64.61397 -{lat:31.266748,lon:120.725372,ele:48.6,time:331234123234,speed:4.1265} -*/ - -public class Waypoint { - public static String TAG ="com.qiyou.beans.Waypoint"; - public static String dTAG ="com.qiyou"; - private Waypoint_bean wb ; - private transient String jsonWp; - public Waypoint_bean getWb() { - if(null==wb) wb = new Waypoint_bean(); - return wb; - } - public void setWb(Waypoint_bean wb){ - this.wb=wb; - } - public Waypoint() - { - wb = new Waypoint_bean(); - } - /* - * construct by JSON string - */ - public Waypoint(String jsonWp) - { -// long bfdbTime = System.currentTimeMillis(); - Gson gson = new Gson(); -// try{ - - wb = gson.fromJson(jsonWp, Waypoint_bean.class); - this.jsonWp = jsonWp; - - - } - - - public String toJsonWp() - { -// long bfdbTime = System.currentTimeMillis(); - - - // if(null != wb.getLatitude()) - { - - Gson gson = new Gson(); - try{ - jsonWp = gson.toJson(wb); - }catch(Exception e) - { - Log.e(TAG,jsonWp); - Utils.logStackTrace(e, dTAG); - } - - } - return jsonWp; - } - - /** - * Returns a String representation of this waypoint. - */ - @Override - public String toString() { - return toJsonWp(); - } - - - public String toGpxString() - { - return null; - } - - /** - * Compares two {@link Waypoint} objects based on latitude and longitude only - */ - @Override - public boolean equals(Object obj) { - - //TODO: check more, it will filter out some same wp for calculation. - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Waypoint other = (Waypoint) obj; - if (wb.getLatitude() == 0f) { - if (other.getWb().getLatitude() != 0f) - return false; - } else if (wb.getLatitude()!=(other.getWb().getLatitude())) - return false; - if (wb.getLongitude() == 0f) { - if (other.getWb().getLongitude() != 0f) - return false; - } else if (wb.getLongitude()!=(other.getWb().getLongitude())) - return false; - return false; - } - - /** - * Compares two {@link Waypoint} objects based on time stamp only to see if the new one is a young brother. - */ - public boolean isNewer(Object obj) { - - //TODO: check more, it will filter out some same wp for calculation. - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Waypoint other = (Waypoint) obj; - return other.getWb().getTime() > wb.getTime(); - } - - public String getJsonWp() { - return jsonWp; - } - public void setJsonWp(String jsonWp) { - this.jsonWp = jsonWp; - } - - -} - diff --git a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Waypoint_bean.java b/qy/src/main/java/com/qiyou/mb/android/beans/basic/Waypoint_bean.java deleted file mode 100644 index 7c5fc0f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/beans/basic/Waypoint_bean.java +++ /dev/null @@ -1,354 +0,0 @@ -package com.qiyou.mb.android.beans.basic; - -import java.util.ArrayList; - -import android.text.TextUtils; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.enums.wpFlag; - - -public class Waypoint_bean { - public Waypoint_bean() { - - } - private float latitude; - private float longitude; - private float elevation; - private float eled; - private long time; - private float speed ; - private float distance; - private long pauseTime ; - private float bearing; - private float accuracy; - private long offtime; - private ArrayList medias; - private int kmflag; //1,2,3.。。 - private float sumDist; - private long sportTime; -// private float roadBear=0f; - private float sumBear; - private float avb; - private float bearDist; - private String roadBook; -// private int turnFlag =-2; - private wpFlag turnFlag =wpFlag.NORMAL; - private GEOaddress geo; - private String comment; - private String name; - private String desc; - private float upDist; - private float downDist; - private float maxEle=-1*QiYouConstant.MAX_ELE; - private float minEle=QiYouConstant.MAX_ELE; - - public GEOaddress getGeo() { - return geo; - } - - public void setGeo(GEOaddress Geo) { - if(geo==null)geo = Geo; - } - - /** - * Returns the latitude of this waypoint. - * @return a float value representing the latitude of this waypoint. - */ - public float getLatitude() { - return latitude; - } - - /** - * Setter for waypoint latitude property. This maps to "latitude" attribute value. - * @param latitude a Doube value representing the latitude of this waypoint. - */ - public void setLatitude(float latitude) { - this.latitude = latitude; - } - - /** - * Returns the longitude of this waypoint. - * @return a float value representing the longitude of this waypoint. - */ - public float getLongitude() { - return longitude; - } - - /** - * Setter for waypoint longitude property. This maps to "long" attribute value. - * @param longitude a Doube value representing the longitude of this waypoint. - */ - public void setLongitude(float longitude) { - this.longitude = longitude; - } - - /** - * Returns the elevation of this waypoint. - * @return A float representing the elevation of this waypoint. - */ - public float getElevation() { - return elevation; - } - - /** - * Setter for waypoint elevation property. This maps to <elevation> tag value. - * @param elevation a float value representing the elevation of this waypoint. - */ - public void setElevation(float elevation) { - this.elevation = elevation; - } - - /** - * Returns the time of this waypoint. - * @return a Date representing the name of this waypoint. - */ - public long getTime() { - return time; - } - - /** - * Setter for waypoint time property. This maps to <time> tag value. - * @param time a Date representing the time of this waypoint. - */ - public void setTime(long time) { - this.time = time; - } - /** - * @return the speed km/h - */ - public float getSpeed() { - return speed; - } - - /** - * @param speed the speed to set,km/h - */ - public void setSpeed(float speed) { - this.speed = speed; - } - - /** - * @return the distance - */ - public float getDistance() { - return distance; - } - - /** - * @param distance the distance to set - */ - public void setDistance(float distance) { - this.distance = distance; - } - - /** - * @return the pauseTime - */ - public long getPauseTime() { - return pauseTime; - } - - /** - * @param pauseTime the pauseTime to set - */ - public void setPauseTime(long pauseTime) { - this.pauseTime = pauseTime; - } - - /* - * @return the media - */ - public ArrayList getMedias() { - if(null == medias) medias = new ArrayList(); - - return medias; - } - - /** - * @param media the media to set - */ - public void setMedias(ArrayList medias) { - this.medias = medias; - } - - public float getEled() { - - /*float factor=distance*QiYouConstant.ELED_FACTOR; - return (float) (eled>0? - eled> factor?eled-factor :0 - : eled<-1*factor? eled - -1*factor:0); */ - return eled; - } - - public void setEled(float eled) { - this.eled = eled; - } - - public float getAccuracy() { - return accuracy; - } - - public void setAccuracy(float accuracy) { - this.accuracy = accuracy; - } - - public float getBearing() { - return bearing; - } - - public void setBearing(float bearing) { - this.bearing = bearing; - } - - public long getOfftime() { - return offtime; - } - - public void setOfftime(long offtime) { - this.offtime = offtime; - } - - public int getKmflag() { - return kmflag; - } - - public void setKmflag(int kmflag) { - this.kmflag = kmflag; - } - - public float getSumDist() { - return sumDist; - } - - public void setSumDist(float sumDist) { - this.sumDist = sumDist; - } - - public long getSportTime() { - return sportTime; - } - - public void setSportTime(long sportTime) { - this.sportTime = sportTime; - } - -/* public float getRoadBear() { - return roadBear; - } - - public void setRoadBear(float roadBear) { - this.roadBear = roadBear; - } -*/ - public float getSumBear() { - return sumBear; - } - - public void setSumBear(float sumBear) { - this.sumBear = sumBear; - } - - public float getAvb() { - return avb; - } - - public void setAvb(float avb) { - this.avb = avb; - } - - public float getBearDist() { - return bearDist; - } - - public void setBearDist(float bearDist) { - this.bearDist = bearDist; - } - - public String getRoadBook() { - if(TextUtils.isEmpty(roadBook)) return ""; - return roadBook.replace("\"", ""); - } - - public void setRoadBook(String roadBook) { - this.roadBook = roadBook; - } - - /*public String getTargetBear() { - return targetBear; - } - - public void setTargetBear(String targetBear) { - this.targetBear = targetBear; - } -*/ - - - public wpFlag getTurnFlag() { - return turnFlag; - } - - public void setTurnFlag(wpFlag turnFlag) { - this.turnFlag = turnFlag; - } - - public String getComment() { - if(TextUtils.isEmpty(comment)) return ""; - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public String getName() { - if(TextUtils.isEmpty(name)) return ""; - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDesc() { - if(TextUtils.isEmpty(desc)) return ""; - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public float getUpDist() { - return upDist; - } - - public void setUpDist(float upDist) { - this.upDist = upDist; - } - - public float getDownDist() { -// return downDist<-1*distance*0.07f? downDist - -1*distance*0.07f:0f; - return downDist; - } - - public void setDownDist(float downDist) { - this.downDist = downDist; - } - - public float getMaxEle() { - return maxEle; - } - - public void setMaxEle(float maxEle) { - this.maxEle = maxEle; - } - - public float getMinEle() { - return minEle; - } - - public void setMinEle(float minEle) { - this.minEle = minEle; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/content_providers/TrackProvider.java b/qy/src/main/java/com/qiyou/mb/android/content_providers/TrackProvider.java deleted file mode 100644 index 2de8524..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/content_providers/TrackProvider.java +++ /dev/null @@ -1,1093 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.content_providers; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -import android.content.ContentProvider; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.UriMatcher; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteException; -import android.database.sqlite.SQLiteOpenHelper; -import android.database.sqlite.SQLiteQueryBuilder; -import android.database.sqlite.SQLiteDatabase.CursorFactory; -import android.net.Uri; -import android.text.TextUtils; -import android.util.Log; - -/** - * @author mwang - * - */ -public class TrackProvider extends ContentProvider { - - private static final String TAG = "com.qiyou.TrackProvider"; - public static final String dTAG ="com.qiyou"; - - - /** The underlying database */ - private static SQLiteDatabase tracksDB; - - public static SQLiteDatabase getTracksDB() { - return tracksDB; - } - - private static final String DATABASE_NAME = "tracks.db"; - - private static final int DATABASE_VERSION =20; - private static final String TRACKS_TABLE = "TRACKS"; - private static final String GEOS_TABLE = "GEOS"; - private static final String TRACK_GEOS_TABLE = "TRACK_GEOS"; - private static final String USERS_TABLE = "USERS"; - private static final String GROUPS_TABLE = "GROUPS"; -// private static final String CATEGORY_TABLE = "track_1"; - private static final String CATE_TRACK_TABLE = "CATEGORY"; - private static final String ACTIVITY_TABLE = "ACTIVITY"; - private static final String MESSAGE_TABLE = "MESSAGE"; - private static final String GROUP_USER_TABLE ="GROUP_USER"; - - - - public static final String KEY_ID = "_id"; - public static final String KEY_SVR_NUMBER = "SVRNUMBER"; - public static final String KEY_LAST_UPDATE_TIME = "LAST_UPDATETIME"; - - // Tracks Column Names - public static final String KEY_TRACK_NAME = "NAME"; - public static final String KEY_TRACK_COMMENT = "COMMENT"; - public static final String KEY_TRACK_DESC = "DESC"; - public static final String KEY_TRACK_START_WP= "STARTWP"; - public static final String KEY_TRACK_LAST_WP = "LASTWP"; - public static final String KEY_TRACK_START_TIME = "START_TIME"; - public static final String KEY_TRACK_END_TIME = "END_TIME"; - public static final String KEY_TRACK_CONTENT = "TRACK_CONTENT"; - public static final String KEY_TRACK_ROAD_BEARS = "ROADBEARS"; - public static final String KEY_TRACK_USER_ID = "USERID"; - public static final String KEY_TRACK_DISTANCE = "DISTANCE"; - public static final String KEY_TRACK_EUP_DIST = "EUP"; - public static final String KEY_TRACK_EDOWN_DIST = "EDOWN"; - public static final String KEY_TRACK_TOPSPEED = "TOPSPEED"; - public static final String KEY_TRACK_SPORT_TIME = "SPORT_TIME"; - public static final String KEY_TRACK_PAUSE_TIME = "PAUSE_TIME"; - public static final String KEY_TRACK_IS_SETS = "CHECKEDIN"; - - public static final String KEY_TRACK_STATUS = "STATUS"; - public static final String KEY_TRACK_TYPE = "TYPE"; - public static final String KEY_TRACK_OFFTIME = "OFF_TIME"; //no gps time - public static final String KEY_TRACK_GPSSPAN = "GPS_SPAN"; //gpsSpan -// public static final String KEY_TRACK_MAXRD_WP = "maxRdWp"; -// public static final String KEY_TRACK_MAXRD = "maxRd"; - public static final String KEY_TRACK_MAXRD_WP = "MAX_RDWP"; - public static final String KEY_TRACK_MAXRD = "MAR_RD"; - public static final String KEY_TRACK_GEO_STATUS = "GEO_STATUS"; - public static final String KEY_TRACK_MDWPS = "MD_WPS"; - public static final String KEY_TRACK_CAL_BURNING = "CALORIES"; - public static final String KEY_TRACK_CREATOR = "CREATOR"; - public static final String KEY_TRACK_SRC = "SRC"; - public static final String KEY_TRACK_AVSTATUS = "AV_STATUS"; - public static final String KEY_TRACK_CREATE_TIME = "CREATE_TIME"; - public static final String KEY_TRACK_5 = "TRACK_5"; - public static final String KEY_TRACK_6 = "TRACK_6"; - public static final String KEY_TRACK_7 = "TRACK_7"; - public static final String KEY_TRACK_8 = "TRACK_8"; - - // geos Column Names - public static final String KEY_GEO_PARENTID = "PARENTID"; - public static final String KEY_GEO_TYPE = "TYPE"; - public static final String KEY_GEO_NAME = "NAME"; - public static final String KEY_GEO_COMMENT = "COMMENT"; - public static final String KEY_GEO_SVRID = "SVRID"; - - public static final String KEY_GEO_LAT = "LAT"; - public static final String KEY_GEO_LON = "LON"; - public static final String KEY_GEO_3 = "GEO_3"; - public static final String KEY_GEO_4 = "GEO_4"; - public static final String KEY_GEO_5 = "GEO_5"; - public static final String KEY_GEO_6 = "GEO_6"; - - // track_geos Column Names - public static final String KEY_TRACK_GEO_GID = "GEO_ID"; - public static final String KEY_TRACK_GEO_TID = "TRACK_ID"; - public static final String KEY_TRACK_GEO_TYPE = "TYPE"; - public static final String KEY_TRACK_GEO_TIME = "TIMESTAMP"; - public static final String KEY_TRACK_GEO_2 = "track_geo_2"; - public static final String KEY_TRACK_GEO_3 = "track_geo_3"; - public static final String KEY_TRACK_GEO_4 = "track_geo_4"; - public static final String KEY_TRACK_GEO_5 = "track_geo_5"; - public static final String KEY_TRACK_GEO_6 = "track_geo_6"; - - - // user Column Names -// public static final String KEY_USER_ID = "USERID"; - public static final String KEY_USER_NAME = "USERNAME"; - public static final String KEY_USER_PASSWD = "PASSWD"; - public static final String KEY_USER_LEVEL = "LEVEL"; - public static final String KEY_USER_TYPE = "TYPE"; - public static final String KEY_USER_SCORE = "SCORE"; - public static final String KEY_USER_HONORS = "HONORS"; - public static final String KEY_USER_GENDA = "GENDA"; - public static final String KEY_USER_LOCATION = "LOCATION"; - public static final String KEY_USER_MAIL = "MAIL"; - public static final String KEY_USER_BIRTHDAY = "BIRTHDAY"; - public static final String KEY_USER_ALBUM = "ALBUM"; - public static final String KEY_USER_DESC = "DESC"; - public static final String KEY_USER_GROUPS = "GROUPS"; - public static final String KEY_USER_SIGN = "SIGN"; - public static final String KEY_USER_STATUS = "STATUS"; - public static final String KEY_USER_1 = "KEY_USER_1"; - public static final String KEY_USER_2 = "KEY_USER_2"; - public static final String KEY_USER_3 = "KEY_USER_3"; - public static final String KEY_USER_4 = "KEY_USER_4"; - public static final String KEY_USER_5 = "KEY_USER_5"; - public static final String KEY_USER_6 = "KEY_USER_6"; - public static final String KEY_USER_7 = "KEY_USER_7"; - - - // group Column Names -// public static final String KEY_USER_GROUP_ID = "GROUPID"; - public static final String KEY_GROUP_NAME = "NAME"; - public static final String KEY_GROUP_TYPE = "TYPE"; - public static final String KEY_GROUP_LEVEL = "LEVEL"; - public static final String KEY_GROUP_SCORE = "SCORE"; - public static final String KEY_GROUP_LOCATION = "LOCATION"; - public static final String KEY_GROUP_HONORS = "HONORS"; - public static final String KEY_GROUP_DESC = "DESC"; - public static final String KEY_GROUP_OWNER = "OWNER"; - public static final String KEY_GROUP_ADMINS = "ADMINS"; - public static final String KEY_GROUP_STATUS = "STATUS"; - public static final String KEY_GROUP_7 = "KEY_7"; - public static final String KEY_GROUP_8 = "KEY_8"; - public static final String KEY_GROUP_9 = "KEY_9"; - public static final String KEY_GROUP_10 = "KEY_10"; - public static final String KEY_GROUP_11 = "KEY_11"; - public static final String KEY_GROUP_12 = "KEY_12"; - public static final String KEY_GROUP_13 = "KEY_13"; - public static final String KEY_GROUP_14 = "KEY_14"; - public static final String KEY_GROUP_15 = "KEY_15"; - - -// public static final String KEY_TRACK_1_COL1 = "T1COL1"; -// public static final String KEY_CATE_DESC = "T1COL2"; -// public static final String KEY_CATE_STATUS = "T1COL3"; -// public static final String KEY_TRACK_1_COL4 = "T1COL4"; -// public static final String KEY_TRACK_1_COL5 = "T1COL5"; -// public static final String KEY_TRACK_1_COL6 = "T1COL6"; -// public static final String KEY_TRACK_1_COL7 = "T1COL7"; -// public static final String KEY_TRACK_1_COL8 = "T1COL8"; - - // track_category Column Names - public static final String KEY_CATE_NAME = "T2COL1"; - public static final String KEY_TRACK_ID = "T2COL2"; - public static final String KEY_CATE_TRACK_STATUS = "T2COL3"; - public static final String KEY_TRACK_2_COL4 = "T2COL4"; - public static final String KEY_TRACK_2_COL5 = "T2COL5"; - public static final String KEY_TRACK_2_COL6 = "T2COL6"; - public static final String KEY_TRACK_2_COL7 = "T2COL7"; - public static final String KEY_TRACK_2_COL8 = "T2COL8"; - - // activity Column Names - public static final String KEY_ACTIVITY_NAME = "NAME"; - public static final String KEY_ACTIVITY_OWNER = "OWNER"; - public static final String KEY_ACTIVITY_DESC = "DESC"; - public static final String KEY_ACTIVITY_LOCATION = "LOCATION"; - public static final String KEY_ACTIVITY_TYPE = "TYPE"; - public static final String KEY_ACTIVITY_ST_DATE = "ST_DATE"; - public static final String KEY_ACTIVITY_END_DATE = "END_DATE"; - public static final String KEY_ACTIVITY_SPONSORS = "SPONSORS"; - public static final String KEY_ACTIVITY_STATUS = "STATUS"; -// public static final String KEY_ACTIVITY_SVRNUMBER = "SVRNUMBER"; - public static final String KEY_ACTIVITY_COL1 = "KEY_1"; - public static final String KEY_ACTIVITY_COL2 = "KEY_2"; - public static final String KEY_ACTIVITY_COL3 = "KEY_3"; - public static final String KEY_ACTIVITY_COL4 = "KEY_4"; - public static final String KEY_ACTIVITY_COL5 = "KEY_5"; - public static final String KEY_ACTIVITY_COL6= "KEY_6"; - public static final String KEY_ACTIVITY_COL7 = "KEY_7"; - public static final String KEY_ACTIVITY_COL8 = "KEY_8"; - - // GROUP_USER Column Names - public static final String KEY_GROUP_USER_USERID = "USERID"; - public static final String KEY_GROUP_USER_GROUPID = "GROUPID"; - public static final String KEY_GROUP_USER_IS_OWNER = "ISOWNER"; - public static final String KEY_GROUP_USER_IS_ADMIN = "ISADMIN"; - public static final String KEY_GROUP_USER_STATUS = "STATUS"; - public static final String KEY_GROUP_USER_KEY_1 = "KEY_1"; - public static final String KEY_GROUP_USER_KEY_2 = "KEY_2"; - public static final String KEY_GROUP_USER_KEY_3 = "KEY_3"; - public static final String KEY_GROUP_USER_KEY_4 = "KEY_4"; - public static final String KEY_GROUP_USER_KEY_5 = "KEY_5"; - public static final String KEY_GROUP_USER_KEY_6 = "KEY_6"; - - // TODO Replace this URI with something unique to your own application. - public static final Uri TRACKS_URI = Uri.parse("content://com.qiyou.mb.android.tracks/tracks"); - public static final Uri GEOS_URI = Uri.parse("content://com.qiyou.mb.android.tracks/geos"); - public static final Uri TRACK_GEOS_URI = Uri.parse("content://com.qiyou.mb.android.tracks/track_geos"); -// public static final Uri CATEGORY_URI = Uri.parse("content://com.qiyou.mb.android.tracks/"+CATEGORY_TABLE); - public static final Uri CATE_TRACK_URI = Uri.parse("content://com.qiyou.mb.android.tracks/"+CATE_TRACK_TABLE); - public static final Uri USER_URI = Uri.parse("content://com.qiyou.mb.android.tracks/"+USERS_TABLE); - public static final Uri GROUP_URI = Uri.parse("content://com.qiyou.mb.android.tracks/"+GROUPS_TABLE); - public static final Uri ACTIVITIES_URI = Uri.parse("content://com.qiyou.mb.android.tracks/"+ACTIVITY_TABLE); - //Create the constants used to differentiate between the different URI requests. - private static final int TRACKS = 1; - private static final int TRACKS_ID = 2; - private static final int TRACKS_LIST = 3; //show formated db content - - private static final int GEOS = 4; - private static final int GEOS_ID = 5; - private static final int GEOS_LIST = 6; //show formated db content - - private static final int TRACK_GEOS = 7; - private static final int TRACK_GEOS_ID = 8; - private static final int TRACK_GEOS_LIST = 9; //show formated db content - - -// private static final int CATEGORIES = 10; -// private static final int CATEGORY_ID = 11; -// private static final int CATEGORY_LIST = 12; //show formated db content - - private static final int CATEGORY_TRACKS = 13; - private static final int CATEGORY_TRACK_ID = 14; - private static final int CATEGORY_TRACK_LIST = 15; //show formated db content - - private static final int USER = 16; - private static final int USER_ID = 17; - private static final int USER_LIST = 18; //show formated db content - - private static final int GROUP = 19; - private static final int GROUP_ID = 20; - private static final int GROUP_LIST = 21; //show formated db content - - private static final int ACTIVITY = 22; - private static final int ACTIVITY_ID = 23; - private static final int ACTIVITY_LIST = 24; //show formated db content - - //Allocate the UriMatcher object, where a URI ending in 'places' will - //correspond to a request for all places, and 'places' with a trailing '/[Unique ID]' will represent a single place details row. - private static final UriMatcher uriMatcher; - static { - uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); - uriMatcher.addURI("com.qiyou.mb.android.tracks", "tracks", TRACKS); - uriMatcher.addURI("com.qiyou.mb.android.tracks", "tracks/*", TRACKS_ID); - uriMatcher.addURI("com.qiyou.mb.android.tracks", "tracks/list/", TRACKS_LIST); - - uriMatcher.addURI("com.qiyou.mb.android.tracks", "geos", GEOS); - uriMatcher.addURI("com.qiyou.mb.android.tracks", "geos/*", GEOS_ID); - uriMatcher.addURI("com.qiyou.mb.android.tracks", "geos/list/", GEOS_LIST); - - uriMatcher.addURI("com.qiyou.mb.android.tracks", "track_geos", TRACK_GEOS); - uriMatcher.addURI("com.qiyou.mb.android.tracks", "track_geos/*", TRACK_GEOS_ID); - uriMatcher.addURI("com.qiyou.mb.android.tracks", "track_geos/list/", TRACK_GEOS_LIST); - - uriMatcher.addURI("com.qiyou.mb.android.tracks", CATE_TRACK_TABLE, CATEGORY_TRACKS); - uriMatcher.addURI("com.qiyou.mb.android.tracks", CATE_TRACK_TABLE+"/*", CATEGORY_TRACK_ID); - uriMatcher.addURI("com.qiyou.mb.android.tracks", CATE_TRACK_TABLE+"/list/", CATEGORY_TRACK_LIST); - - uriMatcher.addURI("com.qiyou.mb.android.tracks", USERS_TABLE , USER); - uriMatcher.addURI("com.qiyou.mb.android.tracks", USERS_TABLE+"/*", USER_ID); - uriMatcher.addURI("com.qiyou.mb.android.tracks", USERS_TABLE+"/list/", USER_LIST); - - uriMatcher.addURI("com.qiyou.mb.android.tracks", GROUPS_TABLE , GROUP); - uriMatcher.addURI("com.qiyou.mb.android.tracks", GROUPS_TABLE+"/*", GROUP_ID); - uriMatcher.addURI("com.qiyou.mb.android.tracks", GROUPS_TABLE+"/list/", GROUP_LIST); - - uriMatcher.addURI("com.qiyou.mb.android.tracks", ACTIVITY_TABLE , ACTIVITY); - uriMatcher.addURI("com.qiyou.mb.android.tracks", ACTIVITY_TABLE+"/*", ACTIVITY_ID); - uriMatcher.addURI("com.qiyou.mb.android.tracks", ACTIVITY_TABLE+"/list/", ACTIVITY_ID); - - } - - @Override - public boolean onCreate() { - Context context = getContext(); - Utils.initSdPath(context); - PlacesDatabaseHelper dbHelper = new PlacesDatabaseHelper(context, DATABASE_NAME, - null, DATABASE_VERSION); - try { - - if(QiYouConstant.DEVELOPER_MODE){ - - File path = new File(QiYouConstant.SD_PATH);// 创建目录 - File f = new File(QiYouConstant.SD_PATH + DATABASE_NAME);// 创建文件 - if (!path.exists()) {// 目录存在返回false - path.mkdirs();// 创建一个目录 - } - if (!f.exists()) {// 文件存在返回false - try { - f.createNewFile();//创建文件 //TODO: 机身内存创建文件出错. - tracksDB =SQLiteDatabase.openOrCreateDatabase(f, null); - dbHelper.onCreate(tracksDB); - // QLog.getLogger().d(dTAG,TAG+" "+ "Database Created as " +f); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - Utils.logStackTrace(e, dTAG); - } - } else{ - tracksDB =SQLiteDatabase.openOrCreateDatabase(f, null); - // QLog.getLogger().d(dTAG,TAG+" "+ "Database Openned " +f); - } - - - - }else{ - tracksDB = dbHelper.getWritableDatabase(); - } - - - } catch (SQLiteException e) { - tracksDB = null; - Log.e(dTAG,TAG+" "+ "Database Opening exception,"+e.getStackTrace()); - Utils.logStackTrace(e, dTAG); - } - - return (tracksDB == null) ? false : true; - } - - @Override - public String getType(Uri uri) { - switch (uriMatcher.match(uri)) { - case TRACKS: return "vnd.android.cursor.dir/tracks"; - case TRACKS_ID: return "vnd.android.cursor.item/track"; - case TRACKS_LIST: return "vnd.android.cursor.dir/tracks/list"; - - case GEOS: return "vnd.android.cursor.dir/geos"; - case GEOS_ID: return "vnd.android.cursor.item/geo"; - case GEOS_LIST: return "vnd.android.cursor.dir/geos/list"; - - case TRACK_GEOS: return "vnd.android.cursor.dir/track_geos"; - case TRACK_GEOS_ID: return "vnd.android.cursor.item/track_geo"; - case TRACK_GEOS_LIST: return "vnd.android.cursor.dir/track_geos/list"; - - case CATEGORY_TRACKS: return "vnd.android.cursor.dir/categories"; - case CATEGORY_TRACK_ID: return "vnd.android.cursor.item/category"; - case CATEGORY_TRACK_LIST: return "vnd.android.cursor.dir/categories/list"; - -// case CATEGORY_TRACKS: return "vnd.android.cursor.dir/cate_tracks"; -// case CATEGORY_TRACK_ID: return "vnd.android.cursor.item/cate_track"; -// case CATEGORY_TRACK_LIST: return "vnd.android.cursor.dir/cate_tracks/list"; - - case USER: return "vnd.android.cursor.dir/users"; - case USER_ID: return "vnd.android.cursor.item/user"; - case USER_LIST: return "vnd.android.cursor.dir/users/list"; - - case GROUP: return "vnd.android.cursor.dir/groups"; - case GROUP_ID: return "vnd.android.cursor.item/group"; - case GROUP_LIST: return "vnd.android.cursor.dir/groups/list"; - - case ACTIVITY: return "vnd.android.cursor.dir/activities"; - case ACTIVITY_ID: return "vnd.android.cursor.item/activity"; - case ACTIVITY_LIST: return "vnd.android.cursor.dir/activities/list"; - - default: throw new IllegalArgumentException("Unsupported URI: " + uri); - } - } - /** - * - */ - public TrackProvider() { - // TODO Auto-generated constructor stub - } - - /* (non-Javadoc) - * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[]) - */ - @Override - public int delete(Uri uri, String where, String[] whereArgs) { - int count; - String segment; - switch (uriMatcher.match(uri)) { - case TRACKS:{ - count = tracksDB.delete(TRACKS_TABLE, where, whereArgs); - break; - } - - case TRACKS_ID:{ - segment = uri.getPathSegments().get(1); - count = tracksDB.delete(TRACKS_TABLE, KEY_ID + "=" - + segment - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""), whereArgs); - break; - } - - case GEOS:{ - count = tracksDB.delete(GEOS_TABLE, where, whereArgs); - break; - } - case GEOS_ID:{ - segment = uri.getPathSegments().get(1); - count = tracksDB.delete(GEOS_TABLE, KEY_ID + "=" - + segment - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""), whereArgs); - break; - } - - - case TRACK_GEOS:{ - count = tracksDB.delete(TRACK_GEOS_TABLE, where, whereArgs); - break; - } - case TRACK_GEOS_ID:{ - segment = uri.getPathSegments().get(1); - count = tracksDB.delete(TRACK_GEOS_TABLE, KEY_ID + "=" - + segment - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""), whereArgs); - break; - } - - case CATEGORY_TRACKS:{ - count = tracksDB.delete(CATE_TRACK_TABLE, where, whereArgs); - break; - } - - case CATEGORY_TRACK_ID:{ - segment = uri.getPathSegments().get(1); - count = tracksDB.delete(CATE_TRACK_TABLE, KEY_ID + "=" - + segment - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""), whereArgs); - break; - } - - default: throw new IllegalArgumentException("Unsupported URI: " + uri); - } - - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - - /* (non-Javadoc) - * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues) - */ - @Override - public Uri insert(Uri _uri, ContentValues _initialValues) { - // Insert the new row, will return the row number if successful. - try{ - long rowID ; - switch (uriMatcher.match(_uri)) { - case TRACKS:{ - rowID = tracksDB.insert(TRACKS_TABLE, "nullhack", _initialValues); - if (rowID > 0) { - Uri uri = ContentUris.withAppendedId(TRACKS_URI, rowID); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - } - break; - } - case GEOS:{ - rowID = tracksDB.insert(GEOS_TABLE, "nullhack", _initialValues); - if (rowID > 0) { - Uri uri = ContentUris.withAppendedId(GEOS_URI, rowID); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - } - break; - } - case TRACK_GEOS:{ - rowID = tracksDB.insert(TRACK_GEOS_TABLE, "nullhack", _initialValues); - if (rowID > 0) { - Uri uri = ContentUris.withAppendedId(TRACK_GEOS_URI, rowID); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - } - break; - } - - /* case CATEGORIES:{ - rowID = tracksDB.insert(CATEGORY_TABLE, "nullhack", _initialValues); - if (rowID > 0) { - Uri uri = ContentUris.withAppendedId(CATEGORY_URI, rowID); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - } - break; - }*/ - case CATEGORY_TRACKS:{ - rowID = tracksDB.insert(CATE_TRACK_TABLE, "nullhack", _initialValues); - if (rowID > 0) { - Uri uri = ContentUris.withAppendedId(CATE_TRACK_URI, rowID); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - } - break; - } - - } - - - /*long rowID = tracksDB.insert(TRACKS_TABLE, "nullhack", _initialValues); - - // Return a URI to the newly inserted row on success. - if (rowID > 0) { - Uri uri = ContentUris.withAppendedId(TRACKS_URI, rowID); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - }*/ - }catch(Exception e) - { - Log.e(dTAG,TAG+" Failed to insert a new record."); - Utils.logStackTrace(e, dTAG); - } - return _uri; -// throw new SQLException("Failed to insert row into " + _uri); - } - - - - /* (non-Javadoc) - * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) - */ - @Override - public Cursor query(Uri uri, String[] projection, String selection, - String[] selectionArgs, String sort) { - - - SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); - - switch (uriMatcher.match( uri)) { - case TRACKS: { - qb.setTables(TRACKS_TABLE); - break; - } - case TRACKS_ID: { - qb.setTables(TRACKS_TABLE); - qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); -// QLog.getLogger().d(dTAG,TAG+" "+ "query, qb.appendWhere: "+ KEY_ID + "=" + uri.getPathSegments().get(1)); - break; - } - - - case GEOS:{ - qb.setTables(GEOS_TABLE); - break; - } - case GEOS_ID: { - qb.setTables(GEOS_TABLE); - qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); -// QLog.getLogger().d(dTAG,TAG+" "+ "query, qb.appendWhere: "+ KEY_ID + "=" + uri.getPathSegments().get(1)); - break; - } - - - case TRACK_GEOS:{ - qb.setTables(TRACK_GEOS_TABLE); - break; - } - case TRACK_GEOS_ID: { - qb.setTables(TRACK_GEOS_TABLE); - qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); -// QLog.getLogger().d(dTAG,TAG+" "+ "query, qb.appendWhere: "+ KEY_ID + "=" + uri.getPathSegments().get(1)); - break; - } - - - - /* case CATEGORIES:{ - qb.setTables(CATEGORY_TABLE); - break; - } - case CATEGORY_ID: { - qb.setTables(CATEGORY_TABLE); - qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); -// QLog.getLogger().d(dTAG,TAG+" "+ "query, qb.appendWhere: "+ KEY_ID + "=" + uri.getPathSegments().get(1)); - break; - } */ - - case CATEGORY_TRACKS:{ - qb.setTables(CATE_TRACK_TABLE); - // QLog.getLogger().d(dTAG,TAG+" "+ "query, CATE_TRACK_TABLE is " + CATE_TRACK_TABLE); - break; - } - case CATEGORY_TRACK_ID: { - qb.setTables(CATE_TRACK_TABLE); - qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); - // QLog.getLogger().d(dTAG,TAG+" "+ "query, qb.appendWhere: "+ KEY_ID + "=" + uri.getPathSegments().get(1)); - break; - } - default : break; - } - - - - - - - // If no sort order is specified sort by date / time - String orderBy; - if (TextUtils.isEmpty(sort)) { - orderBy = TrackProvider.KEY_LAST_UPDATE_TIME + " DESC"; - } else { - orderBy = sort; - } -// QLog.getLogger().d(dTAG,TAG+" query, tables =" +qb.getTables()); - // Apply the query to the underlying database. - Cursor c = null; - try { - c = qb.query(tracksDB, - projection, - selection, selectionArgs, - null, null, orderBy); - if(tracksDB ==null) - Log.e(dTAG,TAG+" "+ "com.qiyou.mb faild to open tracks db."); - // Register the contexts ContentResolver to be notified if - // the cursor result set changes. - c.setNotificationUri(getContext().getContentResolver(), uri); - } catch (Exception e) { - // TODO Auto-generated catch block - - Utils.logStackTrace(e, dTAG); - } - - - // Return a cursor to the query result. - return c; - } - - /* (non-Javadoc) - * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[]) - */ - @Override - public int update(Uri uri, ContentValues values, String where, String[] newWps) { - int count =0; - String[] whereArgs=null; -// QLog.getLogger().d(dTAG,TAG+" "+ "uri is " + uri ); - - switch (uriMatcher.match(uri)) { - case TRACKS: count = tracksDB.update(TRACKS_TABLE, values, where, whereArgs); - - break; - /* case CATEGORIES: count = tracksDB.update(CATEGORY_TABLE, values, where, whereArgs); - break;*/ - case CATEGORY_TRACKS: count = tracksDB.update(CATE_TRACK_TABLE, values, where, whereArgs); - - break; - case TRACKS_ID: String segment = uri.getPathSegments().get(1); -// QLog.getLogger().d(dTAG,TAG+" "+ "Update db by id: " +KEY_ID + "=" + segment ); - tracksDB.beginTransaction(); - try { - count = tracksDB.update(TRACKS_TABLE, values, KEY_ID - + "=" + segment - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""), whereArgs); - if(newWps!=null && newWps.length==3){ - //TODO: check to use sqlite statement for better performance. - - int cnt =1; - String mSql = "update "+ TRACKS_TABLE +" set "; - - if(!TextUtils.isEmpty(newWps[0])){ -// QLog.getLogger().d(dTAG,TAG+" "+ "Update track wps is:" + newWps[0] ); - mSql += KEY_TRACK_CONTENT + " = (" + KEY_TRACK_CONTENT + " ||?)" ; - - cnt++; - - } - if(!TextUtils.isEmpty(newWps[1])){ -// QLog.getLogger().d(dTAG,TAG+" "+ "Update rd wps is:" + newWps[1] ); - if(cnt>1) mSql += ","; - mSql += KEY_TRACK_ROAD_BEARS + " = (" + KEY_TRACK_ROAD_BEARS + " ||?)" ; - cnt++; - - } - - if(!TextUtils.isEmpty(newWps[2])){ -// QLog.getLogger().d(dTAG,TAG+" "+ "Update md wps is:" + newWps[2] ); - if(cnt>1)mSql += ","; - mSql += KEY_TRACK_MDWPS + " = (" +"ifnull(" + TrackProvider.KEY_TRACK_MDWPS +","+ "',')" + " ||?)"; -// mSql += "ifnull(" + TrackProvider.KEY_TRACK_MDWPS +",\",\")" + " = (" + KEY_TRACK_MDWPS + " ||?)"; - cnt++; - } - - - if(cnt>1){ - - mSql += " where " - + KEY_ID - + "=?" - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""); - - Object[] wps = new Object[cnt]; - int i=0; - if(!TextUtils.isEmpty(newWps[0])){ - wps[i] =newWps[0]; - i++; - } - if(!TextUtils.isEmpty(newWps[1])){ - wps[i] =newWps[1]; - i++; - } - if(!TextUtils.isEmpty(newWps[2])){ - wps[i] =newWps[2]; - i++; - } - wps[i]=segment; -// QLog.getLogger().d(dTAG,TAG+" Update mSql is:" + mSql ); - tracksDB.execSQL(mSql,wps); - - } - -// Object[] wps ={newWps[0],newWps[1],segment}; - - - -// QLog.getLogger().d(dTAG,TAG+" Update trackcontent for wps, mSql is:" + mSql ); -// QLog.getLogger().d(dTAG,TAG+" " + newWps[0].toString() ); -// QLog.getLogger().d(dTAG,TAG+" newWps[1] " + newWps[1].toString() ); -// QLog.getLogger().d(dTAG,TAG+" updated track id of " + segment ); - - - - - } - tracksDB.setTransactionSuccessful(); - }catch(Exception er) { - Utils.logStackTrace(er, dTAG); - } finally { - tracksDB.endTransaction(); - } - break; - - default: throw new IllegalArgumentException("Unknown URI " + uri); - } - - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - - - - /* - public int updateTrackWps(Uri uri, ContentValues values,String newWps, String where, String[] whereArgs) { - int count; - switch (uriMatcher.match(uri)) { - case TRACKS: count = tracksDB.update(TRACKS_TABLE, values, where, whereArgs); - break; - - case TRACKS_ID: String segment = uri.getPathSegments().get(1); - count = tracksDB.update(TRACKS_TABLE, values, KEY_ID - + "=" + segment - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""), whereArgs); - String mSql = "update tracks set "+ KEY_TRACK_CONTENT - + " = "+ KEY_TRACK_CONTENT + newWps - + " where " - + KEY_ID - + "=" + segment - + (!TextUtils.isEmpty(where) ? " AND (" - + where + ')' : ""); - - tracksDB.execSQL(mSql); - break; - - default: throw new IllegalArgumentException("Unknown URI " + uri); - } - - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - */ - - // Helper class for opening, creating, and managing database version control - private static class PlacesDatabaseHelper extends SQLiteOpenHelper { - - - private static final String CREATE_TRACK_TABLE = "create table " + TRACKS_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_TRACK_NAME + " TEXT, " - + KEY_TRACK_USER_ID + " INTEGER, " - + KEY_TRACK_COMMENT + " TEXT, " - + KEY_TRACK_DESC + " TEXT, " - + KEY_TRACK_START_WP + " TEXT, " - + KEY_TRACK_LAST_WP + " TEXT, " - + KEY_TRACK_START_TIME + " LONG, " - + KEY_TRACK_END_TIME + " LONG, " - + KEY_TRACK_DISTANCE + " LONG, " - + KEY_TRACK_EUP_DIST + " LONG, " - + KEY_TRACK_EDOWN_DIST + " LONG, " - + KEY_TRACK_TOPSPEED + " LONG, " - + KEY_TRACK_SPORT_TIME + " LONG, " - + KEY_TRACK_PAUSE_TIME + " LONG, " - + KEY_TRACK_CONTENT + " TEXT, " - + KEY_TRACK_IS_SETS + " INTEGER, " - + KEY_SVR_NUMBER + " INTEGER, " - + KEY_TRACK_STATUS + " INTEGER, " - + KEY_TRACK_TYPE + " INTEGER, " - + KEY_TRACK_OFFTIME + " LONG, " - + KEY_TRACK_GPSSPAN + " LONG, " - + KEY_TRACK_ROAD_BEARS + " TEXT, " - + KEY_TRACK_MAXRD_WP + " TEXT, " - + KEY_TRACK_MAXRD + " TEXT, " - + KEY_TRACK_GEO_STATUS + " INTEGER, " - + KEY_TRACK_MDWPS + " TEXT, " - + KEY_TRACK_CAL_BURNING + " LONG, " - + KEY_TRACK_CREATOR + " TEXT, " - + KEY_TRACK_SRC + " TEXT, " - + KEY_TRACK_AVSTATUS + " TEXT, " - + KEY_TRACK_CREATE_TIME + " LONG, " - + KEY_TRACK_5 + " TEXT, " - + KEY_TRACK_6 + " TEXT, " - + KEY_TRACK_7 + " TEXT, " - + KEY_TRACK_8 + " TEXT, " - - + KEY_LAST_UPDATE_TIME + " LONG" - - +"); "; - - - private static final String CREATE_GEO_TABLE = "create table " + GEOS_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_GEO_PARENTID + " INTEGER, " - + KEY_GEO_NAME + " TEXT, " - + KEY_GEO_TYPE + " INTEGER, " - + KEY_GEO_COMMENT + " TEXT, " - + KEY_SVR_NUMBER + " INTEGER, " - + KEY_GEO_LAT + " TEXT, " - + KEY_GEO_LON + " TEXT, " - + KEY_GEO_3 + " TEXT, " - + KEY_GEO_4 + " TEXT, " - + KEY_GEO_5 + " TEXT, " - + KEY_GEO_6 + " TEXT, " - - + KEY_LAST_UPDATE_TIME + " LONG); "; - - private static final String CREATE_TRACK_GEO_TABLE = "create table " + TRACK_GEOS_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_TRACK_GEO_GID + " INTEGER, " - + KEY_TRACK_GEO_TID + " INTEGER, " - + KEY_TRACK_GEO_TYPE + " INTEGER, " - + KEY_SVR_NUMBER + " INTEGER, " - + KEY_TRACK_GEO_TIME + " TEXT, " - + KEY_TRACK_GEO_2 + " TEXT, " - + KEY_TRACK_GEO_3 + " TEXT, " - + KEY_TRACK_GEO_4 + " TEXT, " - + KEY_TRACK_GEO_5 + " TEXT, " - + KEY_TRACK_GEO_6 + " TEXT, " - + KEY_LAST_UPDATE_TIME + " LONG); "; - - private static final String CREATE_USER_TABLE = "create table " + USERS_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_SVR_NUMBER + " INTEGER, " - + KEY_USER_PASSWD + " INTEGER, " - + KEY_USER_NAME + " TEXT, " - + KEY_USER_TYPE + " INTEGER, " - + KEY_USER_LEVEL + " INTEGER, " - + KEY_USER_SCORE + " INTEGER, " - + KEY_USER_GENDA + " INTEGER, " - + KEY_USER_LOCATION + " TEXT, " - + KEY_USER_MAIL + " TEXT, " - + KEY_USER_BIRTHDAY+ " TEXT, " - + KEY_USER_ALBUM + " TEXT, " - + KEY_USER_DESC + " TEXT, " - + KEY_USER_GROUPS+ " TEXT, " - + KEY_USER_STATUS+ " TEXT, " - + KEY_USER_SIGN + " TEXT, " - + KEY_USER_HONORS + " TEXT, " - + KEY_USER_1 + " TEXT, " - + KEY_USER_2+ " TEXT, " - + KEY_USER_3 + " TEXT, " - + KEY_USER_4 + " TEXT, " - + KEY_USER_5+ " TEXT, " - + KEY_USER_6 + " TEXT, " - + KEY_USER_7 + " TEXT, " - - + KEY_LAST_UPDATE_TIME + " LONG); "; - - - private static final String CREATE_GROUPS_TABLE = "create table " + GROUPS_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_SVR_NUMBER + " INTEGER, " - + KEY_GROUP_NAME + " TEXT, " - + KEY_GROUP_TYPE + " INTEGER, " - + KEY_GROUP_LEVEL + " INTEGER, " - + KEY_GROUP_SCORE + " TEXT, " - + KEY_GROUP_LOCATION+ " TEXT, " - + KEY_GROUP_HONORS + " TEXT, " - + KEY_GROUP_DESC + " TEXT, " - + KEY_GROUP_OWNER+ " TEXT, " - + KEY_GROUP_ADMINS + " TEXT, " - + KEY_GROUP_STATUS+ " TEXT, " - + KEY_GROUP_7 + " TEXT, " - + KEY_GROUP_8+ " TEXT, " - + KEY_GROUP_9 + " TEXT, " - + KEY_GROUP_10 + " TEXT, " - + KEY_GROUP_11+ " TEXT, " - + KEY_GROUP_12 + " TEXT, " - - + KEY_LAST_UPDATE_TIME + " LONG); "; - - - private static final String CREATE_GROUP_USER = "create table " + GROUP_USER_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_GROUP_USER_USERID + " INTEGER, " - + KEY_GROUP_USER_GROUPID + " INTEGER, " - + KEY_GROUP_USER_IS_OWNER + " INTEGER, " - + KEY_GROUP_USER_IS_ADMIN + " INTEGER, " - + KEY_GROUP_USER_STATUS + " INTEGER, " - + KEY_GROUP_USER_KEY_1 + " TEXT, " - + KEY_GROUP_USER_KEY_2+ " TEXT, " - + KEY_GROUP_USER_KEY_3 + " TEXT, " - + KEY_GROUP_USER_KEY_4 + " TEXT, " - + KEY_GROUP_USER_KEY_5 + " TEXT, " - + KEY_GROUP_USER_KEY_6 + " TEXT, " - + KEY_LAST_UPDATE_TIME + " LONG); "; - - private static final String CREATE_CATE_TRACK = "create table " + CATE_TRACK_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_CATE_NAME + " TEXT, " - + KEY_TRACK_ID + " TEXT, " - + KEY_CATE_TRACK_STATUS + " TEXT, " - + KEY_TRACK_2_COL4 + " TEXT, " - + KEY_TRACK_2_COL5 + " TEXT, " - + KEY_TRACK_2_COL6+ " TEXT, " - + KEY_TRACK_2_COL7 + " TEXT, " - + KEY_TRACK_2_COL8 + " TEXT, " - + KEY_LAST_UPDATE_TIME + " LONG); "; - - - - private static final String CREATE_ACTIVITY_TABLE = "create table " + ACTIVITY_TABLE + " (" - + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + KEY_SVR_NUMBER + " INTEGER, " - + KEY_ACTIVITY_NAME + " TEXT, " - + KEY_ACTIVITY_OWNER + " TEXT, " - + KEY_ACTIVITY_DESC + " TEXT, " - + KEY_ACTIVITY_LOCATION + " TEXT, " - + KEY_ACTIVITY_TYPE + " TEXT, " - + KEY_ACTIVITY_ST_DATE+ " TEXT, " - + KEY_ACTIVITY_END_DATE + " TEXT, " - + KEY_ACTIVITY_SPONSORS + " TEXT, " - + KEY_ACTIVITY_STATUS + " TEXT, " - + KEY_ACTIVITY_COL1+ " TEXT, " - + KEY_ACTIVITY_COL2 + " TEXT, " - + KEY_ACTIVITY_COL3 + " TEXT, " - + KEY_ACTIVITY_COL4 + " TEXT, " - + KEY_ACTIVITY_COL5+ " TEXT, " - + KEY_ACTIVITY_COL6 + " TEXT, " - + KEY_ACTIVITY_COL7 + " TEXT, " - + KEY_ACTIVITY_COL8 + " TEXT, " - + KEY_LAST_UPDATE_TIME + " LONG); "; - - private static final String DATABASE_CREATE = CREATE_TRACK_TABLE + CREATE_GEO_TABLE +CREATE_TRACK_GEO_TABLE+"..."+CREATE_ACTIVITY_TABLE ; - - public PlacesDatabaseHelper(Context context, String name, CursorFactory factory, int version) { - super(context, name, factory, version); - } - - @Override - public void onCreate(SQLiteDatabase db) { - - db.execSQL(CREATE_TRACK_TABLE); - db.execSQL(CREATE_GEO_TABLE); - db.execSQL(CREATE_TRACK_GEO_TABLE); - db.execSQL(CREATE_CATE_TRACK); - db.execSQL(CREATE_USER_TABLE); - db.execSQL(CREATE_GROUPS_TABLE); - db.execSQL(CREATE_ACTIVITY_TABLE); - db.execSQL(CREATE_GROUP_USER); - // QLog.getLogger().dLog(TAG, " DATABASE_CREATE: " + DATABASE_CREATE); - insertInitialValues(db); - } - - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - // QLog.getLogger().dLog(TAG, " Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); - - //TODO: migrate data for db upgrade - db.execSQL("DROP TABLE IF EXISTS " + TRACKS_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + GEOS_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + TRACK_GEOS_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + USERS_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + GROUPS_TABLE); -// db.execSQL("DROP TABLE IF EXISTS " + CATEGORY_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + CATE_TRACK_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + ACTIVITY_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + USERS_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + GROUPS_TABLE); - db.execSQL("DROP TABLE IF EXISTS " + GROUP_USER_TABLE); - onCreate(db); - - } - private void insertInitialValues(SQLiteDatabase db){ - // QLog.getLogger().dLog(TAG, " adding default cates... " ); - /* String INSERT_CATES = "INSERT INTO "+CATE_TRACK_TABLE +"(" - + KEY_CATE_NAME +"," - + KEY_TRACK_ID - + ")" - + " VALUES (" - +"'通勤','0' );"; - QLog.getLogger().dLog(TAG, " INSERT_CATES: "+INSERT_CATES ); - db.beginTransaction(); - db.execSQL(INSERT_CATES); - - INSERT_CATES = "INSERT INTO "+CATE_TRACK_TABLE +"(" - + KEY_CATE_NAME +"," - + KEY_TRACK_ID - + ")" - + " VALUES (" - +"'休闲','0' );"; - db.execSQL(INSERT_CATES); - QLog.getLogger().dLog(TAG, " INSERT_CATES: "+INSERT_CATES ); - INSERT_CATES = "INSERT INTO "+CATE_TRACK_TABLE +"(" - + KEY_CATE_NAME +"," - + KEY_TRACK_ID - + ")" - + " VALUES (" - +"'竞速','0');"; - QLog.getLogger().dLog(TAG, " INSERT_CATES: "+INSERT_CATES ); - db.execSQL(INSERT_CATES); - db.endTransaction(); - */ - -// ContentValues[] values = new ContentValues[3]; -// List valueList = new ArrayList(); - ContentValues value; -// int i=0; - - -// valueList.add(value); -/* value = new ContentValues(); - value.put(TrackProvider.KEY_CATE_NAME, "休闲"); - value.put(TrackProvider.KEY_TRACK_ID, 0); - db.insert(CATE_TRACK_TABLE, null, value); */ -// valueList.add(value); - value = new ContentValues(); - value.put(TrackProvider.KEY_CATE_NAME, "竞速"); - value.put(TrackProvider.KEY_TRACK_ID, 0); - db.insert(CATE_TRACK_TABLE, null, value); -// valueList.add(value); - value = new ContentValues(); - value.put(TrackProvider.KEY_CATE_NAME, "骑游"); - value.put(TrackProvider.KEY_TRACK_ID, 0); -// QLog.getLogger().d(dTAG, TAG+" adding new cate is "+key); - db.insert(CATE_TRACK_TABLE, null, value); - - /* try { - db.insert(table, nullColumnHack, values) ; - - } - catch (Exception er) { - Utils.logStackTrace(er, dTAG); - }*/ - - - // QLog.getLogger().dLog(TAG, " adding default cates... done" ); - - - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/receivers/BootReceiver.java b/qy/src/main/java/com/qiyou/mb/android/receivers/BootReceiver.java deleted file mode 100644 index 75fb807..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/receivers/BootReceiver.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.qiyou.mb.android.receivers; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.service.LocationService; -import com.qiyou.mb.android.utils.log.QLog; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -public class BootReceiver extends BroadcastReceiver { - - public static String TAG ="com.qiyou.BroadcastReceiver"; - public static final String dTAG ="com.qiyou"; - - @Override - public void onReceive(Context context, Intent intent) { - QLog.getLogger().d(dTAG,TAG+" intent.getAction() " +intent.getAction()); - if (intent.getAction().equals(QiYouConstant.EXTRA_KEY_BOOT)){ - QLog.getLogger().d(dTAG,TAG+" Android started, to check last track status " ); - Intent serviceIntent = new Intent(context, LocationService.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_BOOT, "True"); - context.startService(serviceIntent); - - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/receivers/CoarseLocationReceiver.java b/qy/src/main/java/com/qiyou/mb/android/receivers/CoarseLocationReceiver.java deleted file mode 100644 index ecdcca4..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/receivers/CoarseLocationReceiver.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.qiyou.mb.android.receivers; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.service.OfflineMapService; -import com.qiyou.mb.android.utils.log.QLog; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -public class CoarseLocationReceiver extends BroadcastReceiver { - public static String TAG ="com.qiyou.CoarseLocationReceiver"; - public static final String dTAG ="com.qiyou"; - public CoarseLocationReceiver() { - // TODO Auto-generated constructor stub - } - - @Override - public void onReceive(Context context, Intent intent) { - - - String key =null; -// Location location =null; - String GEOAdressString =null; - - key = QiYouConstant.EXTRA_KEY_OFFMAP; - if (intent.hasExtra(key)) - { - QLog.getLogger().d(dTAG, TAG+ " offmap update... Network Coarse locaiton change Receiver got GEOAdressString "); - QLog.getLogger().d(dTAG, TAG+ " offmap update... GEOAdressString: " + GEOAdressString); - GEOAdressString = intent.getExtras().getString(key); -// Log.e(TAG, "GPS time:" +Utils.getFormatedTime(location.getTime())); - Intent serviceIntent = new Intent(context, OfflineMapService.class); - serviceIntent.putExtra(key, GEOAdressString); - context.startService(serviceIntent); - - } - - - /* key = LocationManager.KEY_LOCATION_CHANGED; - if (intent.hasExtra(key)) - { - QLog.getLogger().d(dTAG, TAG+ " Network Coarse locaiton change Receiver got noticed "); - location = (Location)intent.getExtras().get(key); - - Intent serviceIntent = new Intent(context, OfflineMapService.class); - serviceIntent.putExtra(key, GEOAdressString); - context.startService(serviceIntent); - }*/ - - - -// Bundle extras = intent.getExtras(); - - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/receivers/ForceUpdateReceiver.java b/qy/src/main/java/com/qiyou/mb/android/receivers/ForceUpdateReceiver.java deleted file mode 100644 index 2fde02f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/receivers/ForceUpdateReceiver.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.receivers; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.service.LocationService; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -/** - * @author mwang - * - */ -public class ForceUpdateReceiver extends BroadcastReceiver { - - public static String TAG ="com.qiyou.ForceUpdateReceiver"; - public static final String dTAG ="com.qiyou"; - - /** - * - */ - public ForceUpdateReceiver() { - // TODO Auto-generated constructor stub - } - - /* (non-Javadoc) - * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) - */ - @Override - public void onReceive(Context context, Intent intent) { - - String key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE; - if (intent.hasExtra(key)) { - // Log.e(TAG, "Receiver got noticed, and sending to service."); - boolean isForceUpdate = intent.getExtras().getBoolean(key); - QLog.getLogger().dLog(TAG," AlarmManager time:" +Utils.getFormatedTime(System.currentTimeMillis()) +" ," + String.valueOf(isForceUpdate)); -// QLog.getLogger().d(dTAG, TAG+" "+"AlarmManager time:" +Utils.getFormatedTime(System.currentTimeMillis()) +" ," + String.valueOf(isForceUpdate)) ; -// Log.e(TAG, "Hello AlarmManager, this is receiver, forwarding your request... " ); - - Intent serviceIntent = new Intent(context, LocationService.class); - serviceIntent.putExtra(key, isForceUpdate); - context.startService(serviceIntent); - - } - - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/receivers/NetworkChangesReceiver.java b/qy/src/main/java/com/qiyou/mb/android/receivers/NetworkChangesReceiver.java deleted file mode 100644 index 961b0be..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/receivers/NetworkChangesReceiver.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.qiyou.mb.android.receivers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.text.TextUtils; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.service.BDLocationSvc; -import com.qiyou.mb.android.service.TrackGEOService; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -//这个receiver不需要注册么? -public class NetworkChangesReceiver extends BroadcastReceiver { - - public static String TAG ="com.qiyou.NetworkChangesReceiver"; - public static final String dTAG ="com.qiyou"; - - @Override - public void onReceive(Context context, Intent intent) { - /* ConnectivityManager connectMgr = (ConnectivityManager) getSystemService; - NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); - NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); - if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) { - Log.i(TAG, "unconnect"); - // unconnect network - }else { - // connect network - } */ - - - - String action = intent.getAction(); - QLog.getLogger().d(dTAG, TAG+" NetworkChangesReceiver get action " + action); - if(TextUtils.equals(action, QiYouConstant.ACTION_CONNECTIVITY_CHANGE )){//网络变化的时候会发送通知 - QiYouConstant.NETWORK_CONNECTED =Utils.isNetworkConnected(context); - - QLog.getLogger().d(dTAG, TAG+" 网络变化了...."); - int networkType =Utils.getNetworkType(context); - QLog.getLogger().d(dTAG, TAG +( networkType>-1?(networkType ==1?" WIFII 可用 ":" Mobile Network 可用"): " 网络断掉了")); - if( networkType==QiYouConstant.NETWORK_TYPE_WIFII && Utils.canProcessWifiConn(context)){ -// SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); -// QiYouConstant.LAST_GEO_UPDATE =settings.getLong(QiYouConstant.PK_LONG_LAST_GEO_UPDATE, 0); -// QiYouConstant.CAN_GEO_UPDATE = System.currentTimeMillis()- QiYouConstant.LAST_GEO_UPDATE > QiYouConstant.GEO_UPDATE_INTERVAL*1000*60; -// - if(Utils.canUpdateGEOfootmark(context)){ - //update GEO, roadbook info - QLog.getLogger().d(dTAG, TAG+" 开始联网 更新 GEO 信息... "); - Intent serviceIntent = new Intent(context, TrackGEOService.class); - serviceIntent.putExtra(QiYouConstant.ACTION_CONNECTIVITY_CHANGE, "True"); - context.startService(serviceIntent); - } - if(Utils.canUpdateOffmap(context)){ //update offmap - Intent serviceIntent = new Intent(context, BDLocationSvc.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_NETWORK_LOCATION,QiYouConstant.EXTRA_KEY_GET_CURRENT_CITY); - context.startService(serviceIntent); - } - - - } - - - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/receivers/NewWaypointsReceiver.java b/qy/src/main/java/com/qiyou/mb/android/receivers/NewWaypointsReceiver.java deleted file mode 100644 index 68e2ff1..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/receivers/NewWaypointsReceiver.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.receivers; -import java.util.ArrayList; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.service.TrackDbServiceBackground; -import com.qiyou.mb.android.utils.log.QLog; -//import com.qiyou.mb.android.service.TrackDbService; - -/** - * @author mwang - * - */ -public class NewWaypointsReceiver extends BroadcastReceiver { - - public static String TAG ="com.qiyou.NEW_WAYPOINTS_RECEIVER"; - public static final String dTAG ="com.qiyou"; - - /** - * - */ - public NewWaypointsReceiver() { - // TODO Auto-generated constructor stub - } - - /* (non-Javadoc) - * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) - */ - @Override - public void onReceive(Context context, Intent intent) { - - //location service -->track service - String key = QiYouConstant.NEW_LOCATION; - if (intent.hasExtra(key)) { -// QLog.getLogger().d(dTAG,TAG+" "+"LocationService Receiver got noticed, and sending to TrackService for db update"); - @SuppressWarnings("unchecked") - ArrayList locLst = (ArrayList) intent.getExtras().get(key) ; - // This update came from Passive provider, so we can extract the location - // directly. - // location = (Location)intent.getExtras().get(key); -// String JsonWp = intent.getExtras().get(key).toString(); -// ArrayList locLst = (ArrayList)(intent.getExtras().getParcelable(QiYouConstant.NEW_LOCATION)); - Intent serviceIntent = new Intent(context, TrackDbServiceBackground.class); - serviceIntent.putExtra(key, locLst); - context.startService(serviceIntent); -// return; - } - //from locationservice to trackservice - key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE; - if (intent.hasExtra(key)) { - QLog.getLogger().d(dTAG,TAG+" "+ "Force update Receiver got noticed, and sending to TrackService for db update"); - QLog.getLogger().d("Force_update", "Force update Receiver got noticed, and sending to TrackService for db update"); - - Intent serviceIntent = new Intent(context, TrackDbServiceBackground.class); - serviceIntent.putExtra(key, true); - context.startService(serviceIntent); - - } - - /* key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE_STAT; - if (intent.hasExtra(key)) { - QLog.getLogger().dLog(dTAG,TAG+" begin to update track statics"); - - Intent serviceIntent = new Intent(context, TrackDbServiceBackground.class); - serviceIntent.putExtra(key, true); - context.startService(serviceIntent); - - } */ - - - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/receivers/TimeTickReceiver.java b/qy/src/main/java/com/qiyou/mb/android/receivers/TimeTickReceiver.java deleted file mode 100644 index 70b840f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/receivers/TimeTickReceiver.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.qiyou.mb.android.receivers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.service.TimtickService; -import com.qiyou.mb.android.utils.log.QLog; - -public class TimeTickReceiver extends BroadcastReceiver { - - public static String TAG ="com.qiyou.TimeTickReceiver"; - public static final String dTAG ="com.qiyou"; - @Override - public void onReceive(Context context, Intent intent) { - QLog.getLogger().d(dTAG,TAG+".......TimeTickReceiver....... intent.getAction() " +intent.getAction()); - if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { - Intent serviceIntent = new Intent(context, TimtickService.class); - - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); - long lastStart = settings.getLong(QiYouConstant.PK_LONG_LAST_TRACK_START,-1); - if(lastStart <=0){ - context.stopService(serviceIntent); - return; - } - - String key = QiYouConstant.EXTRA_KEY_TICK_UPDATE; - - serviceIntent.putExtra(key, true); - context.startService(serviceIntent); -// if(QiYouConstant.DEVELOPER_MODE) Utils.logStackTrace(new Exception("it is for debug only...to start TimtickService...for checking gps "),dTAG); - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/BDLocationSvc.java b/qy/src/main/java/com/qiyou/mb/android/service/BDLocationSvc.java deleted file mode 100644 index b16f145..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/BDLocationSvc.java +++ /dev/null @@ -1,239 +0,0 @@ -package com.qiyou.mb.android.service; - -import android.app.IntentService; -import android.content.Intent; -import android.location.Location; -import android.location.LocationManager; -import android.text.TextUtils; -import android.util.Log; - -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.LocationMode; -//import com.baidu.location.BDLocation; -//import com.baidu.location.BDLocationListener; -//import com.baidu.location.LocationClient; -//import com.baidu.location.LocationClientOption; -import com.google.gson.Gson; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -public class BDLocationSvc extends IntentService { - - public final static String TAG = "com.qiyou.BDLocationSvc"; - public final static String dTAG = "com.qiyou"; - - LocationClient mLocClient; - MyLocationListenner myListener ; - QiYouApplication app ; - public BDLocationSvc() { - super(TAG); - // TODO Auto-generated constructor stub - } - - public BDLocationSvc(String name) { - super(name); - // TODO Auto-generated constructor stub - } - - @Override - public void onCreate() { -// locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); - super.onCreate(); - if(!QiYouConstant.NETWORK_CONNECTED ){ -// if(!Utils.isNetworkConnected(getApplicationContext())){ - - app.isNetworkLocationRequestStarted=false; - this.stopSelf(); - } - app = (QiYouApplication) this.getApplication(); - if(app.mLocClient==null){ - app.mLocClient = new LocationClient(getApplicationContext()); - } - mLocClient =app.mLocClient; - if(app.bdListener==null){ - app.bdListener = new MyLocationListenner(); - } - - myListener = (MyLocationListenner) app.bdListener; - - QLog.getLogger().d(dTAG, TAG +" Begin to request BDlocation service..."); - - } -// boolean isOffMap; -// boolean isLocation; - - @Override - protected void onHandleIntent(Intent intent) { - // TODO Auto-generated method stub - - if(app.isNetworkLocationRequestStarted) return; - app.isNetworkLocationRequestStarted=true; -// isOffMap=false; -// isLocation=false; - String key; -// Bundle extras = intent.getExtras(); - String value=null; - key =QiYouConstant.EXTRA_KEY_NETWORK_LOCATION; - if(intent.hasExtra(key)){ - value= intent.getExtras().getString(key); - QLog.getLogger().d(dTAG, TAG+ " get extra vlaue of: "+value); - } - if(TextUtils.isEmpty(value)) return; - QiYouConstant.NETWORK_LOCATION_FOR_GEO =value.equalsIgnoreCase(QiYouConstant.EXTRA_KEY_GET_CURRENT_CITY); - QiYouConstant.NETWORK_LOCATION_FOR_LOCATION=value.equalsIgnoreCase( LocationManager.KEY_LOCATION_CHANGED);; -// key = QiYouConstant.EXTRA_KEY_GET_CURRENT_CITY; -// isOffMap =intent.hasExtra(key); -// -// key = LocationManager.KEY_LOCATION_CHANGED; -// isLocation=intent.hasExtra(key); - - startRequestLocation() ; - } - class MyLocationListenner implements BDLocationListener { - @Override - public void onReceiveLocation(BDLocation location) { - // TODO Auto-generated method stub - if (location == null) - return; - // if (location.getLocType() == BDLocation.TypeGpsLocation) - int errCode=location.getLocType(); - QLog.getLogger().d(dTAG, TAG +" BDlocation error code:" + location.getLocType()); - if(errCode==161){ - if(QiYouConstant.NETWORK_LOCATION_FOR_LOCATION && app.canSendLocation2UI){ - app.isNetworkLocationRequestStarted =true; - QLog.getLogger().d(dTAG, TAG +" get locaiton info for network location service...."); - - QLog.getLogger().d(dTAG, TAG +" option.getScanSpan: "+ mLocClient.getLocOption().getScanSpan()); -// if(app.playBack ||!app.canRecord()&&!app.isRouting){ - if(app.canStopNetworkRequest()){ - stopRequestLocation(); - return; - } - - Location loc =new Location(QiYouConstant.LOCATION_BD_LOC); - loc.setLatitude(location.getLatitude()); - loc.setLongitude(location.getLongitude()); - loc.setAccuracy(location.getRadius()); - - Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION,loc); - broadcastIntent.putExtra(QiYouConstant.ACTION_NEW_COARSE_LOCATION,""); - - sendBroadcast(broadcastIntent); - - } else - if(QiYouConstant.NETWORK_LOCATION_FOR_GEO){ - QLog.getLogger().d(dTAG, TAG +" offmap update...get locaiton info for offmap..."); - - - if(app.getGEOinfo()==null || - app.getGEOinfo()!=null && !app.getGEOinfo().getDistrict().equalsIgnoreCase(location.getDistrict())){ - GEOaddress go =new GEOaddress(); - go.setCity(location.getCity()); - go.setCityId( location.getCityCode()); - go.setProvince(location.getProvince()); - go.setStreet(location.getStreet()); - go.setStreetNo(location.getStreetNumber()); - go.setDistrict(location.getDistrict()); - go.setLat((float) location.getLatitude()); - go.setLon((float) location.getLongitude()); - QLog.getLogger().d(dTAG, TAG +String.format(" offmap update...BDLocation get cityId :%s,cityName :%s",location.getCityCode(),location.getCity())); - app.setGEOinfo(go); - - int networkType =Utils.getNetworkType(app); - if(networkType==-1) return; //no active network - if( networkType == QiYouConstant.NETWORK_TYPE_WIFII && app.canUpdateOffmap()){ - - QLog.getLogger().d(dTAG, TAG +" offmap update...begin to check offmap status..."); -// app.setlastOffMapRequestTime(); - - Gson gson = new Gson(); - String jsonGo=null; - try{ - jsonGo = gson.toJson(go); - }catch(Exception e) - { - Log.e(TAG,jsonGo); - Utils.logStackTrace(e, dTAG); - } - QLog.getLogger().d(dTAG, TAG +" offmap update...jsonGo is..." +jsonGo); - Intent intent = new Intent(); - intent.setAction(QiYouConstant.ACTION_NEW_COARSE_LOCATION); - intent.putExtra(QiYouConstant.EXTRA_KEY_OFFMAP, jsonGo); - sendBroadcast(intent); - } - - } - stopRequestLocation(); //for offmap, request once only to get cityId - } - - } - - if( !QiYouConstant.NETWORK_CONNECTED || !(QiYouConstant.NETWORK_LOCATION_FOR_LOCATION && app.canSendLocation2UI)) - stopRequestLocation(); - } - - - - } - - void setLocationOption() { - LocationClientOption option = new LocationClientOption(); - -// option.setOpenGps(true); // 打开gps - option.setAddrType("all"); - option.setCoorType("bd09ll"); // 设置坐标类型 -// option.setServiceName("com.baidu.location.service_v2.9"); // ? - option.setScanSpan(5000); // 设置定位模式,小于1秒则一次定位;大于等于1秒则定时定位 - //option.disableCache(true); - option.setPriority(LocationClientOption.GpsFirst); -// option.setPoiNumber(1); - mLocClient.setLocOption(option); // 2.x版本以后的定位给API支持在API运行过程中,热切换配置参数。 - - } - - void startRequestLocation() { -// stopRequestLocation(); - // this nullpoint check is necessary - if (mLocClient != null) { - setLocationOption(); - mLocClient.registerLocationListener(myListener); - mLocClient.start(); - mLocClient.requestLocation(); - QLog.getLogger().d(dTAG, TAG +" mLocClient start Request Location. "); -// startTime = System.currentTimeMillis(); -// app.isNetworkLocationRequestStarted=true; - } - } - - void stopRequestLocation() { - if (mLocClient != null) { - mLocClient.unRegisterLocationListener(myListener); - mLocClient.stop(); - app.isNetworkLocationRequestStarted=false; - QLog.getLogger().d(dTAG, TAG +" mLocClient stop Request Location. "); - } - } - @Override - public void onDestroy() { - -// Log.i(dTAG, TAG +" Services onDestory"); -// stopRequestLocation() ; - // // isStop=true;//即使service销毁线程也不会停止,所以这里通过设置isStop来停止线程 - // QLog.getLogger().d(TAG," save app.sumPaused "+app.sumPaused ); - // QLog.getLogger().d(TAG," save app.sumOfftime: "+app.sumOfftime ); - // QLog.getLogger().d(TAG,"---------app.sumPause loop----------------------------" ); - - super.onDestroy(); - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/DBservice.java b/qy/src/main/java/com/qiyou/mb/android/service/DBservice.java deleted file mode 100644 index 50e9eea..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/DBservice.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.qiyou.mb.android.service; - -import android.app.IntentService; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Intent; -import android.net.Uri; -import android.util.Log; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -public class DBservice extends IntentService { - public static String TAG ="com.qiyou.DBservice"; - public static final String dTAG ="com.qiyou"; - public DBservice(String name) { - super(name); - // TODO Auto-generated constructor stub - } - - @Override - protected void onHandleIntent(Intent arg0) { - // TODO Auto-generated method stub - - } - - - protected ContentResolver contentResolver; - protected String[] projection; - protected QiYouApplication app; - - - @Override - public void onCreate() { - super.onCreate(); - app =(QiYouApplication)this.getApplication(); - contentResolver = getContentResolver(); - } - - - - - /* - * update track - */ - protected void updateTable(Uri uri,ContentValues values,int Id,String[] wps) - { - if(values ==null || values.size()==0) return; - - if(Id <=0){ - Log.e(dTAG,TAG+" Only can updated tracks that in db already, turn to add new track."); -// addNewWayPoints(); //new track - return; - } - - // Update the TrackProvider -// String where = TrackProvider.KEY_ID + " = '" + Id + "'"; - QLog.getLogger().d(dTAG,TAG+" "+ "update Track where id is " + Id ); - try { - uri = Uri.withAppendedPath(TrackProvider.TRACKS_URI, String.valueOf(Id)); - if (contentResolver.update(uri, values, null, wps) == 0) { - //没有找到记录,新增track. - Log.e(dTAG,TAG+" "+"没有可匹配更新。"); -// tb.setTrackId(0); -// addNewWayPoints(); - } - - } - catch (Exception er) { -// Log.e(dTAG, TAG+ " Update Tracks db Adding/Update failed."); - Utils.logStackTrace(er, dTAG); - } - - - - } - @Override - public void onDestroy() { - super.onDestroy(); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/DBserviceNew.java b/qy/src/main/java/com/qiyou/mb/android/service/DBserviceNew.java deleted file mode 100644 index 1659bcc..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/DBserviceNew.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.qiyou.mb.android.service; - -import android.app.Service; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Intent; -import android.net.Uri; -import android.os.IBinder; -import android.util.Log; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -public class DBserviceNew extends Service { - public static String TAG ="com.qiyou.DBserviceNew"; - public static final String dTAG ="com.qiyou"; -// public DBserviceNew(String name) { -// super(name); -// // TODO Auto-generated constructor stub -// } - - - @Override - public void onStart(Intent intent, int startId) { - QLog.getLogger().d(dTAG,TAG+"... service TimtickService onStart.....," ); - if(intent!=null) - handleIntent(intent); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId){ - QLog.getLogger().d(dTAG,TAG+"... service TimtickService onStartCommand.....," ); - handleIntent(intent); - // We want this service to continue running until it is explicitly - // stopped, so return sticky. - return START_STICKY; - } - protected void handleIntent(Intent intent){ - - //to check if the application restart with new instances or not - // The check result is, the new application instance created, the original referenced application still exits. - - //TODO: to find what cause creating new application instances? - -// String debugstring="Time Tick regist at: "+ registTime+ ", Application instance start time is:" + app.startTime +",Time past:"+( app.startTime -registTime); -// QLog.getLogger().d(dTAG,TAG+ debugstring); -// Utils.logStackTrace(new Exception(debugstring),dTAG); - - -// String key = QiYouConstant.EXTRA_KEY_TICK_UPDATE; - - } - - protected ContentResolver contentResolver; - protected String[] projection; - protected QiYouApplication app; - - - @Override - public void onCreate() { - super.onCreate(); - app =(QiYouApplication)this.getApplication(); - contentResolver = getContentResolver(); - } - - - - - /* - * update track - */ - protected void updateTable(Uri uri,ContentValues values,int Id,String[] wps) - { - if(values ==null || values.size()==0) return; - - if(Id <=0){ - Log.e(dTAG,TAG+" Only can updated tracks that in db already, turn to add new track."); -// addNewWayPoints(); //new track - return; - } - - // Update the TrackProvider -// String where = TrackProvider.KEY_ID + " = '" + Id + "'"; - QLog.getLogger().d(dTAG,TAG+" "+ "update Track where id is " + Id ); - try { - uri = Uri.withAppendedPath(TrackProvider.TRACKS_URI, String.valueOf(Id)); - if (contentResolver.update(uri, values, null, wps) == 0) { - //没有找到记录,新增track. - Log.e(dTAG,TAG+" "+"没有可匹配更新。"); -// tb.setTrackId(0); -// addNewWayPoints(); - } - - } - catch (Exception er) { - Log.e(dTAG, TAG+ " Update Tracks db Adding/Update failed."); - Utils.logStackTrace(er, dTAG); - } - - - - } - @Override - public void onDestroy() { - super.onDestroy(); - } - - @Override - public IBinder onBind(Intent intent) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/GpsService.java b/qy/src/main/java/com/qiyou/mb/android/service/GpsService.java deleted file mode 100644 index 6a03833..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/GpsService.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.qiyou.mb.android.service; - -import org.apache.commons.logging.Log; - -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.os.Bundle; -import android.os.IBinder; -import android.os.PowerManager; -import android.os.PowerManager.WakeLock; - -public class GpsService extends Service { - - WakeLock wakeLock; - - private LocationManager locationManager; - - public GpsService() { - // TODO Auto-generated constructor stub - } - - @Override - public IBinder onBind(Intent arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void onCreate() { - // TODO Auto-generated method stub - super.onCreate(); - - PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE); - - wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep"); - - // Toast.makeText(getApplicationContext(), "Service Created", - // Toast.LENGTH_SHORT).show(); - -// Log.e("Google", "Service Created"); - - } - - @Override - @Deprecated - public void onStart(Intent intent, int startId) { - // TODO Auto-generated method stub - super.onStart(intent, startId); - -// Log.e("Google", "Service Started"); - - locationManager = (LocationManager) getApplicationContext() - .getSystemService(Context.LOCATION_SERVICE); - - locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, - 5000, 5, listener); - - } - - private LocationListener listener = new LocationListener() { - - @Override - public void onLocationChanged(Location location) { - // TODO Auto-generated method stub - -// Log.e("Google", "Location Changed"); - - if (location == null) - return; - - /* if (isConnectingToInternet(getApplicationContext())) { - JSONArray jsonArray = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - - try { - Log.e("latitude", location.getLatitude() + ""); - Log.e("longitude", location.getLongitude() + ""); - - jsonObject.put("latitude", location.getLatitude()); - jsonObject.put("longitude", location.getLongitude()); - - jsonArray.put(jsonObject); - - Log.e("request", jsonArray.toString()); - - new LocationWebService().execute(new String[] { - Constants.TRACK_URL, jsonArray.toString() }); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - }*/ - - } - - @Override - public void onProviderDisabled(String provider) { - // TODO Auto-generated method stub - - } - - @Override - public void onProviderEnabled(String provider) { - // TODO Auto-generated method stub - - } - - @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - // TODO Auto-generated method stub - - } - }; - - @Override - public void onDestroy() { - // TODO Auto-generated method stub - super.onDestroy(); - - wakeLock.release(); - - } - -/* public static boolean isConnectingToInternet(Context _context) { - ConnectivityManager connectivity = (ConnectivityManager) _context - .getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivity != null) { - NetworkInfo[] info = connectivity.getAllNetworkInfo(); - if (info != null) - for (int i = 0; i < info.length; i++) - if (info[i].getState() == NetworkInfo.State.CONNECTED) { - return true; - } - - } - return false; - } -*/ - } \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/service/LocationMornitorService.java b/qy/src/main/java/com/qiyou/mb/android/service/LocationMornitorService.java deleted file mode 100644 index ee1e942..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/LocationMornitorService.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.qiyou.mb.android.service; - -import android.app.IntentService; -import android.content.Intent; -import android.location.Location; -import android.location.LocationManager; -import android.util.Log; - -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.log.QLog; - -/* - * Monitor the locaiton GPS signal, while the signal continues the service will exit. - */ -public class LocationMornitorService extends IntentService { - - public final static String TAG="com.qiyou.MORNITOR_LOCATION_SERVICE"; - public static final String dTAG ="com.qiyou"; - protected QiYouApplication app; - long update_interval = 0; - long logtime; - -// Location location ; - public LocationMornitorService( ) { - super(TAG); - // TODO Auto-generated constructor stub -// app =(QiYouApplication)this.getApplication(); - - } - public LocationMornitorService(String name) { - super(name); - // TODO Auto-generated constructor stub - - } - - @Override - public void onCreate() { - super.onCreate(); - app =(QiYouApplication)this.getApplication(); - update_interval = app.getGPS_REQUEST_SPAN()/2*4; - printAppStartTime(); - QLog.getLogger().d(dTAG,TAG+" Start the service for monitoring GPS status. time: "+ System.currentTimeMillis() ); - - } - - @Override - protected void onHandleIntent(Intent intent) { - if(!app.canSendLocation2UI) return; - if(app.playBack || app.getRecordingTrack().getTrackBean().getStatus()!=TrackStatus.RECORDING)return; -// if(!intent.hasExtra(QiYouConstant.NEW_LOCATION))return; -// location =(Location)intent.getExtras().get(QiYouConstant.NEW_LOCATION); - monitorLocation(); - - } - -// long lastLocTime=0; - void monitorLocation() - { - try { - - while(!app.canSendLocation2UI && app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.RECORDING){ - Thread.sleep(update_interval); - printAppStartTime();//QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ app.startTime ); - - } - - - Location loc =app.playBack?null:app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); - if(loc!=null){ -// lastLocTime =loc.getTime(); - QLog.getLogger().d(dTAG,TAG + " getLastKnownLocation loc.time " + loc.getTime()); -// QLog.getLogger().d(dTAG,TAG+" "+ "1, System.currentTimeMillis() - loc.getTime():" -// + String.valueOf(System.currentTimeMillis() - loc.getTime() ) +",update_interval*5 is "+update_interval*5); - - } -// else -// { -// QLog.getLogger().d(dTAG,TAG + " getLastKnownLocation loc is null.."); -// } -// if(!app.playBack)loc = app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); - - if(loc ==null) loc =app.getLocationCached().size()>0 - ?app.getLocationCached().get(app.getLocationCached().size()-1) - :app.lastLocation; - if(loc ==null){ - Log.i(dTAG,TAG + " loc is null.."); - notifyUI(); -// return; - } -// if(loc!=null) QLog.getLogger().d(dTAG,TAG+" "+ "2, System.currentTimeMillis() - loc.getTime():" -// + String.valueOf(System.currentTimeMillis() - loc.getTime() ) +",update_interval*5 is "+update_interval*5); - //no location ever get. -// while(app.canSendLocation2UI && System.currentTimeMillis() - loc.getTime()0 - ?app.getLocationCached().get(app.getLocationCached().size()) - :app.lastLocation; - if(loc ==null){ - Log.i(dTAG,TAG + " loc is null.."); - notifyUI(); - return; - } - printAppStartTime();//QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ app.startTime ); - - - } -// if(loc!=null) QLog.getLogger().d(dTAG,TAG+" "+ "3, System.currentTimeMillis() - loc.getTime():" -// + String.valueOf(System.currentTimeMillis() - loc.getTime() ) +",update_interval*5 is "+update_interval*5); - //when ever get one location at least - -// boolean noGps=app.canSendLocation2UI && loc!=null && System.currentTimeMillis() - loc.getTime()>update_interval*5 -// && app.getRecordingTrack().getTrackBean().getStatus()==QiYouConstant.TRACK_STATUS_TRACKING; -// QLog.getLogger().d(dTAG,TAG+" noGps "+noGps); - -// if(loc!=null) QLog.getLogger().d(dTAG,TAG + "4, getLastKnownLocation loc.time " + loc.getTime()+", original last time is "+lastLocTime); - - while(app.canSendLocation2UI && loc!=null && System.currentTimeMillis() -app.lastLocationTime>update_interval*2 - && app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.RECORDING &&!app.isNetworkLocationRequestStarted) - { -// QLog.getLogger().d(dTAG,TAG + "5, getLastKnownLocation loc.time " + loc.getTime()+", original last time is "+lastLocTime); -// QLog.getLogger().d(dTAG,TAG+" "+ "5, System.currentTimeMillis() - loc.getTime():" -// + String.valueOf(System.currentTimeMillis() - loc.getTime() ) +",update_interval*5 is "+update_interval*5); -// QLog.getLogger().dLog(dTAG,TAG+" "+ " monitorGPS(), System.currentTimeMillis() " + System.currentTimeMillis() +",app.lastLocationTime is "+app.lastLocationTime ); -// QLog.getLogger().dLog(dTAG,TAG+" "+ " monitorGPS(), System.currentTimeMillis() - app.lastLocationTime:" + String.valueOf(System.currentTimeMillis() - app.lastLocationTime ) +",update_interval*5 is "+update_interval*5); -//// -// QLog.getLogger().d(dTAG,TAG+" "+ " monitorGPS(), System.currentTimeMillis() - loc.getTime():" + String.valueOf(System.currentTimeMillis() - lastLocTime ) +",update_interval*5 is "+update_interval*5); -// - notifyUI(); - Thread.sleep(update_interval); -// printAppStartTime();//QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ app.startTime ); -// monitorLocation(); -// loc = app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); -// lastLocTime =loc!=null?loc.getTime():System.currentTimeMillis(); - - } - - - - } catch (InterruptedException e) { - // TODO Auto-generated catch block -// e.printStackTrace(); - Utils.logStackTrace(e,TAG); - } - } - - - - void notifyUI(){ - QLog.getLogger().d(dTAG,TAG+" Lost the gps signal..."); - if(app.isNetworkLocationRequestStarted || app.playBack ) return; - - Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, new Location(QiYouConstant.LOCATION_MONITOR)); -// broadcastIntent.putExtra(QiYouConstant.EXTRA_KEY_NO_LOCCATION_SIGNAL, true); - sendBroadcast(broadcastIntent); - -// Utils.logStackTrace(new Exception(" Lost the gps signal..."),TAG); - - } - - void printAppStartTime(){ - if(app.startTime!=logtime){ - logtime =app.startTime; - QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ logtime ); - } - } - - @Override - public void onDestroy() { - -// Log.i(dTAG,TAG + " Services onDestory"); - - // // isStop=true;//即使service销毁线程也不会停止,所以这里通过设置isStop来停止线程 - // QLog.getLogger().d(TAG," save app.sumPaused "+app.sumPaused ); - // QLog.getLogger().d(TAG," save app.sumOfftime: "+app.sumOfftime ); - // QLog.getLogger().d(TAG,"---------app.sumPause loop----------------------------" ); - - super.onDestroy(); - - } - -} - - - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/service/LocationService.java b/qy/src/main/java/com/qiyou/mb/android/service/LocationService.java deleted file mode 100644 index 7235d3b..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/LocationService.java +++ /dev/null @@ -1,1645 +0,0 @@ -package com.qiyou.mb.android.service; - -import java.util.ArrayList; -import java.util.HashMap; -import android.app.IntentService; -import android.content.Intent; -import android.location.Location; -import android.location.LocationManager; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; - -public class LocationService extends IntentService { -//public class LocationService extends Service { - - public final static String TAG = "com.qiyou.LOCATION_SERVICE"; - public static final String dTAG = "com.qiyou"; - protected boolean isForceUpdate = false; - - - -/* @Override - public void onStart(Intent intent, int startId) { - QLog.getLogger().d(dTAG,TAG+"... service LOCATION_SERVICE onStart.....," ); - if(intent!=null) - handleIntent(intent); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId){ - QLog.getLogger().d(dTAG,TAG+"... service LOCATION_SERVICE onStartCommand.....," ); - handleIntent(intent); - // We want this service to continue running until it is explicitly - // stopped, so return sticky. - return START_STICKY; - } - */ - - public LocationService() { - super(TAG); - } - - public LocationService(String name) { - super(name); - // TODO Auto-generated constructor stub - } - - protected QiYouApplication app; - - @Override - public void onCreate() { - super.onCreate(); - app = (QiYouApplication) this.getApplication(); -// app.reviewTrackStatus(); - isPlayback =app.playBack && QiYouConstant.PLAYBACK_CAN_RECORD; - trackType = app.getRecordingTrack().getTrackBean().getType(); - MAX_TIME_UPDATE_DB = Utils.get_updatedb_invterval(trackType); -// QLog.getLogger().dLog(TAG," LocationService is created....................................................... "); - } - - @Override - protected void onHandleIntent(Intent intent) { -//// @Override -// protected void handleIntent(Intent intent) { - // TODO Auto-generated method stub - - String key; - Bundle extras = intent.getExtras(); - - /* key =QiYouConstant.STOP_LOCATION_SERVICE; - if (intent.hasExtra(key)) { - stopSelf(); - } - */ - - key = QiYouConstant.EXTRA_KEY_BOOT; - // QLog.getLogger().d(dTAG,TAG+"intent.hasExtra(key), Key, app.isLastTrackExist():"+intent.hasExtra(key) - // +" , "+key+" , "+ app.isLastTrackExist()); - - if (intent.hasExtra(key)) { - if (app.isLastTrackExist()) { - app.restoreLastTracking(); -// QLog.getLogger().dLog(dTAG, TAG + " ----------$%@#$^%$$%^ Restore tracking on boot.............%$%^%%^&@#$#%%^---"); - } - } - /* key = QiYouConstant.EXTRA_KEY_TICK_UPDATE; - if (intent.hasExtra(key)) { - QLog.getLogger().d(dTAG,TAG+ " ----------$%@#$^%$$%^ EXTRA_KEY_TICK_UPDATE get notice to check gps..............%$%^%%^&@#$#%%^---"); - updateGPSstatus(); - return; - }*/ - - isForceUpdate =false; - - key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE; - if (intent.hasExtra(key)) { -// QLog.getLogger().dLog(TAG," LocationService got the alarm notice. "); - - try{ - - - - if (!app.isOneRequestForceUpdate){ - -// app.updateStatistics(); // changed to:1. each save new wapwpoints, 2. finish recording - - if (app.getRecordingTrack().getTrackBean().getLastdbTime() == 0 - || System.currentTimeMillis() - - app.getRecordingTrack().getTrackBean() - .getLastdbTime() < QiYouConstant.MAX_TIME_FORCE_UDATE) - - return; - } - - - if (app.isOneRequestForceUpdate) - app.isOneRequestForceUpdate = false; - - isForceUpdate = extras.getBoolean(key); - // Toast toast= Toast.makeText(this, - // "begin force update... track status: "+app.getRecordingTrack().getTrackBean().getStatus() - // +",last db update time since now(s): " - // +(System.currentTimeMillis() - - // app.getRecordingTrack().getTrackBean().getLastdbTime())/1000, - // Toast.LENGTH_SHORT ); - // toast.show(); - // - /*QLog.getLogger().dLog(TAG, - " begin force update... track status:" - + app.getRecordingTrack().getTrackBean() - .getStatus() - + ",since last db update time (s) :" - + (System.currentTimeMillis() - app - .getRecordingTrack().getTrackBean() - .getLastdbTime()) / 1000);*/ - - processLocation(new Location(QiYouConstant.LOCATION_FORCE_UPDATE)); - - if (app.isAppLong() && app.isLastTrackExist() - && (app.recordingTrack == null || app.isGPSstopped)) { - app.restoreLastTracking(); -// QLog.getLogger().d(dTAG, TAG + " ----------$%@#$^%$$%^ Restore tracking by ForceUpdate.............%$%^%%^&@#$#%%^---"); - } else if (app.isAppLong() - && app.getRecordingTrack().getTrackBean().getStatus() != TrackStatus.RECORDING) { -// QLog.getLogger().d(dTAG, TAG + " Application start time since now(s): " + (System.currentTimeMillis() - app.startTime) / 1000); - app.cancelForceDbAlarm(); - app.stopAndroidGPSRequest(); - return; - } - }catch (Exception er){ - Utils.logStackTrace(er, dTAG); - } - return; - } - - // 记录运动轨迹 - key = LocationManager.KEY_LOCATION_CHANGED; // get location from gps - - try{ - - if (intent.hasExtra(key)) { -// QLog.getLogger().dLog(TAG," Location Service got new location. "); - if ( app.getRecordingTrack().getTrackBean().getStatus() !=TrackStatus.RECORDING){ -// QLog.getLogger().dLog(TAG," app.getRecordingTrack().getTrackBean().getStatus()" +app.getRecordingTrack().getTrackBean().getStatus()); -// QLog.getLogger().dLog(TAG," Location got, No active tracking exits, stopping gps request..."); - app.stopAndroidGPSRequest(); - return; - } -// app.lastNaviLocation= (Location) extras.get(key); -// QLog.getLogger().d(dTAG,TAG+" "+ "gg Location got, and ready to process.");. - -// Location loc =!isPlayback? app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER):(Location) extras.get(key); -// processLocation(loc); - processLocation((Location) extras.get(key)); - return; - } - }catch(Exception er){ - Utils.logStackTrace(er, TAG); - } - - - - key = QiYouConstant.EXTRA_KEY_FINISH_RECORDING; - - if (intent.hasExtra(key)) { - isCleanning=true; - this.preUpdatedb(false); -// QLog.getLogger().dLog(dTAG,"------------------------ cache cleaned--------------------------" ); - - } - - - } - boolean isCleanning; - // update ui, then update db -// String KEY_PAUSETIME = "PAUSETIME"; - // String KEY_OFFTIME="OFFTIME"; - String KEY_AVBEAR = "AVBEAR"; - boolean isFirstwp ; - TrackType trackType; - long MAX_TIME_UPDATE_DB;// = Utils.get_updatedb_invterval(trackType); - - - void processLocation(Location location) { - - /* if(location!=null &&location.getSpeed()>0){ - QLog.getLogger().dLog(TAG," loacation accuracy:" +location.getAccuracy()); - QLog.getLogger().dLog(TAG," loacation speed:" +location.getSpeed()); - }*/ - - - boolean isGpsLocation =Utils.isLocOfGPS(location); -// MAX_TIME_UPDATE_DB = Utils.get_updatedb_invterval(trackType); - isFirstwp = (isPlayback ||isGpsLocation) && app.getRecordingTrack().getTrackBean().getTrackId() == 0; - isFirstwp = isFirstwp && app.getRecordingTrack().getTrackBean().getStartTime()==0; - isFirstwp = isFirstwp && !app.isRestoreLastTracking; - isFirstwp = isFirstwp && location.getSpeed()>0; - - if(isFirstwp){ - - /*if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2) - app.speech("卫星定位成功,记录开始",0);*/ - app.SpDist = 0; - - -// app.setCntKm((int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000)); - -// app.timeKm=System.currentTimeMillis(); -// QLog.getLogger().dLog(TAG,"------------------------ isFirstwp: -----------------------------" +isFirstwp); - } - if(app.timeKm==0){ - app.timeKm=System.currentTimeMillis(); - } - boolean isReturn =!isForceUpdate && location == null || - !isPlayback - && !isForceUpdate - && (location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime()); - - - - - -// QLog.getLogger().dLog(TAG," Location is here 1 "); - if (isReturn){ -// QLog.getLogger().dLog(TAG," !isForceUpdate && location == null, " + (!isForceUpdate && location == null)); -// QLog.getLogger().dLog(TAG," !isPlayback && !isForceUpdate && location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime()" -// +(!isPlayback && !isForceUpdate && (location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime()))); -// QLog.getLogger().dLog(TAG,"returned"); - return; - } - - /* - if(!isFirstwp && !isPlayback && location.getSpeed() >0 ||QiYouConstant.DEVELOPER_MODE){ - //to filter out the suddenly high speed. - - String pearTag="PEARTAG"; - if(app.lastLocation!=null - && app.lastLocation.getSpeed()>0 - && location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN - && location.getSpeed()>2*app.lastLocation.getSpeed() - && location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6){ - - QLog.getLogger().dLog(TAG,pearTag, " Get one peak point!-------"); - QLog.getLogger().dLog(TAG,pearTag, " location.getSpeed() "+location.getSpeed()*3.6); - QLog.getLogger().dLog(TAG,pearTag, " app.lastLocation.getSpeed() "+app.lastLocation.getSpeed()*3.6); - QLog.getLogger().dLog(TAG,pearTag, " 2*app.getRecordingTrack().getTrackBean().getAvs() "+ 2*app.getRecordingTrack().getTrackBean().getAvs() ); - return; - - } - - - }*/ - - /* if(!isFirstwp && !isPlayback && location.getSpeed() >0){ - //to filter out the suddenly high speed. - - String pearTag="PEARTAG"; - - QLog.getLogger().dLog(TAG,pearTag, " location.getSpeed() "+location.getSpeed()); - QLog.getLogger().dLog(TAG,pearTag, " location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN "+(location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN)); - QLog.getLogger().dLog(TAG,pearTag, " location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6 "+(location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6)); - - - if(app.lastLocation!=null -// && app.lastLocation.getSpeed()>0 - && location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN - && location.getSpeed()>2*app.lastLocation.getSpeed() - &&location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6){ - - QLog.getLogger().dLog(TAG,pearTag, " Get one peak point!-------"); -// QLog.getLogger().dLog(TAG,pearTag, " location.getSpeed() "+location.getSpeed()); -// QLog.getLogger().dLog(TAG,pearTag, " app.lastLocation.getSpeed() "+app.lastLocation.getSpeed()); -// QLog.getLogger().dLog(TAG,pearTag, " 2*app.getRecordingTrack().getTrackBean().getAvs()/3.6 "+ 2*app.getRecordingTrack().getTrackBean().getAvs()/3.6); -// - - - if(app.toDecideLocations==null){ - app.toDecideLocations=new ArrayList(); - app.toDecideLocations.add(location); - - return; - }else{ - - QLog.getLogger().dLog(TAG,pearTag, " app.toDecideLocations.contains(location) "+app.toDecideLocations.contains(location)); - - if(app.toDecideLocations.contains(location)){//the location is okay to save - app.toDecideLocations.remove(location); - - }else{//compare with exits ones to decide exists ones to be cleared or allowed - - - QLog.getLogger().dLog(TAG,pearTag, " app.toDecideLocations.size() "+app.toDecideLocations.size()); - - if(app.toDecideLocations.size()>2){ - app.toDecideLocations.add(location); - - for(Location loc:app.toDecideLocations){ - QLog.getLogger().dLog(dTAG, pearTag, "location to be allowed for suddenly big speed is:"+loc.getSpeed()); - } - - for(Location loc:app.toDecideLocations){ - processLocation(loc); - } - return; - } - Location lastLoc =app.toDecideLocations.get(app.toDecideLocations.size()-1); - if(location.getSpeed()>lastLoc.getSpeed()){//new one speed is large than last - app.toDecideLocations.add(location); - }else{// new speed is not bigger than last in - - for(Location loc:app.toDecideLocations){ - QLog.getLogger().dLog(dTAG, pearTag, "location to be removed for suddenly big speed is:"+loc.getSpeed()); - } - - app.toDecideLocations.clear(); - } - - } - - } - - }else if(app.toDecideLocations!=null){ - - - QLog.getLogger().dLog(dTAG, pearTag, " app.lastLocation.getSpeed() is:"+app.lastLocation.getSpeed()); - QLog.getLogger().dLog(dTAG, pearTag, " app.getRecordingTrack().getTrackBean().getAvs()/3.6 is:"+app.getRecordingTrack().getTrackBean().getAvs()/3.6); - for(Location loc:app.toDecideLocations){ - QLog.getLogger().dLog(dTAG, pearTag, "location to be removed for suddenly big speed is:"+loc.getSpeed()); - } - app.toDecideLocations.clear();//remove the large locations with high speed - } - } */ - - - - - - - - // // // //// QLog.getLogger().dLog(TAG," location.getTime():" +location.getTime()); - // // // //// QLog.getLogger().dLog(TAG," app.getRecordingTrack().getTrackBean().getStartTime():" +app.getRecordingTrack().getTrackBean().getStartTime()); - /* - if (!isPlayback - && !isForceUpdate - && app.getRecordingTrack().getTrackBean().getLastWp()!=null - && location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime()){ - - QLog.getLogger().dLog(TAG," !isForceUpdate && location == null, returned. "); - - return;// this should not happen,but in case to get past playback - // location sending which is stopped. - }*/ -// QLog.getLogger().dLog(TAG," Location is here 2 "); - - long pausingTime = 0; - long offTime = 0; -// if (app.canRecord()) { - if (app.canRecord()) { - if ( !isGpsLocation) { // force update, not from location change - - if (isForceUpdate && app.lastOfftime == 0) -// if (isForceUpdate) - app.lastOfftime = System.currentTimeMillis(); - } - - if (app.lastOfftime > 0) { - /* offTime = location.getTime() == 0 ? System.currentTimeMillis() - - app.lastOfftime : location.getTime() - - app.lastOfftime;*/ - - offTime = System.currentTimeMillis() - app.lastOfftime ; //系统时间只能能用于计算 相对时间,绝对时间以gps、network 为准 - offTime =offTime>app.getGPS_REQUEST_SPAN()?offTime:0; - app.offtime = offTime; - app.sumOfftimeWp += offTime; - if (offTime>0 && isForceUpdate) { -// if (location.getTime() == 0) { // only force update during the - // lost gps signal period, to - // count the off time. - // offTime =location.getTime()==0?System.currentTimeMillis() - - // app.lastOfftime :location.getTime() - app.lastOfftime; - app.lastOfftime = System.currentTimeMillis(); - // app.sumOfftime +=offTime; - // app.sumOfftimeWp +=offTime; - } else - app.lastOfftime = 0; - -// QLog.getLogger().d(dTAG, TAG + " app.lastOfftime " + app.lastOfftime); -// QLog.getLogger().d(dTAG, TAG + " app.offtime " + app.offtime); -// QLog.getLogger().d(dTAG, TAG + " app.sumOfftimeWp " + app.sumOfftimeWp); -// QLog.getLogger().d(dTAG, TAG + " track total Offtime: " + app.getRecordingTrack().getTrackBean().getOffTime()); - } - - if ( isGpsLocation ) { - - if(location.hasSpeed() && location.getSpeed()==0 && app.lastPaused == 0){ - app.lastPaused = location.getTime(); - // // // //// QLog.getLogger().dLog(TAG," system.current Time: "+Utils.getFormatedTime(System.currentTimeMillis()) +" "+System.currentTimeMillis()); -// QLog.getLogger().dLog(TAG," location.getSpeed()==0 && app.lastPaused == 0"); -// QLog.getLogger().dLog(TAG," location.getTime(): "+Utils.getFormatedTime(location.getTime()) +" "+location.getTime()); - - // // // //// QLog.getLogger().dLog(TAG," "); - -// QLog.getLogger().dLog(TAG," ----------------------------------------------------------------------->isFirstwp "+isFirstwp ); -// QLog.getLogger().dLog(TAG," speed ==0 && app.lastPaused == 0" +(location.getSpeed()==0 && app.lastPaused == 0)); - }else if(location.hasSpeed() && location.getSpeed()>0 && app.lastPaused >0){ -// pausingTime = location.getTime() - app.lastPaused; - pausingTime = location.getTime() - app.lastPaused-QiYouConstant.MAX_GPS_SPAN; - pausingTime=pausingTime>0?pausingTime:0; - app.lastPaused =0; - app.sumPaused += pausingTime; -// if(app.sumPaused<=0)app.sumPaused=0; - -// // QLog.getLogger().dLog(TAG," location.getSpeed()>0 && app.lastPaused >0" +(location.getSpeed()>0 && app.lastPaused >0)); -// // // // //// QLog.getLogger().dLog(TAG," app.sumPaused Time: "+Utils.getFormatedTime(System.currentTimeMillis()) +" "+System.currentTimeMillis()); -// // QLog.getLogger().dLog(TAG," location.getTime(): "+Utils.getFormatedTime(location.getTime()) +" "+location.getTime()); - - // // // //// QLog.getLogger().dLog(TAG," "); - - - } - - -// // // // //// QLog.getLogger().dLog(TAG," system.current "+Utils.getFormatedTime(System.currentTimeMillis()) +" "+System.currentTimeMillis()); -// // // // //// QLog.getLogger().dLog(TAG," trackId "+ app.getRecordingTrack().getTrackBean().getTrackId() ); -// // // // //// QLog.getLogger().dLog(TAG," app.sumPause "+app.sumPaused ); -// // // // //// QLog.getLogger().dLog(TAG," track total pause time: "+ app.getRecordingTrack().getTrackBean().getPauseTime() ); -/* - if (app.lastPaused == 0) { - app.lastPaused = location.getTime(); - } - if (app.lastPaused > 0) { - pausingTime = location.getTime() - app.lastPaused; - if (location.getSpeed() == 0) - app.lastPaused = location.getTime(); - else - app.lastPaused = 0; - // if(isForceUpdate) - app.sumPaused += pausingTime; - if(app.sumPaused<=0)app.sumPaused=0; - // QLog.getLogger().d(TAG," app.sumPause "+app.sumPaused ); - // QLog.getLogger().d(TAG," track total pause time: "+ - // app.getRecordingTrack().getTrackBean().getPauseTime() ); - }*/ - } - } - - - if (isForceUpdate) { - // if(app.getLocationCached().size()==0)return; - preUpdatedb(false); - return; - } -// QLog.getLogger().dLog(TAG," Location is here 3 "); - sendToDb(location); - } - - - private void sendToDb(Location location) { - - - - -// QLog.getLogger().d(dTAG,TAG+ " gg Location processed, and send to track service for db."); - -// long MAX_TIME_UPDATE_DB = Utils.get_updatedb_invterval(trackType); - int MAX_WPS_UPDATE_DB = Utils.get_updatedb_cachsize(trackType); - - - - if( isFirstwp && app.sumDist>0 ){ - QLog.getLogger().dLog(TAG," isFirstwp && app.sumDist>0 "); - QLog.getLogger().dLog(TAG," app.sumDist ? " +app.sumDist ); -// app.initialTrackParameters(); - - } - -// QLog.getLogger().dLog(TAG," Location is here 5 "); - boolean isGoodWp = location.getSpeed() > 0 || isFirstwp; - - if (isGoodWp) // ||QiYouConstant.DEVELOPER_MODE) - { -// QLog.getLogger().dLog(TAG," ---------------------------input new location to app.getLocationCached()..........-------------- "); -// app.getLocationCached().put(app.getLocationCached().size() + 1, location); //TODO: review +1 - - - - Location lastLoc=app.getLocationCached().size()>0?app.getLocationCached().get(app.getLocationCached().size()-1):app.lastLocation; - - double dist = (isFirstwp?0:Utils.getDistance2(location,lastLoc)); - if(!isFirstwp && lastLoc!=null){ - float maxSpeed=location.getSpeed()>lastLoc.getSpeed()?location.getSpeed():lastLoc.getSpeed(); - float cdist=maxSpeed*(location.getTime()-lastLoc.getTime()); - /*if(dist>cdist){ - QLog.getLogger().dLog(TAG,"-------------------------- dist>cdist, dist is "+dist +",cdist is"+ cdist); - QLog.getLogger().dLog(TAG," location.getTime(): "+location.getTime() +",lastLoc.getTime():"+ lastLoc.getTime()); - QLog.getLogger().dLog(TAG,"maxSpeed : "+maxSpeed ); - }*/ - dist=dist>cdist?cdist:dist; - } - app.SpDist+=dist; - app.sumNavDist+=dist; - boolean isKmflag = app.SpDist > QiYouConstant.TRACK_SPLIT_DIST * 0.999;// || - - // app.SpDist>QiYouConstant.TRACK_SPLIT_DIST; - if (isKmflag) { - // QLog.getLogger().d(dTAG, - // TAG+"---- split dist meets target,sumdist is: ----"+ - // app.SpDist +","+ (app.sumDist + app.locDist)); - app.SpDist = 0; -// app.setCntKm(app.getCntKm() + 1); -// app.setCntKm((int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000)); - if(QiYouConstant.BL_SPEAK_KM){ - speakNewKm(); - } - app.timeKm=System.currentTimeMillis(); - } - - Bundle bd = new Bundle(); - bd.putDouble("dist", dist); - bd.putBoolean("iskm", isKmflag); - location.setExtras(bd); - if(app.canSendLocation2UI) - app.getRecordingTrack().getTrackBean().setDistance((float) (app.getRecordingTrack().getTrackBean().getDistance()+dist) ); - - - - - app.getLocationCached().put(app.getLocationCached().size(), location); -// QLog.getLogger().dLog(TAG," app.getLocationCached().size() - " +app.getLocationCached().size()); - app.getRecordingTrack().getTrackBean().setTopSpeed(location.getSpeed()*3.6f);// recording the top speed. - - if(app.GPS_SPAN_FACTOR>1){ - app.GPS_SPAN_FACTOR=1; - app.startAndroidGPSRequest(); - } - - } else if (app.getLocationCached().size() == 0) { - return; - } -// QLog.getLogger().dLog(TAG," Location is here 6 "); - // if( - // QiYouConstant.DEVELOPER_MODE)Log.e(dTAG,TAG+" "+"app.getLocationCached().size(): " - // +app.getLocationCached().size()); - // to judge if its the time for update db. - long last_update_db_request_time = app.getRecordingTrack() - .getTrackBean().getLastdbTime(); // if( - // QiYouConstant.DEVELOPER_MODE)Log.e(dTAG,TAG+" "+"last_update_db_request_time: " - // +l)ast_update_db_request_time); - boolean isUpdatedbTime = System.currentTimeMillis() - - last_update_db_request_time > MAX_TIME_UPDATE_DB; - - boolean canUpdateDb = app.getLocationCached().size() >= MAX_WPS_UPDATE_DB; // wp - // number - canUpdateDb = canUpdateDb || isFirstwp || isUpdatedbTime; // first wp, - // db time - // reach. - - -// QLog.getLogger().dLog(TAG," canUpdateDb - " +canUpdateDb); - // canUpdateDb = canUpdateDb && app.getLocationCached().size()>0; //wps - // not null. - - if (canUpdateDb)// ||QiYouConstant.DEVELOPER_MODE) //prepare for db - // updating - { - preUpdatedb(isFirstwp); - } - - // send out new location and pausing status... to calculate this pausing - // time - - } - - // final String KEY_Altitude ="ELE"; - // final String KEY_Adist ="ADIST"; - // final String KEY_Bearing ="Bear"; - // final String KEY_Dist ="Dist"; - float dist = 0f; - float bear = 0f; - boolean isBear; - boolean isSumbear; - boolean isKmflag; - float sumBear = 0; - float eleDist = QiYouConstant.MAX_ELE ; - float avBear = 0; - float avBear2 = 0; // direction. - float cTargetBear = 0; - boolean isPlayback ; - - void preUpdatedb(boolean isFirstwp) { - ArrayList newLocLst = new ArrayList(); - Location lastSavedLoc = null; - Location lastLoc = null; - Location currentLoc; - boolean isWpForDb = true; // wp is too close to last one, bearing is not - // changed much, then skip - boolean isTime = false; - boolean isDist = false; - - double sdist = 0; - - // float minDist=0; - int interval = isPlayback ? QiYouConstant.PLAYBACK_TIME_INTERVAL - : QiYouConstant.MAX_GPS_SPAN; - // int MIN_WPS_DISTANCE = QiYouConstant.MIN_WPS_DISTANCE_FACTOR ; - int MAX_WPS_EVERAGE_ELE_CNT = Utils - .get_updatedb_wpsElesumcnt(trackType); - // QLog.getLogger().d(dTAG,TAG+" "+" start prepare for db request, app.getLocationCached().size() " - // +app.getLocationCached().size()); -// float minDist = app.getRecordingTrack().getTrackBean().getAvs() -// * interval * QiYouConstant.MIN_WPS_DISTANCE_FACTOR; - - float minDist = app.getRecordingTrack().getTrackBean().getAvs()/3.6f - * interval/1000 * QiYouConstant.MIN_WPS_DISTANCE_FACTOR; - - if (app.minTime == 0) { - app.minTime = QiYouConstant.WPS_SAVE_PERCENT_FACTOR * interval; - - } -// QLog.getLogger().dLog(TAG," Location is here 7 "); - // QLog.getLogger().d(dTAG, - // TAG+" ---- -------app.getLocationCached().size()--- -------- "+app.getLocationCached().size()); - - - /*QLog.getLogger().dLog(TAG," begin to check locations in app.getLocationCached() ----------------->"); - QLog.getLogger().dLog(TAG," is first WP? " +isFirstwp); - QLog.getLogger().dLog(TAG," track start time:"+ Utils.getFormatedTime(app.getRecordingTrack().getTrackBean().getStartTime())+"," + app.getRecordingTrack().getTrackBean().getStartTime()); - QLog.getLogger().dLog(TAG," size of app.getLocationCached() :" +app.getLocationCached().size()); - for (int i = 0; i <= app.getLocationCached().size(); i++) { - QLog.getLogger().dLog(TAG," location " +i+1 ); - - Location loc = app.getLocationCached().get(i); - if(loc==null){ - QLog.getLogger().dLog(TAG," loc is null " ); - }else{ - QLog.getLogger().dLog(TAG," loc's time: " + Utils.getFormatedTime(loc.getTime()) +","+loc.getTime()); - } - - } - QLog.getLogger().dLog(TAG," <---------------- end of check locations in app.getLocationCached()");*/ - - int j = 0; - if (app.getLocationCached().size() > 0) { - currentLoc = app.getLocationCached().get(0);//currentLoc = app.getLocationCached().get(1); - - // if( lastLoc ==null ) lastLoc = currentLoc; - - if (lastSavedLoc == null) { - if (app.lastSavedLocation == null) { - app.lastSavedLocation = currentLoc; - } - lastSavedLoc = app.lastSavedLocation; - - } - if (app.lastLocation == null) - app.lastLocation = currentLoc; - // if(app.lastBearLoc==null)app.lastBearLoc=currentLoc; - } - - // check and mark the bearloc - // for (int i = 1; i <= app.getLocationCached().size(); i++) { - for (int i = 0; i <= app.getLocationCached().size()-1; i++) { - currentLoc = app.getLocationCached().get(i); - if (lastLoc == null) - lastLoc = currentLoc; - - if (app.cntBeared == 0 && !isBear) { - // app.sumBear+=currentLoc.getBearing();//>180?currentLoc.getBearing()-360:currentLoc.getBearing(); - app.sumBear += currentLoc.getBearing() > 180 ? currentLoc - .getBearing() - 360 : currentLoc.getBearing(); - app.sumBear2 += currentLoc.getBearing(); - app.cntBear++; - // app.sumBear2+=currentLoc.getBearing(); - // bearing since last location - avBear = app.sumBear / app.cntBear; - - cTargetBear =app.sumBear2 / app.cntBear; - - if (app.cntBear <= QiYouConstant.WPS_ROAD_BEAR_CNT && !QiYouConstant.BL_ONE_SHOT_BEAR) - continue; -// QLog.getLogger().d(dTAG, TAG+" avBear ,app.sumBear,app.cntBear is " +avBear +","+app.sumBear +","+app.cntBear); -// } -// -// if (app.cntBeared == 0) { // first time for bearing calculation. - - float abear = (currentLoc.getBearing() > 180 ? currentLoc - .getBearing() - 360 : currentLoc.getBearing()) - - (avBear > 180 ? avBear - 360 : avBear); - - if (Math.abs(abear) > QiYouConstant.WPS_ROAD_BEARING - && app.cntBear > QiYouConstant.WPS_ROAD_BEAR_CNT) { - bear = abear; - app.targetBear = avBear; - - - } else if (QiYouConstant.BL_ONE_SHOT_BEAR) { - float tbear = (currentLoc.getBearing() > 180 ? currentLoc - .getBearing() - 360 : currentLoc.getBearing()) - - (lastLoc.getBearing() > 180 ? lastLoc - .getBearing() - 360 : lastLoc.getBearing()); - if (Math.abs(tbear) > QiYouConstant.WPS_ROAD_BEARING) { - bear = tbear; - app.targetBear = currentLoc.getBearing() > 180 ? currentLoc - .getBearing() - 360 : currentLoc.getBearing(); - } - } else -// continue; - bear = 0; - - - } else if(app.targetBear !=-360){ - bear = (currentLoc.getBearing() > 180 ? currentLoc.getBearing() - 360 - : currentLoc.getBearing()) - - (app.targetBear > 180 ? app.targetBear - 360 - : app.targetBear); - } -// QLog.getLogger().d(dTAG, TAG+" bear,app.targetBear ,app.cntBeared" +bear +" , "+app.targetBear +"," +app.cntBeared); - // bear =Math.abs(tbear)>Math.abs(abear)?tbear:abear; - - // bear =currentLoc.getBearing() - app.targetBear ; - // sumBear+=Math.abs(bear); - sumBear += currentLoc.getBearing() - avBear; - // QLog.getLogger().d(dTAG, TAG+" bear,sumBear : "+bear +" , " +sumBear); - - // isBear = (app.cntBear > QiYouConstant.WPS_SAVE_PERCENT_FACTORE ) - // && h.abs(bear)>QiYouConstant.WPS_ROAD_BEARING ; - // isBear = app.cntBear> QiYouConstant.WPS_ROAD_BEAR_CNT && - // Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING ; - isBear = app.targetBear !=-360 - && Math.abs(bear) > QiYouConstant.WPS_ROAD_BEARING - && Math.abs(currentLoc.getBearing() - cTargetBear) > QiYouConstant.WPS_ROAD_BEARING - && Math.abs(currentLoc.getBearing() - app.targetBear) > QiYouConstant.WPS_ROAD_BEARING; - - - isSumbear = app.cntBear > QiYouConstant.WPS_ROAD_BEAR_CNT - && Math.abs(sumBear) > QiYouConstant.WPS_ROAD_BEARING - && (currentLoc.getTime() - app.lastSumbear > app.minTime); - - // isBear = isBear && (currentLoc.getTime() - - // app.lastBearLoc.getTime() > - // QiYouConstant.WPS_SAVE_PERCENT_FACTORE*1000); - // isBear = isBear && (app.cntBear > - // QiYouConstant.WPS_SAVE_PERCENT_FACTORE(Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING - // || Math.abs(sumBear)>2*QiYouConstant.WPS_ROAD_BEARING); - // isBear = app.cntBear > QiYouConstant.WPS_SAVE_PERCENT_FACTORE && - // Mat ); - if (isSumbear) { - app.lastSumbear = currentLoc.getTime(); - app.sumBearLocs.put(currentLoc.getTime(), currentLoc); - - } - - // if(isBear && app.cntBeared<= QiYouConstant.WPS_ROAD_BEAR_CNT){ - if (isBear) { - // QLog.getLogger().d(dTAG, - // TAG+" bear, currentLoc.getBearing(), avBear , app.cntBear : "+ - // bear +" , " + currentLoc.getBearing() +" , " + targetBear+ - // " , "+ app.cntBear); - - if (app.cntBeared == 0) { - app.lastBearLoc = currentLoc; - // app.targetBear =(lastLoc.getBearing()>180? - // lastLoc.getBearing()-360: lastLoc.getBearing()) > ( - // avBear>180? avBear-360: avBear) - // ?avBear:lastLoc.getBearing(); - // app.targetBear =lastLoc.getBearing(); - // app.targetBear =avBear; - // app.targetBear - // =Math.abs(tbear)>Math.abs(abear)?lastLoc.getBearing():avBear; - } - app.cntBeared++; - // app.sumBear2+=currentLoc.getBearing(); - // if(app.cntBeared>1) - // app.sumBear2+=currentLoc.getBearing();// - // >180?currentLoc.getBearing()-360:currentLoc.getBearing(); - isBear = isBear - && app.cntBeared > QiYouConstant.WPS_ROAD_BEAR_CNT; - if (!isBear) - continue; - - // QLog.getLogger().d(dTAG, - // TAG+" app.lastBearLoc.getTime() : "+app.lastBearLoc.getTime() - // ); - // QLog.getLogger().d(dTAG, TAG+"currentLoc.getBearing(), app.targetBear" - // +" , " +currentLoc.getBearing()+" , " + app.targetBear); - - // app.bearLocs.put( app.lastBearLoc.getTime(), new - // Float[]{app.targetBear,app.sumBear2/(app.cntBeared-1)} ); - -// app.bearLocs.put(app.lastBearLoc.getTime(), new Float[] { -// app.targetBear, currentLoc.getBearing() }); - - app.bearLocs.put( currentLoc.getTime(), new Float[] { - app.targetBear, currentLoc.getBearing() }); - - - if (getRoadTurnFlag2(currentLoc.getBearing(), app.targetBear) != getRoadTurnFlag2( - app.lastBearLoc.getBearing(), app.targetBear)) {// current - // loc'bear - // has a new - // turn -// QLog.getLogger().d(dTAG, TAG+"getRoadTurnFlag2(currentLoc.getBearing(), targetBear), getRoadTurnFlag2(app.lastBearLoc.getBearing(), targetBear)" +getRoadTurnFlag2(currentLoc.getBearing(), app.targetBear) + ","+ getRoadTurnFlag2(app.lastBearLoc.getBearing(), app.targetBear) ); -// QLog.getLogger().d(dTAG, TAG+ "getRoadTurnFlag2" +currentLoc.getTime()); - app.bearLocs.put(currentLoc.getTime(), new Float[] {app.targetBear,app.lastBearLoc.getBearing() }); - } - - // app.bearLocs.put( - // app.lastBearLoc.getTime(),app.sumBear2/app.cntBear ); - - app.lastBearLoc = null; - app.sumBear = 0; - // app.sumBear =app.sumBear2; - - app.cntBear = 0; - isBear = false; - bear = 0; -// i=i>app.cntBeared?i-app.cntBeared:1; - app.cntBeared = 0; - app.targetBear =-360; - app.sumBear2=0; - cTargetBear=0; - - } else if (app.cntBeared > 0) { - // }else { - // QLog.getLogger().d(dTAG, - // TAG+" app.getLocationCached().size(), i, app.cntBeared: "+app.getLocationCached().size()+" , "+ - // i +" , " + app.cntBeared ); - i = i > app.cntBeared ? i - app.cntBeared : 0; // i = i > app.cntBeared ? i - app.cntBeared : 1; - app.cntBeared = 0; - app.lastBearLoc = null; - app.sumBear =0; - // app.sumBear =app.sumBear2; - app.cntBear = 0; - bear = 0; - app.targetBear =-360; - app.sumBear2 = 0; - cTargetBear =0; - - } - lastLoc = currentLoc; - } -// QLog.getLogger().dLog(TAG," Location is here 8 "); - HashMap tmpMap = new HashMap(); -// QLog.getLogger().dLog(dTAG, " begin to check cached locations................................................."); - boolean isMaxProcessed =false; - for (int i = 0; i <= app.getLocationCached().size()-1; i++) { - -// QLog.getLogger().dLog(dTAG, "current location: " + (i+1) +" of " +(app.getLocationCached().size())); - - float lastAele = 0; // last average ele - float elesum = 0; - // float avSp =app.getRecordingTrack().getTrackBean().getAvs(); - // Log.e(dTAG,TAG+" "+ "current location: " + i +" of " - // +app.getLocationCached().size()); - currentLoc = app.getLocationCached().get(i); - - if (app.lastBearLoc != null - && !app.bearLocs.containsKey(app.lastBearLoc.getTime())) { - if (currentLoc.getTime() >= app.lastBearLoc.getTime()) { -// QLog.getLogger().d(dTAG, TAG + " Unfinished bearing judge, break the cache loop. i,size " + (i+1) + "," + (app.getLocationCached().size())); - -// tmpMap.put(tmpMap.size() + 1, currentLoc); - tmpMap.put(tmpMap.size() , currentLoc); - continue; - } - } - - if (app.sumOfftimeWp > 0 || isFirstwp - - // || app.lastPaused==0 &&(currentLoc.getTime()-lastLoc.getTime() - // >QiYouConstant.MAX_GPS_SPAN*QiYouConstant.GPS_CODE_START_WPS_CNT_SKIP)// - // offtime //TODO: RVIEW. - - ) { // GPS just warmup, skip first 5 wps ele data. - app.gpsStartTime = currentLoc.getTime();//TODO: remove. - app.skipCnt = QiYouConstant.GPS_CODE_START_WPS_CNT_SKIP; - // QLog.getLogger().d(dTAG, TAG+" GPS code start detected,next " + - // app.skipCnt +" wp will be skipped for ele calculation."); - } - - if (app.skipCnt == 0) { - app.getEles().add((float) currentLoc.getAltitude()); - } else { - // QLog.getLogger().d(dTAG, TAG+" wps left to skip ele cal is : "+ - // app.skipCnt); - app.skipCnt--; - - } - - // 记录关键点,丢弃一些距离密集点 - - // minDist = - // avSp*((currentLoc.getTime()-lastLoc.getTime()))*QiYouConstant.MIN_WPS_DISTANCE_FACTOR; - // distance since last saved location. - - isBear = app.bearLocs.containsKey(currentLoc.getTime()); - if (isBear) { - Float[] bears = app.bearLocs.get(currentLoc.getTime()); - if (bears != null) { - cTargetBear = bears[0]; - avBear2 = bears[1]; - } - -// QLog.getLogger().d(dTAG, TAG + " currentLoc.getTime(), targetBear is: " + currentLoc.getTime() + " , " + cTargetBear); - - } else - isSumbear = app.sumBearLocs.containsKey(currentLoc.getTime()); - // - /* if (!(isBear || isSumbear)) { - sdist = Utils.getDistance(currentLoc, lastSavedLoc); - isDist = sdist > minDist; - // QLog.getLogger().d(dTAG, TAG+" minDist,sdist : "+minDist +" , " +sdist); - // time since last saved location - isTime = app.minTime < currentLoc.getTime() - - lastSavedLoc.getTime(); - }*/ -// QLog.getLogger().dLog(TAG," Location is here 9 "); - // QLog.getLogger().d(dTAG, TAG+" Sumbear,bear"+sumBear +"," + bear+","+isBear); - - // QLog.getLogger().d(dTAG, TAG+" isDist,isTime : "+isDist +" , " +isTime); - - - - - if(app.lastSavedLocation==null ||app.lastSavedLocation.getTime()==0){ - app.lastSavedLocation=currentLoc; -// QLog.getLogger().dLog( TAG, " app.lastSavedLocation is null. "); - } -// long diff = currentLoc.getTime() - app.lastSavedLocation.getTime() ; - long diff = currentLoc.getTime() - app.lastLocation.getTime(); - - if( isMaxProcessed || diff <= MAX_TIME_UPDATE_DB){ - -// QLog.getLogger().dLog(dTAG," currentLoc time "+Utils.getFormatedTime(currentLoc.getTime())); -// QLog.getLogger().dLog(dTAG," app.lastSavedLocation time "+Utils.getFormatedTime(app.lastSavedLocation.getTime())); - - /*sdist = (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastLocation)); - - if(sdist -currentLoc.getExtras().getDouble("dist")!=0) - QLog.getLogger().dLog(dTAG," old dist - new dist: "+( sdist -currentLoc.getExtras().getDouble("dist"))); - */ - - sdist=currentLoc.getExtras().getDouble("dist"); - - - -// app.sumDiff+=sdist -Utils.getDistance(currentLoc, app.lastLocation) ; - - -// QLog.getLogger().dLog(dTAG," currentLoc time "+Utils.getFormatedTime(currentLoc.getTime())); -// QLog.getLogger().dLog(dTAG," app.lastLocation time "+Utils.getFormatedTime(app.lastSavedLocation.getTime())); - -// sdist = (float) (isFirstwp?0:Utils.getDistance(currentLoc, app.lastLocation)); -// sdist = (float) (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastSavedLocation)); -// app.sumDiff+=sdist -Utils.getDistance(currentLoc, app.lastSavedLocation) ; -// QLog.getLogger().dLog(dTAG," app.sumDiff "+app.sumDiff ); - }else{ - sdist=0; //系统暂停或失联gps后恢复,总距离不计入 - isMaxProcessed=true; -// QLog.getLogger().dLog(TAG,"Caution! -------------------------------------- 系统暂停或失联gps后恢复,总距离不计入 , MAX_TIME_UPDATE_DB is" +MAX_TIME_UPDATE_DB +" ,diff is" +diff ); - - } - -// sdist = Utils.getDistance(currentLoc, lastSavedLoc); - isDist = sdist > minDist; - // QLog.getLogger().d(dTAG, TAG+" minDist,sdist : "+minDist +" , " +sdist); - // time since last saved location - isTime = app.minTime < currentLoc.getTime() - - lastSavedLoc.getTime(); - - - - if (Math.round(app.sumDist) == 0 || Double.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - app.sumDist = app.getRecordingTrack().getTrackBean() - .getDistance(); - } - if (Math.round(app.sumDist) == 0 || Double.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { -// Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist); -// QLog.getLogger().dLog(TAG," Distance is NaN? app.sumDist: " + app.sumDist); - app.sumDist = 0; - } - - - app.sumDist += sdist; - app.getRecordingTrack().getTrackBean().setDistance((float) app.sumDist); //累加总里程, Meter - /* if(currentLoc.getExtras().containsKey("sumdist")){ - double testSumdist =currentLoc.getExtras().getDouble("sumdist"); - QLog.getLogger().dLog(dTAG," ------------------- currentLoc speed " +currentLoc.getSpeed()); - QLog.getLogger().dLog(TAG," ------------------- app.sumDist " +( app.sumDist )); - QLog.getLogger().dLog(TAG," ------------------- testSumdist: " +( testSumdist)); - QLog.getLogger().dLog(TAG," ------------------- delta sumdiff of app.sumDist - testSumdist: " +( app.sumDist - testSumdist)); - }*/ - - - // 几个点的平均海拔 - - // QLog.getLogger().d(dTAG, TAG+" split dist is: "+ app.SpDist); -// sdist = isFirstwp?0:Utils.getDistance(currentLoc, app.lastLocation); - app.bearDist += sdist; - // dist+=sdist; - app.locDist += sdist; -// app.SpDist += sdist;// (float) - // Utils.getDistanceFromXtoY(currentLoc.getLatitude(),currentLoc.getLongitude(),app.lastLocation.getLatitude(),app.lastLocation.getLongitude()); - - isKmflag=currentLoc.getExtras().getBoolean("iskm"); - /*isKmflag = app.SpDist > QiYouConstant.TRACK_SPLIT_DIST * 0.999;// || - - // app.SpDist>QiYouConstant.TRACK_SPLIT_DIST; - if (isKmflag) { - // QLog.getLogger().d(dTAG, - // TAG+"---- split dist meets target,sumdist is: ----"+ - // app.SpDist +","+ (app.sumDist + app.locDist)); - app.SpDist = 0; -// app.setCntKm(app.getCntKm() + 1); -// app.setCntKm((int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000)); - if(QiYouConstant.BL_SPEAK_KM){ - speakNewKm(); - } - app.timeKm=System.currentTimeMillis(); - - - - }*/ - isWpForDb = //isForceUpdate || - isDist - && isTime - || isKmflag - || isBear - || isSumbear - || isFirstwp - || currentLoc.getTime() - lastSavedLoc.getTime() > QiYouConstant.MAX_GEO_TIME / 2 - || currentLoc.getSpeed()*3.6f >= app.getRecordingTrack() - .getTrackBean().getTopSpeed() - || QiYouConstant.WPS_SAVE_ALL - ; - - - - /* if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - app.sumDist = app.getRecordingTrack().getTrackBean() - .getDistance(); - } - if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist); - QLog.getLogger().dLog(TAG," Distance is NaN? app.sumDist: " + app.sumDist); - app.sumDist = 0; - } - app.sumDist += sdist; - QLog.getLogger().dLog(dTAG, " app.sumDist "+app.sumDist );*/ - - -// QLog.getLogger().dLog(TAG," Location is here 10 "); - isWpForDb= isWpForDb &&!app.isRestoreLastTracking ; - - if(!isFirstwp && sdist==0) - isWpForDb =isWpForDb && app.getLocationCached().size()>1; //过滤偶尔出现的飘逸的卫星信号 - - isWpForDb=isWpForDb ||isCleanning && (i == app.getLocationCached().size()-1); - - if (isWpForDb) { - -// QLog.getLogger().dLog(dTAG," -------------------------it isWpForDb to save the wp for db "); - // dist = (float) - // Utils.getDistanceFromXtoY(currentLoc.getLatitude(),currentLoc.getLongitude(),lastLoc.getLatitude(),lastLoc.getLongitude()); - - - /*if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - app.sumDist = app.getRecordingTrack().getTrackBean() - .getDistance(); - } - if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist); - QLog.getLogger().dLog(TAG," Distance is NaN? app.sumDist: " + app.sumDist); - app.sumDist = 0; - } - - if(diff <= MAX_TIME_UPDATE_DB){ - QLog.getLogger().dLog(dTAG," currentLoc time "+Utils.getFormatedTime(currentLoc.getTime())); - QLog.getLogger().dLog(dTAG," app.lastSavedLocation time "+Utils.getFormatedTime(app.lastSavedLocation.getTime())); - - sdist = (float) (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastSavedLocation));//TODO : use double.....than float - app.sumDiff+=sdist -Utils.getDistance(currentLoc, app.lastSavedLocation) ; - } else{ - sdist=0; - QLog.getLogger().dLog(dTAG,"Caution 2! -------------------------------------- 系统暂停或失联gps后恢复,总距离不计入 , MAX_TIME_UPDATE_DB is" +MAX_TIME_UPDATE_DB +" ,diff is" +diff ); - - } - - app.sumDist += sdist; - - - QLog.getLogger().dLog(dTAG, " app.sumDist "+app.sumDist ); - */ - - - int s = app.getEles().size(); - if (s >= MAX_WPS_EVERAGE_ELE_CNT) { - StringBuffer sb = new StringBuffer(); - for (float e : app.getEles()) { - elesum += Math.round(e); - sb.append(e + ","); - - } - - lastAele = (float) (elesum / (s + 0.0)); - // QLog.getLogger().d(dTAG, TAG+" eles are: " + sb.toString()); - // QLog.getLogger().d(dTAG, TAG+" elesum,lastAele,s : "+ elesum+ " , "+ - // lastAele+" , "+s); - if (app.lastEle < QiYouConstant.MAX_ELE ) { - eleDist = lastAele - app.lastEle; - - float factor=(float) (sdist*QiYouConstant.ELED_FACTOR); - - eleDist= (float) (eleDist>0? - eleDist> factor?eleDist-factor :0 - : eleDist<-1*factor? eleDist - -1*factor:0); - } - - /*eleDist = (float) (eleDist>0? - eleDist> sdist*0.07f?eleDist-sdist*0.07f :0 - : eleDist<-1*sdist*0.07f? eleDist - -1*sdist*0.07:0); */ - - - - app.lastEle = lastAele; - app.eles.clear(); - elesum = 0; - - if(app.getRecordingTrack().getTrackBean().getTrackId()>0 - && app.startTime > app.getRecordingTrack().getTrackBean().getLastdbTime()){ - app.maxEle= app.maxEle app.getRecordingTrack().getTrackBean().getUpDist()? - app.upDist :app.getRecordingTrack().getTrackBean().getUpDist(); - app.downDist = app.downDist>app.getRecordingTrack().getTrackBean().getDownDist()? - app.downDist:app.getRecordingTrack().getTrackBean().getDownDist(); - } - - app.maxEle=app.maxElelastAele?lastAele:app.minEle;; - app.upDist+=eleDist>0?sdist:0; - app.downDist+=eleDist<0?sdist:0; - - } - - /* if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - app.sumDist = app.getRecordingTrack().getTrackBean() - .getDistance(); - } - if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist); - app.sumDist = 0; - } - app.sumDist += app.locDist;*/ - String wpJson=getLocationChanges(currentLoc); - if(!TextUtils.isEmpty(wpJson)); - newLocLst.add(wpJson); // put the - // current loc - // in the cache - // for update - - if (eleDist != QiYouConstant.MAX_ELE ) { - eleDist = QiYouConstant.MAX_ELE ; - } - // - // if(isBear){ - // app.sumBear =0; - // app.cntBear=0; - // app.cntBeared=0; - // } - // - if (isBear) - // if( Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING) - { - app.bearLocs.remove(currentLoc.getTime()); - app.bearDist = 0; - // app.minTime = QiYouConstant.WPS_SAVE_PERCENT_FACTORE - // *interval; - app.minTime = interval; - minDist = 0; - } else { - if (app.minTime < QiYouConstant.MAX_GEO_TIME / 2) - app.minTime += 2 * interval; // 直线行驶状态下,递减wp个数 - minDist = app.getRecordingTrack().getTrackBean().getAvs() - * interval * QiYouConstant.MIN_WPS_DISTANCE_FACTOR; - } - - if (isSumbear) { - app.sumBearLocs.remove(currentLoc.getTime()); - } - - // QLog.getLogger().d(dTAG, TAG+" minTime, location timeDiff,isBear "+ - // app.minTime +", "+ - // (currentLoc.getTime()-lastSavedLoc.getTime()) +" , "+isBear); - app.locDist = 0; - dist = 0; - // bear=0; - // sumBear =isBear?0:sumBear; - sumBear = 0; - isDist = false; - isSumbear = false; - isTime = false; - app.sumPaused = 0; - // app.offtime =0; - app.sumOfftimeWp = 0; - // if(!isPlayback) - app.lastSavedLocation = currentLoc; - lastSavedLoc = currentLoc; - j++; - - // Log.e(dTAG,TAG+" "+ "to be updated..."); - } -// QLog.getLogger().dLog(TAG," Location is here 11 "); - app.lastLocation = currentLoc; - } - -// if(!isPlayback ||isPlayback && QiYouConstant.PLAYBACK_CAN_RECORD) - if (app.playBack && QiYouConstant.PLAYBACK_CAN_RECORD || app.isLastTrackExist() &&(isForceUpdate || newLocLst.size() > 0)) { // to update db - - /*if (app.getLocationCached().size() > 0){ - QLog.getLogger().dLog(dTAG, " ..." + j + " of "+ app.getLocationCached().size() + ", wps keeped: " + j* 100 / (app.getLocationCached().size()) + "%"); - }*/ - - Intent locIntent = new Intent(QiYouConstant.ACTION_NEW_WAYPOINTS_TO_SAVE); - if (newLocLst.size() > 0) - locIntent.putExtra(QiYouConstant.NEW_LOCATION, newLocLst); - else if (isForceUpdate) {// only force update the db when there is - // no new waypoint in - locIntent.putExtra(QiYouConstant.EXTRA_KEY_FORCE_UPDATE,isForceUpdate); -// QLog.getLogger().d(dTAG, TAG + " Force update to db broadcast."); - - } - sendBroadcast(locIntent); - - - newLocLst.clear(); - app.setlastLocation( app.lastLocation );// persist the last location. - /*if(isFirstwp){ - if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2) - app.speech("卫星定位成功,记录开始",0); - }*/ - - - - sendShareLocation(); - - - } - - - // to remove the items in the location cache. - app.getLocationCached().clear(); -// QLog.getLogger().dLog(TAG," ---------------------------app.getLocationCached().clear()..........-------------- "); - if (app.lastBearLoc != null - && !app.bearLocs.containsKey(app.lastBearLoc.getTime())) {// location - // cache - // dosn't - // match - // isBear - // condition. -// QLog.getLogger().dLog(dTAG, TAG -// + " The location cache dosn't contain enough points for bear judge,keep some locaitons in the cach for new comming ones."); - // for(Iterator iterator = - // app.getLocationCached().values().iterator();iterator.hasNext();){ - // Location loc =iterator.next(); - // if(loc.getTime()< app.lastBearLoc.getTime()){ - // iterator.remove(); - // - // } - // } - - app.getLocationCached().putAll(tmpMap); -// QLog.getLogger().dLog(dTAG, "locations put in next loop: " + tmpMap.size()); - - } -// QLog.getLogger().dLog(TAG," Location is here 13 "); - } - - private String getLocationChanges(Location currentLoc) { - // int MAX_WPS_EVERAGE_ELE_CNT = - // Utils.get_updatedb_wpsElesumcnt(trackType) ; -// Bundle bd = currentLoc.getExtras();// lastloc.getExtras(); -// long pause = bd.getLong(KEY_PAUSETIME) + app.sumPaused; -// long pause = app.sumPaused>QiYouConstant.MAX_GPS_SPAN*1? app.sumPaused:0; - long pause = 0; //app.sumPaused; - // long offtime = bd.getLong(KEY_OFFTIME)+app.sumOfftimeWp; - - long sportTime = app.getRecordingTrack().getTrackBean().getSportTime(); // current - // sport - // time - // of - // track; - - /*if (app.getRecordingTrack().getTrackBean().getEndTime() > 0) { - long nt = currentLoc.getTime() - - app.getRecordingTrack().getTrackBean().getEndTime() - pause - - app.sumOfftimeWp; - nt = nt > 0 ? nt : 0; - if(nt==0)return null; - sportTime += nt; - }*/ - - -// app.lastLocationTime =app.lastLocation!=null?app.lastLocation.getTime():app.lastLocationTime; - - - - long diff = currentLoc.getTime() - app.lastSavedLocation.getTime() ; - long nt =0; - if(diff <= MAX_TIME_UPDATE_DB){ - if(app.locDist>0 && app.sumPaused>0){ - - long calPausetime =(long) (diff - 1000*app.locDist/( (app.lastSavedLocation.getSpeed() + currentLoc.getSpeed())/2.0000) - app.sumOfftimeWp) ; - pause = calPausetime>0?calPausetime:0; -// QLog.getLogger().dLog( TAG, " app.locDist>0 && app.sumPaused>0, calPausetime:"+calPausetime +", app.sumPaused" + app.sumPaused); - /* QLog.getLogger().dLog( TAG, " pause is " +pause); - QLog.getLogger().dLog( TAG, String.format(" last saved speed is%s ,current speed is%s",app.lastSavedLocation.getSpeed(),currentLoc.getSpeed()));*/ - - } - - nt = diff - pause - app.sumOfftimeWp; -// nt = diff - app.sumPaused - app.sumOfftimeWp;//TODO: valid the change for sport time calculation. - nt = nt > 0 ? nt : 0; - - }else{// 和上次位置时间间隔 比较大,应为离线或静止状态,计入静止时间 - - /* pause=diff - app.sumOfftimeWp; - nt =0;*/ - pause=diff -MAX_TIME_UPDATE_DB - app.sumOfftimeWp; - nt =MAX_TIME_UPDATE_DB; - /*QLog.getLogger().dLog( TAG, " diff > MAX_TIME_UPDATE_DB, diff:"+diff +","+ Utils.getTimeCnt(diff) +",MAX_TIME_UPDATE_DB is "+ MAX_TIME_UPDATE_DB +", app.sumPaused " + app.sumPaused); - QLog.getLogger().dLog( TAG, " pause is " +pause);*/ - - - if(app.sumOfftimeWp==0){ - //TODO: dist should be 0, sumdist ,app.cntKm,kmdist should not grow; - - } - - } - nt=nt>diff?diff:nt; - sportTime += nt; - - if(isPlayback) - sportTime = sportTime*QiYouConstant.MAX_GPS_SPAN/QiYouConstant.PLAYBACK_TIME_INTERVAL; - -// QLog.getLogger().dLog( TAG, " sportTime is " +sportTime); - -/* if ( app.lastSavedLocation!=null && app.lastSavedLocation.getTime() > 0 ) { - - long diff = currentLoc.getTime() - app.lastSavedLocation.getTime() ; - - if(diff > MAX_TIME_UPDATE_DB){ - pause =diff -app.sumOfftimeWp; - - }else if(app.locDist>0 && pause>0){ - - long avsptime =(long) (diff - 1000*app.locDist/( (app.lastSavedLocation.getSpeed() + currentLoc.getSpeed())/2.000) - app.sumOfftimeWp) ; - pause = avsptime>0? - pause>(diff - avsptime)?(diff - avsptime):pause - :0; - - long calPausetime =(long) (diff - 1000*app.locDist/( (app.lastSavedLocation.getSpeed() + currentLoc.getSpeed())/2.0000) - app.sumOfftimeWp) ; - pause = calPausetime>0?calPausetime:0; - } - - - long nt = diff - pause - app.sumOfftimeWp; - nt = nt > 0 ? nt : 0; - sportTime += nt; -// if(pause>0){ -// // // // //// QLog.getLogger().dLog( TAG, " currentLoc.getTime()- app.lastSavedLocation.getTime(): " -// + (currentLoc.getTime()- app.lastSavedLocation.getTime())); -// // // // //// QLog.getLogger().dLog(TAG, " delta sporttime is: " + nt); -// // // // //// QLog.getLogger().dLog(TAG, " pause is: " + pause); -// } - }*/ - - -// app.sumSpeed+= currentLoc.getSpeed(); -// app.spdCnt++; - - app.getRecordingTrack().getTrackBean().setSportTime(sportTime); - -// QLog.getLogger().d(dTAG, TAG + " app.lastLocationTime: " + app.lastLocationTime); -// QLog.getLogger().d(dTAG, TAG + " sportTime: " +sportTime); - -// QLog.getLogger().d(dTAG, TAG + " app.recordingTrack.getTrackBean().getSportTime(): " +app.recordingTrack.getTrackBean().getSportTime()); - StringBuffer sb = new StringBuffer(); - sb.append("{"); - - // sb.append("\"lastlat\":" +lastloc.getLatitude()); - // sb.append(",\"lastlon\":"+lastloc.getLongitude()+","); - - sb.append("\"latitude\":" + currentLoc.getLatitude()); - sb.append(",\"longitude\":" + currentLoc.getLongitude()); - sb.append(",\"bearDist\":" + String.format("%.2f", app.bearDist)); - if (isBear) { - // if( Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING) - // { - // float bear =bd.getFloat(KEY_Bearing); - // sb.append(",\"roadBear\":"+ avBear); - // sb.append(",\"turnFlag\":"+ - // getRoadTurnFlag2(currentLoc.getBearing(), targetBear)); - sb.append(",\"turnFlag\":" + getRoadTurnFlag2(avBear2, cTargetBear)); - - sb.append(",\"targetBear\":" +String.format("%.2f", cTargetBear) ); - // } - sb.append(",\"bearing\":" + String.format("%.2f", avBear2)); - sb.append(",\"cbearing\":" + String.format("%.2f", currentLoc.getBearing())); - } else - sb.append(",\"bearing\":" + String.format("%.2f", currentLoc.getBearing())); - - if (isSumbear) { - sb.append(",\"sumBear\":" + sumBear); -// sb.append(",\"roadB\":" + bear); - - } - - sb.append(",\"accuracy\":" + String.format("%.2f", currentLoc.getAccuracy())); - // sb.append(",\"blat\":" +Utils.getbdLat(currentLoc.getLatitude(), - // currentLoc.getLongitude())); - // sb.append(",\"blon\":"+Utils.getbdLon(currentLoc.getLatitude(), - // currentLoc.getLongitude())); - // if(lastAele !=100000 || QiYouConstant.DEVELOPER_MODE) - // sb.append(",\"ele\":"+currentLoc.getAltitude()*1.0); -// sb.append(",\"cele\":" + currentLoc.getAltitude() * 1.0); // 取连续点的平均海拔值 - if (!Float.isNaN(app.lastEle) && app.lastEle < QiYouConstant.MAX_ELE ) - sb.append(",\"elevation\":" + String.format("%.2f", app.lastEle)); - // else - // sb.append(",\"ele\":"+ currentLoc.getAltitude()*1.0); - // if(null !=bd && bd.containsKey(KEY_Adist)){ - // float eleDist =bd.getFloat(KEY_Adist); - // // float cele = bd.getFloat(KEY_Altitude); - // - // sb.append(",\"eled\":"+ eleDist*1.00 ); - // } - - if (eleDist < QiYouConstant.MAX_ELE && !Float.isNaN(app.lastEle)) { - sb.append(",\"eled\":" +String.format("%.2f", eleDist) ); - } - sb.append(",\"upDist\":" + String.format("%.2f", app.upDist) ); - sb.append(",\"downDist\":" + String.format("%.2f", app.downDist) ); - if( app.maxEle >-1000) - sb.append(",\"maxEle\":" + String.format("%.2f", app.maxEle) ); - if(app.minEle < QiYouConstant.MAX_ELE) - sb.append(",\"minEle\":" + String.format("%.2f", app.minEle) ); - - - if (isKmflag) { - - sb.append(",\"kmflag\":" + app.getCntKm()); - } - // sb.append(",\"time\":"+Utils.getUTC(bloc.getTime())); - sb.append(",\"time\":" + currentLoc.getTime()); - sb.append(",\"readabletime\": \"" - + Utils.getFormatedTime(currentLoc.getTime()) + "\""); - sb.append(",\"sportTime\":" + sportTime); - sb.append(",\"distance\":" + String.format("%.2f", app.locDist)); - // sb.append(",\"odist\":"+ odist ); - // sb.append(",\"cspdist\":"+ cspdist ); - sb.append(",\"sumDist\":" + String.format("%.2f", app.sumDist)); - - if (pause > 0) - sb.append(",\"pauseTime\":" + pause); - - // offtime =app.sumOfftimeWp; - - - if (app.sumOfftimeWp > 0) - { - sb.append(",\"offTime\":" + app.sumOfftimeWp); - } - - // if(bloc.getSpeed()>0) - sb.append(",\"speed\":" + String.format("%.2f", currentLoc.getSpeed() * 3.6f)); - sb.append("}"); - - // Log.e(dTAG,TAG+" "+sb.toString()); - return sb.toString(); - - } - - int getRoadTurnFlag(float cBear, float target) { - int flag = 0; - // boolean turnR=false; - boolean turnR = false; - if (target >= 180) { - turnR = cBear < target - 180 || cBear > target; - } else { - // turnR =cBear>target +180 || cBear target; - } - - flag = turnR ? 1 : -1; - - // if(Math.abs((cBear>180?cBear-360:cBear) -target)>160) flag=2; //折返 - - return flag; - } - - wpFlag getRoadTurnFlag2(float cBear, float target) { - int flag = 0; - cBear = cBear > 180 ? cBear - 360 : cBear; - target = target > 180 ? target - 360 : target; - // boolean turnR=false; - boolean turnR = false; - if (target >= 0) { - turnR = cBear < target - 180 || cBear > target; - } else { - // turnR =cBear>target +180 || cBear target; - } - - flag = turnR ? 1 : -1; - - // if(Math.abs((cBear>180?cBear-360:cBear) -target)>160) flag=2; //折返 - - return wpFlag.valueOf(flag); - } - - private void speakNewKm(){ - - if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL==2)return; - long timeUsed=System.currentTimeMillis() -app.timeKm; - if(timeUsed/1000/60<1)return; - long totalTime=app.getRecordingTrack().getTrackBean().getTotalTime()>timeUsed?app.getRecordingTrack().getTrackBean().getTotalTime():timeUsed; - String total =QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL==1? //STANDARD - String.format("您已运动%s公里,共用时%s,平均速度%.2f公里每小时,最高速度%.2f公里每小时,消耗热量%.2f卡路里,过去的一公里用时%s,加油", - app.getCntKm(), - // (int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000), - Utils.getTimeCnt4Read(totalTime,true), - app.getRecordingTrack().getTrackBean().getAvs(), - app.getRecordingTrack().getTrackBean().getTopSpeed(), - app.getRecordingTrack().getCalBurn(), - Utils.getTimeCnt4Read(timeUsed,true) - ) - : //SIMPLE - String.format("过去的一公里用时%s,您已运动%s公里,共用时%s", - Utils.getTimeCnt4Read(timeUsed,true), - app.getCntKm(), -// - Utils.getTimeCnt4Read(totalTime,true) - ); - - - -// String lastKm=String.format("过去的一公里用时%s", -// Utils.getTimeCnt4Read(System.currentTimeMillis() -app.timeKm,true) -// ); -// -// app.speech(lastKm); -// QLog.getLogger().dLog(TAG, -// String.format("track distance is:%.3f,app。cntKm :%s", -// app.getRecordingTrack().getTrackBean().getDistance(),app.cntKm)); - app.speech(total,0); - } - - - - - - - void sendShareLocation(){ - QLog.getLogger().dLog(TAG," begin to send shared location... "); - if(!QiYouConstant.PV_BL_SHARE_LOCATION || !Utils.isNetworkConnected(app))return; - long shareInterVal = QiYouConstant.DEVELOPER_MODE ? QiYouConstant.PV_INT_LIVE_SPAN /10 : QiYouConstant.PV_INT_LIVE_SPAN; - if(System.currentTimeMillis() - app.lastSharedTime > shareInterVal){ - app.sendSharedLocation(); - } - - - } - - - - - - - - - - - - @Override - public void onDestroy() { - - // Log.i(TAG,"Services onDestory"); - - // // isStop=true;//即使service销毁线程也不会停止,所以这里通过设置isStop来停止线程 - // QLog.getLogger().d(TAG," save app.sumPaused "+app.sumPaused ); - // QLog.getLogger().d(TAG," save app.sumOfftime: "+app.sumOfftime ); - // QLog.getLogger().d(TAG,"---------app.sumPause loop----------------------------" ); -// app.saveLocationParameters(false); - super.onDestroy(); - - } - - /*@Override - public IBinder onBind(Intent intent) { - // TODO Auto-generated method stub - return null; - } -*/ - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/LocationService2.java b/qy/src/main/java/com/qiyou/mb/android/service/LocationService2.java deleted file mode 100644 index 11b2bd3..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/LocationService2.java +++ /dev/null @@ -1,284 +0,0 @@ -package com.qiyou.mb.android.service; - -import java.io.UnsupportedEncodingException; - -import org.apache.http.Header; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHeader; -import org.apache.http.protocol.HTTP; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.app.Service; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Intent; -import android.net.Uri; -import android.os.IBinder; -import android.util.Log; - -import com.loopj.android.http.JsonHttpResponseHandler; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.receivers.TimeTickReceiver; -import com.qiyou.mb.android.ui.Welcome; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; -import com.qiyou.mb.android.utils.server.SharedLocation; - -public class LocationService2 extends Service { - public static String TAG ="com.qiyou.LocationService2"; - public static final String dTAG ="com.qiyou"; -// public DBserviceNew(String name) { -// super(name); -// // TODO Auto-generated constructor stub -// } - - - @Override - public void onStart(Intent intent, int startId) { - QLog.getLogger().d(dTAG,TAG+"... service LocationService2 onStart.....," ); - if(intent!=null) - handleIntent(intent); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId){ - QLog.getLogger().d(dTAG,TAG+"... service LocationService2 onStartCommand.....," ); - handleIntent(intent); - // We want this service to continue running until it is explicitly - // stopped, so return sticky. - return START_STICKY; - } - protected void handleIntent(Intent intent){ - - //to check if the application restart with new instances or not - // The check result is, the new application instance created, the original referenced application still exits. - - //TODO: to find what cause creating new application instances? - -// String debugstring="Time Tick regist at: "+ registTime+ ", Application instance start time is:" + app.startTime +",Time past:"+( app.startTime -registTime); -// QLog.getLogger().d(dTAG,TAG+ debugstring); -// Utils.logStackTrace(new Exception(debugstring),dTAG); - - - - if(intent==null)return; - - String key = QiYouConstant.EXTRA_KEY_UPLOAD_SHARED_LOCATION; - if (intent.hasExtra(key)){ - - sendSharedLocation(); -// postJsonWS() - - return; - } - } - - - protected QiYouApplication app; - - - @Override - public void onCreate() { - super.onCreate(); - app =(QiYouApplication)this.getApplication(); - } - - - - void sendSharedLocation(){ - - if(app.lastLocation ==null){ - return; - } - - - SharedLocation sl = new SharedLocation(); - sl.setBear(app.lastLocation.getBearing()); - sl.setLat(app.lastLocation.getLatitude()); - sl.setLon(app.lastLocation.getLongitude()); - sl.setSpeed(app.lastLocation.getSpeed()); - sl.setEle((float) (app.lastLocation.getAltitude())); -// sl.setTime(app.lastLocation.getTime()); //to use server time - sl.setId(app.user.getUserbean().getId()); - sl.setName(app.user.getUserbean().getUserName()/*.getAccount()*/); - sl.setExpired( QiYouConstant.PV_INT_LIVE_TERM); - sl.setDist((float) app.sumDist); - sl.setType(0); - sl.setFace(0); - sl.setMsg(QiYouConstant.PV_STR_SHARE_MSG); - - - QLog.getLogger().d(dTAG, TAG+" begin to post shared location.............."); - - postJsonWS(Utils.getGsonString(sl),RestMethods.LIVE_P_SHARE_LOCATION); - - - - - - } - - - int failureCnt=0; - - void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{ - failureCnt =0; -// if(jsonObject==null)return; - - if(method.equalsIgnoreCase(RestMethods.LIVE_P_SHARE_LOCATION)){ - app.lastSharedTime=System.currentTimeMillis(); - QLog.getLogger().d(dTAG, TAG+" shared success! app.lastSharedTime " + app.lastSharedTime); - } - - } - - void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){ - QLog.getLogger().d(dTAG, TAG+" shared failure!"); - failureCnt++; - if(failureCnt<=3){ - QLog.getLogger().d(dTAG, TAG+" shared failure,tring count 1....."); - sendSharedLocation(); - } - } - - - - - - - - - - - - - - - - - void postJsonWS(String json,String url) { - if(!Utils.isNetworkConnected(this)){ - return; - } -// setCookie(); - - QLog.getLogger().d(dTAG, TAG+" post json is "+json); - // Show Progress Dialog - - - // Make RESTful webservice call using AsyncHttpClient object -// testCookies(); - StringEntity entity =null; - try { - entity = new StringEntity(json,HTTP.UTF_8); - } catch (UnsupportedEncodingException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - if(entity==null)return; - - entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); - -// QiyouRestClient.post(activity,url, entity,"application/json", - QiYouApplication.post( app,url, entity,"application/json", - new JsonHttpResponseHandler(){ - @Override - public void onSuccess(int statusCode, org.apache.http.Header[] headers, JSONObject response){ - - if (response != null) { - try { -// JSONObject jsonObject= response.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ; - JSONObject jsonObject= null; - try { - jsonObject= response.getJSONObject(QiYouConstant.JSONOBJECT_KEY); - - } catch (JSONException e) { - - } - String method =response.has(QiYouConstant.SIGN_KEY)?response.getString(QiYouConstant.SIGN_KEY):""; - String msg=response.getString(QiYouConstant.MSG_KEY); - processJsonObject(method, jsonObject,msg); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - - } - } - - - - String msg = ""; - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { - // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONObject) was received"); - - try { -// JSONObject jsonObject= errorResponse.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ; -// String method =jsonObject.has(QiYouConstant.SIGN_KEY)?jsonObject.getString(QiYouConstant.SIGN_KEY):""; -// String msg=errorResponse.getString(QiYouConstant.MSG_KEY); - msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - asynClientOnFailure(statusCode,msg,headers); - } - - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { - // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONArray) was received" ); - asynClientOnFailure(statusCode,msg,headers); - } - - - - @Override - public void onFailure(int statusCode, org.apache.http.Header[] headers, String errorResponse, java.lang.Throwable throwable ) { - QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], String, Throwable) was received" ); - QLog.getLogger().d(dTAG, TAG+"errorResponse: "+errorResponse); - asynClientOnFailure(statusCode,msg,headers); - } - @Override - public void onProgress(int bytesWritten, int totalSize) { - - } - }); - - - } - - - - - - @Override - public void onDestroy() { - super.onDestroy(); - } - - @Override - public IBinder onBind(Intent intent) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/LogService.java b/qy/src/main/java/com/qiyou/mb/android/service/LogService.java deleted file mode 100644 index 7655c9f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/LogService.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.qiyou.mb.android.service; - - import java.io.EOFException; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.log.QLog; - -import android.app.IntentService; -import android.content.Intent; -import android.os.Environment; - -public class LogService extends IntentService { -public static String TAG="com.qiyou.mb.android.service.LOGSERVICE"; - public LogService(String name) { - super(name); - // TODO Auto-generated constructor stub - } - public LogService() { - super(TAG); - // TODO Auto-generated constructor stub - } - String shell = "logcat | grep com.qiyou"; - @Override - protected void onHandleIntent(Intent intent) { - // TODO Auto-generated method stub - if(intent.getExtras()!=null) - shell = intent.getExtras().get(QiYouConstant.EXTRA_KEY_LOG_SHELL).toString(); - } - public void exportLog() - { -// String shell = "logcat | grep ^E.com.qiyou.mb.android"; - - - try - { - Process process = Runtime.getRuntime().exec(shell); - InputStream inputStream = process.getInputStream(); - - - boolean sdCardExist = Environment.getExternalStorageState().equals( - android.os.Environment.MEDIA_MOUNTED); - File dir = null; - if (sdCardExist) - { -// dir = new File(Environment.getExternalStorageDirectory().toString() -// + File.separator + "logcat-qiyou"+System.currentTimeMillis()+".txt"); - dir = new File("/sdcard/"+"logcat-qiyou"+System.currentTimeMillis()+".log");// 创建目录 - if (!dir.exists()) - { - dir.createNewFile(); - QLog.getLogger().d(TAG, String.format("LOGCAT file %s created",dir) ); - } - - } - byte[] buffer = new byte[1024]; - int bytesLeft = 5 * 1024 * 1024; // Or whatever - try - { - FileOutputStream fos = new FileOutputStream(dir); - try - { - while (bytesLeft > 0) - { - int read = inputStream.read(buffer, 0, Math.min(bytesLeft, - buffer.length)); - if (read == -1) - { - throw new EOFException("Unexpected end of data"); - } - fos.write(buffer, 0, read); - bytesLeft -= read; -// QLog.getLogger().d(TAG, String.format("LOGCAT file %s content write",read) ); - } - } finally - { - fos.close(); // Or use Guava's - // Closeables.closeQuietly, - // or try-with-resources in Java 7 - } - } finally - { - inputStream.close(); - } -// String logcat = convertStreamToString(inputStream); -// outputFile2SdTest(logcat, "logwyx.txt"); - QLog.getLogger().d(TAG, "LOGCAT = ok" ); - } catch (IOException e) - { - e.printStackTrace(); - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/OfflineMapService.java b/qy/src/main/java/com/qiyou/mb/android/service/OfflineMapService.java deleted file mode 100644 index d54b3d8..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/OfflineMapService.java +++ /dev/null @@ -1,339 +0,0 @@ -package com.qiyou.mb.android.service; - -import java.util.ArrayList; - -import android.app.IntentService; -import android.content.Intent; -import android.location.Location; -import android.util.Log; -//import com.baidu.mapapi.map.MKOLSearchRecord; -//import com.baidu.mapapi.map.MKOLUpdateElement; -//import com.baidu.mapapi.map.MKOfflineMap; -//import com.baidu.mapapi.map.MKOfflineMapListener; -//import com.baidu.mapapi.map.MapController; -import com.baidu.mapapi.map.MapView; -import com.baidu.mapapi.map.offline.MKOLSearchRecord; -import com.baidu.mapapi.map.offline.MKOLUpdateElement; -import com.baidu.mapapi.map.offline.MKOfflineMap; -import com.baidu.mapapi.map.offline.MKOfflineMapListener; -import com.google.gson.Gson; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -public class OfflineMapService extends IntentService { -// public class OfflineMapService extends IntentService implements MKOfflineMapListener { - public static String TAG ="com.qiyou.OfflineMapService"; - public static String dTAG ="com.qiyou"; - -// private MapView mMapView = null; - private MKOfflineMap mOffline = null; -// private MapController mMapController = null; - protected QiYouApplication app; - int ratio=0; - private ArrayListlocalMapList =null; - int tryTimes=0; - public OfflineMapService() - { - super(TAG); - } - - @Override - public void onCreate() { - super.onCreate(); - app = (QiYouApplication) this.getApplication(); - initialOffMap(); - } - - - public OfflineMapService(String name) { - super(name); - // TODO Auto-generated constructor stub - } - String cityName; - @Override - protected void onHandleIntent(Intent intent) { - - - QLog.getLogger().d(dTAG, TAG+ " offmap update...Network location OfflineMap service get intent..."); -// if(mMapView==null) return; - importFromSDCard(); //scan the latest baiduSDK path - -// if(app.isOfflimeMapWorking) return; -// -// if(!app.isNetworkLocationRequestStarted) { -// app.startNetworkLocationRequest(); -// return; -// } -// app.isOfflimeMapWorking =true; - - /* - String key; - Location loc=null; - Bundle extras = intent.getExtras(); - if(extras!=null){ - key = LocationManager.KEY_LOCATION_CHANGED; - loc = (Location) extras.get(key); - } - if(loc==null) loc = app.lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); - if(loc!=null) - { - app.stopNetworkLocationRequest(); - String cityName =getCityName(loc); -// cityName ="苏州"; - int cityId =search(cityName ); - -// if(cityId>0 && needDownload(cityId)) -// downloadCityMap(cityId); - DownloadOffmap(cityId); - - - }*/ - int cityId =-1; - String key = QiYouConstant.EXTRA_KEY_OFFMAP; - String Gstring = intent.getExtras().getString(key); - if(Gstring!=null){ - Gson gson = new Gson(); - GEOaddress go=null ; - try{ - go = gson.fromJson(Gstring, GEOaddress.class); - - }catch(Exception e) - { - Log.e(dTAG,TAG+" fromJson error: "+Gstring); - Utils.logStackTrace(e, dTAG); - - } - - if(go!=null && go.getCityId()!=null){ - cityId =Integer.valueOf( go.getCityId()); - cityName=go.getCity(); - QLog.getLogger().d(dTAG, String.format(" offmap update... %s trying check the current city offline map: %s",TAG,cityName)); - } - - } - - DownloadOffmap(cityId); - - app.setlastOffMapRequestTime(); - } - - - void DownloadOffmap(int cityId){ -// MKOLUpdateElement e - boolean rt = true; - if(localMapList ==null){ - QLog.getLogger().d(dTAG, TAG+" No offlineMap downloaded before."); - }else - for(MKOLUpdateElement e: localMapList){ - - if(e.update){ - ratio =0; -// mOffline.remove(cityId); - downloadCityMap(e.cityID,e.cityName); - } - -// }else if(e.update || e.ratio<100) { - else if(e.ratio<100) { - ratio =e.ratio; - tryTimes =0; //initilize the trytimes for the cityid - downloadCityMap(e.cityID,e.cityName); - } - - - if(e.cityID == cityId ){ - rt = false; - } - /*QLog.getLogger().d(dTAG, TAG+ String.format("发现历史下载%s,上次下载 %d",e.cityName,e.ratio) ); -// rt = e.update || e.ratio<100; - rt = e.ratio<100; - if(e.ratio<100){ - ratio =e.ratio; - QLog.getLogger().d(dTAG, TAG+ String.format("发现未下载完成地图%s,上次下载 %d",e.cityName,e.ratio) ); - tryTimes =0; //initilize the trytimes for the cityid - downloadCityMap(e.cityID,e.cityName); - rt =false; - } */ -// return e.update && e.ratio==100; - } - - if(rt){ - - tryTimes =0;//initilize the trytimes for the cityid - downloadCityMap(cityId,cityName); - } - - importFromSDCard(); - - - } - - - - boolean downloadCityMap(int cityId,String cityName){ - app.isOfflimeMapWorking = true; - mOffline.start(cityId); -// Toast.makeText(this, "开始下载离线地图. cityid: "+cityId, Toast.LENGTH_SHORT) -// .show(); - QLog.getLogger().d(dTAG, TAG+" 开始下载离线地图. cityid: "+cityId ); - long totalTime =0; - int lastPcent =0; - int dPcent =0; - while( ratio<100 && Utils.getNetworkType(this) == QiYouConstant.NETWORK_TYPE_WIFII - &&totalTime<1000*20){ - if(lastPcent==0)lastPcent=ratio; - - try { - QLog.getLogger().d(dTAG, TAG+ " " +cityName +" Offline map download percent: " + ratio ); - Thread.sleep(1000); - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - dPcent +=ratio -lastPcent ; - if(ratio==lastPcent)totalTime+=1000; - lastPcent =ratio; - - } - - QLog.getLogger().d(dTAG, TAG+" Offline map download percent: " + dPcent ); - if(ratio ==100){ - String msg = String.format("成功下载并导入 %s 离线地图",cityName); -// Toast.makeText(this, msg , Toast.LENGTH_SHORT).show(); - QLog.getLogger().d(dTAG, TAG+ " "+msg); - - app.isOfflimeMapWorking = false; - }else - { - QLog.getLogger().d(dTAG, TAG+String.format(" 本次新下载了%d" ,lastPcent -ratio)); - if(lastPcent ==ratio && ratio==0){ - mOffline.remove(cityId); - QLog.getLogger().d(dTAG, TAG+" 删除原有下载,重新开始下载"); - tryTimes+=1; - if(tryTimes<3) - downloadCityMap(cityId,cityName); - - } - - } - - QLog.getLogger().d(dTAG, TAG+ " 本次处理结束."); - app.setlastOffMapRequestTime(); - return true; - } - - void importFromSDCard( ){ -// int num = -// mOffline.scan(); - /*String msg = ""; - if ( num == 0){ - msg = "没有导入离线包,这可能是离线包放置位置不正确,或离线包已经导入过"; - } - else{ - msg = String.format("成功导入 %d 个离线包,可以在下载管理查看",num); - } -// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); - QLog.getLogger().d(dTAG, TAG+" "+ msg );*/ - } - - private int search(String cityName ){ - int cityId= -1; - ArrayList records = mOffline.searchCity(cityName); - if (records != null && records.size() == 1) - cityId = records.get(0).cityID; - - return cityId; - } - - - void initialOffMap(){ -// mMapView = new MapView(new Activity()); - - QLog.getLogger().d(dTAG, " offmap update... initializing mapview"); - - /* mMapView = app.mMapview; - - if(mMapView ==null){ - stopSelf(); - return; - }*/ - -// mMapController = mMapView.getController(); - - mOffline = new MKOfflineMap(); - /** - * 初始化离线地图模块,MapControler可从MapView.getController()获取 - */ - -// mOffline.init(mMapController, this); - - mOffline.init(/*mMapController,*/ mylistener); - - - //获取已下过的离线地图信息 - localMapList = mOffline.getAllUpdateInfo(); - if ( localMapList == null ){ - localMapList = new ArrayList(); - } - } - - - MKOfflineMapListener mylistener = new MKOfflineMapListener() { - - @Override - public void onGetOfflineMapState(int type, int state) { - switch (type) { - case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: - { - MKOLUpdateElement update = mOffline.getUpdateInfo(state); - if ( update != null ){ - ratio =update.ratio; -// stateView.setText(String.format("%s : %d%%", update.cityName, update.ratio)); -// updateView(); - } - } - break; - case MKOfflineMap.TYPE_NEW_OFFLINE: -// QLog.getLogger().d(dTAG, String.format("add offlinemap num:%d", state)); - break; - case MKOfflineMap.TYPE_VER_UPDATE: -// QLog.getLogger().d(dTAG, String.format("new offlinemap ver")); - break; - } - - } - - - }; - - - /*@Override - public void onGetOfflineMapState(int type, int state) { - switch (type) { - case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: - { - MKOLUpdateElement update = mOffline.getUpdateInfo(state); - //处理下载进度更新提示 - if ( update != null ){ - ratio =update.ratio; -// stateView.setText(String.format("%s : %d%%", update.cityName, update.ratio)); -// updateView(); - } - } - break; - case MKOfflineMap.TYPE_NEW_OFFLINE: - //有新离线地图安装 - QLog.getLogger().d("OfflineDemo", String.format("add offlinemap num:%d", state)); - break; - case MKOfflineMap.TYPE_VER_UPDATE: - // 版本更新提示 - // MKOLUpdateElement e = mOffline.getUpdateInfo(state); - - break; - } - - }*/ -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/QNaviSvc.java b/qy/src/main/java/com/qiyou/mb/android/service/QNaviSvc.java deleted file mode 100644 index a20119a..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/QNaviSvc.java +++ /dev/null @@ -1,1557 +0,0 @@ -package com.qiyou.mb.android.service; - -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.location.Location; -import android.os.Bundle; -import android.os.IBinder; -import android.os.Vibrator; -import android.text.TextUtils; - -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; -import java.util.ArrayList; -import java.util.HashMap; -//import com.qiyou.mb.android.receivers.ProximIntentReceiver; - -public class QNaviSvc extends Service { - - public final static String TAG = "com.qiyou.qnaviSvc"; - public static final String dTAG = "com.qiyou"; -// public static final String REQEUST_CODE_INTENT_EXTRA="REQEUST_CODE"; -// public static final String ROADBOOK_INTENT_EXTRA="ROADBOOK"; - - -// private HashMap intentMap; -// private LocationManager locManager ; -// private ProximityIntentReceiver proximiReceiver; - - -// private static final String REQEUST_CODE_INTENT_EXTRA="REQEUST_CODE"; -// private static final String ROADBOOK_INTENT_EXTRA="ROADBOOK"; - private int naviId=0; - private long lastCheckNaviPoint=0; - private double lastCheckNaviDist=0; //last alert check dist - private double lastExistNaviDist=0; //last exist sum dist - private boolean isWrongWayAlert; - private boolean isFirstWaypoint =false; - private long lastTime_avs=0; - private float last_avs=0f; - private int wrongWayCnt=0; - private final String WRONG_WAY=" 偏离设定路线。。。 "; - private final long WRONG_WAY_MAX_INTERVAL = 300*1000 ; - private final long WRONG_WAY_MIN_INTERVAL = 60*1000 ; - private final int MIN_TURN_DIST =10; //最小转弯播报距离,小于此距离则直接报 转弯 -// private final int WRONG_WAY_MAX_DIST=1000; - private boolean isNotCheckedin=true; - private float avDist=50;//average distance for judging wps - private float currentDist=0; - private float nextDist=0; - private float lastDist=0; - private int wrongDirectionCnt=0; - private final int WRONG_WAY_ALERT_CNT=2; //cnt passt sine first validation that takes as isWrongWayAlert - private final int WRONG_WAY_ALERT_AVDIST_CNT=2; // alert dist limit - private final int INT_START_ALERT_CNT=3; // cnt passed since first validation begin to speach alert msg. - private float minDistPlus=0; -// private String targetKey=""; -// private boolean is_targetWb_fired=false; - private Vibrator vibrator ; - @Override - public IBinder onBind(Intent intent) { - // TODO Auto-generated method stub - return null; - } - - protected QiYouApplication app; - @Override - public void onCreate(){ -// // // QLog.getLogger().d(dTAG,TAG+"... service naviSvc onCreate.....," ); - // // QLog.getLogger().d( TAG,TAG+"... service naviSvc onCreate.....," ); - app = (QiYouApplication) this.getApplication(); -// intentMap =new HashMap() ; - - - } - - - @Override - public int onStartCommand(Intent intent, int flags, int startId){ - // // QLog.getLogger().d( TAG,TAG+"... service NaviSvc onStartCommand.....," ); - handleIntent(intent); - // We want this service to continue running until it is explicitly - // stopped, so return sticky. -// return START_NOT_STICKY; //TODO: checking why can not stop the service. - return START_STICKY; - } - - - private void handleIntent(Intent intent){ - - //to check if the application restart with new instances or not - // The check result is, the new application instance created, the original referenced application still exits. - - //TODO: to find what cause creating new application instances? - if(intent==null)return; - - String key = QiYouConstant.EXTRA_KEY_START_NAVI; - - - if (intent.hasExtra(key)){ - - if(app.isNaving && !app.isRestoreNavi)return; - // // QLog.getLogger().dLog(TAG,TAG, " is Play back? "+app.playBack ); - naviId =app.naviTrackId; - - if(!app.isRestoreNavi) - sayHello(); - app.isRestoreNavi=false; - initialParameters(); - getChkWps(); - processNavigation(); -// // // QLog.getLogger().dLog(TAG,TAG, " Navigation is done.......................................... "); -// exitNav(); - return; - } - - } - - - final float sleepFactor=0.5f; - final int turnFactor= 8;//10;//5; - final int distFactor= 6;//8; - private long [] vibratorTurnPattern = {100,500,100,500}; // 停止 开启 停止 开启 - private long [] vibratorWrongWayPattern = {100,1000,100,1000}; // 停止 开启 停止 开启 - private boolean mIsFromLast=false; - private int minSleeptime; - private int maxSleeptime; - -// private HashMap checkWps; - private HashMap checkWps; - private ArrayList firedWbs; - - - private void processNavigation(){ - - // // QLog.getLogger().d( TAG,TAG+"... processNavigation()...." ); - vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); - new Thread(){ - private ArrayList alertWbs; -// private HashMap checkWps; - Waypoint_bean targetWb; -// Location targetLoc; -// int distance=0; -// int radius=0; - - - int alertDist=0; - int sleeptime;; -// int minSleeptime; -// int maxSleeptime; - int maxDist; -// int minDist; -// float avs=0; - int leftDistance=0; - boolean isClosing=false; - int lastLeft=0; - int lastCnt=0; - int tringCnt=-5;//numbers of run away from the target - int distForSayTurn=0; -// long lastLocationTime=0; - int speakCnt=0; -// boolean isSpeakTurn=false; -// float lastDist=0; - - - - final String LATERTHEN="然后";//"后" - @Override - public void run() { -// isWrongWayAlert=false; - app.isNaving=true; - sleeptime=getinitialSleepTime() ; - minSleeptime=sleeptime*5; - maxSleeptime =1*60*1000; //最大sleep时间 -// maxDist=30*sleeptime;// - maxDist=1000;//最大1公里 -// minDist=maxDist/3; - Track gpxTrack=null; - alertWbs = new ArrayList(); - firedWbs =new ArrayList(); - if(app.naviTrackId>0){ - app.setLastNavId(); -// gpxTrack=app.tracks_cached.get(app.naviTrackId); - gpxTrack=app.getTrackCache().get(app.naviTrackId); - if(gpxTrack!=null){ - alertWbs.addAll(gpxTrack.getTrackBean().getRoadWps()); - -// app.rd= gpxTrack.getTrackBean().getDistance()/gpxTrack.getTrackBean().getTrkseg().size() >100?100f:1000f; - app.rd= gpxTrack.getTrackBean().getDistance()/gpxTrack.getTrackBean().getTrkseg().size() >100?app.rd/5:app.rd; - - if(gpxTrack.getTrackBean().getIsCheckedIn()==0){ //骑行最大睡觉时间为2分钟 - maxSleeptime = maxSleeptime*2; - } - } - - - } - /*else - for(Integer i:app.getGpxShowingTracks()){ - gpxTrack=app.getTrackCache().get(i); - if(gpxTrack!=null) - alertWbs.addAll(gpxTrack.getTrackBean().getRoadWps()); - }*/ - - if(alertWbs.isEmpty())return; - try { - - - - if(checkForNewLocation(targetWb )){ - - return; - } - int minDist=Integer.MAX_VALUE; - int tmpInt=Integer.MAX_VALUE; - int targetIndex = 0; -// Long bfdbTime = System.currentTimeMillis(); - int dist; - String LATERTHEN_TURN=""; - if(currentDist==0){ - for(int i=0;idist){ - tmpInt=dist; - targetIndex=i; - } - } - } - else{ - for(int i=0;idist){ - if(dist>currentDist){ -// tmpInt=dist; - targetIndex=i; - break; - } - } - } - - if(targetIndex>0){ - firedWbs.addAll(alertWbs.subList(0,targetIndex)); - - } - isFirstWaypoint =targetIndex==0; - // // QLog.getLogger().dLog(TAG,TAG, "Target index is:" +targetIndex); - -// distForSayTurn =alertDist/10>distForSayTurn?distForSayTurn:alertDist/10; - String targetRoadbook=""; - String targetTurn=""; - String nextGeo =""; - Waypoint_bean nextWb; - - while(firedWbs.size()<= alertWbs.size()){ - - // // QLog.getLogger().dLog(TAG,TAG, " firedWbs.size(): " +firedWbs.size()); - - if(isNaviDone()){ - - return; - } - speakCnt=0; - leftDistance=0; - lastCnt=0; - LATERTHEN_TURN=""; - nextDist=0; - if( wrongWayCnt==0 && isFromLast() && currentDist>0){ //in right way, last target is not right, try to find next right turn - // // QLog.getLogger().dLog(TAG,TAG, " to find next target, condition is: wrongWayCnt==0 && isFromLast() && currentDist>0" ); - for(int i=0;icurrentDist){ - targetIndex=i; - break; - } - } - /*targetIndex =targetIndex0){ - firedWbs.clear(); - firedWbs.addAll(alertWbs.subList(0,targetIndex)); - } - setFromLast(false); - - }else{ - targetWb =alertWbs.size()>firedWbs.size()?alertWbs.get(firedWbs.size()):alertWbs.get(alertWbs.size()-1); - } - - - - // // QLog.getLogger().dLog(TAG,TAG, "Target index is:" +targetIndex); - - - - if(targetWb==null)continue; - - sleeptime=getinitialSleepTime() ; - minDist=(int) (getAvs()/3.6*sleeptime/1000*turnFactor); - minDist =app.playBack?(int) (getAvs()/3.6*500/1000*turnFactor):minDist; - distForSayTurn=minDist; - - - targetRoadbook =targetWb.getRoadBook(); - - // // QLog.getLogger().dLog(TAG,TAG,"1 targetRoadbook: " +targetRoadbook ); - - - if( QiYouConstant.PV_INT_NAVI_SPEAK_MODEL==0 ){ - int i =targetRoadbook.lastIndexOf("前方到达"); - // // QLog.getLogger().dLog(TAG,TAG," targetRoadbook.lastIndexOf(前方到达): " +i ); - if(i>0){ - targetRoadbook = targetRoadbook.substring(0,i); - } - } - - // // QLog.getLogger().dLog(TAG,TAG,"2 targetRoadbook: " +targetRoadbook ); - - targetTurn =targetWb.getTurnFlag().toCHString(); - targetTurn=targetTurn.equalsIgnoreCase(wpFlag.NORMAL.toCHString())?"":targetTurn.equalsIgnoreCase(wpFlag.CUST.toCHString())?"":targetTurn; - LATERTHEN_TURN =TextUtils.isEmpty(targetTurn)?targetTurn:LATERTHEN+targetTurn; - alertDist= (int) (targetWb.getBearDist()>0?targetWb.getBearDist():targetWb.getDistance()); - - if(targetWb.getTurnFlag()==wpFlag.MAXR){ - targetRoadbook += nextGeo+",\n"+targetWb.getComment(); - // // QLog.getLogger().dLog(TAG,TAG," find maxR" ); - } else - if(firedWbs.size()+10 && alertDist>minDist) - { - alertDist =(int) (alertDist/4); - alertDist=alertDist>maxDist?maxDist:alertDist; - alertDist=alertDistalertDist?alertDist:distForSayTurn; - // QLog.getLogger().dLog(TAG,TAG, " 0 leftDistance: " +leftDistance+", lastLeft : " +lastLeft +", lastCnt "+ lastCnt +",getAvs() :" + ""+getAvs() +",alertDist:" +alertDist +", distForSayTurn:" +distForSayTurn); - - if(lastLeft +alertDist>0){ - - speakTurn( targetWb, getTurnDesc(lastLeft +alertDist ,targetTurn)/*String.format("前行%s ,%s", Utils.getFormatedDistance(lastLeft +alertDist),targetTurn)*/); - - checkOnWay(targetWb); -// sleeptime =(int) ((((alertDist+lastLeft-distForSayTurn)/(getAvs()/3.6))*1000)*(app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/QiYouConstant.MAX_GPS_SPAN:sleepFactor)); - sleeptime =getAvailableSleepTime(alertDist+lastLeft-distForSayTurn); - if(sleeptime>0){ - // QLog.getLogger().dLog(TAG,TAG," ----Sleep:" +sleeptime); - if(isNaviGood()) - Thread.sleep(sleeptime); - } - } - - speakTurn(targetWb,targetTurn); - - - lastLeft =getLeftDistance(targetWb,alertDist); - if(lastLeft +alertDist>0){ - speakRoadBook(targetWb,String.format("前行%s , %s, %s",Utils.getFormatedDistance(lastLeft +alertDist),LATERTHEN_TURN,targetRoadbook)); - }else{ - speakRoadBook(targetWb, targetRoadbook); - } - - //TODO: sleep to the last distination - checkOnWay(targetWb); -// sleeptime =(int) ((((alertDist+lastLeft)/(getAvs()/3.6))*1000)*(app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/QiYouConstant.MAX_GPS_SPAN:sleepFactor)); - sleeptime =getAvailableSleepTime(alertDist+lastLeft); - // // QLog.getLogger().dLog(TAG,TAG," Sleep:" +sleeptime); - if(sleeptime>0) - if(isNaviGood()) - Thread.sleep(sleeptime); - - if(checkForNewLocation(targetWb )){ - - return; - } - - - if(firedWbs.size() ==alertWbs.size()){ - speakRoadBook(targetWb,"到达终点位置附近"); - } - - if(firedWbs.size() > alertWbs.size()){ //到达终点位置附近,重新寻找导航点 - // QLog.getLogger().dLog(TAG,TAG, " 到达终点位置附近,重新寻找导航点 ... " ); - Thread.sleep(getinitialSleepTime()); - processNavigation(); - return; - } - - - - continue; - } - - distForSayTurn = distForSayTurn >alertDist?alertDist:distForSayTurn; - - // QLog.getLogger().dLog(TAG,TAG, " alertDist:" +alertDist +",sleeptime: "+sleeptime +",distForSayTurn:"+distForSayTurn); - - checkOnWay(targetWb); - if(checkForNewLocation(targetWb )){ - - return; - } - - updateUI(targetWb,"导航中..."); - sayHi(); - - lastLeft =getLeftDistance(targetWb,alertDist); - leftDistance =lastLeft; - - // QLog.getLogger().dLog(TAG,TAG, " lastLeft:" +lastLeft +",sleeptime: "+sleeptime); - - // QLog.getLogger().dLog(TAG,TAG, "1 leftDistance: " +leftDistance+", lastLeft : " +lastLeft +", lastCnt "+ lastCnt +",getAvs() :" +""+getAvs() +",alertDist:" +alertDist +", distForSayTurn:" +distForSayTurn); - - - while(getAvs()>0 && lastLeft>0 && lastCnt>=tringCnt){ - sleeptime= getinitialSleepTime(); - - if(isClosing) - if(checkForNewLocation(targetWb )){ - - return; - } - - lastLeft =getLeftDistance(targetWb,alertDist); - // // QLog.getLogger().dLog(TAG,TAG, " lastLeft:" +lastLeft +",lastCnt: "+lastCnt); - if(lastLeft<=0 && lastCnt>=0){ //in alert zone - isClosing=true; - // // QLog.getLogger().dLog(TAG,TAG, "in alert zone, to speak..."); - break; - } - - if(checkForNewLocation(targetWb )){ - - return; - } - - lastLeft =getLeftDistance(targetWb,alertDist); - - - if(leftDistance-lastLeft>=0){ //接近目标 -// lastLeft=leftDistance; - lastCnt++; - - if(lastLeft<0){ //in alertdist - isClosing=true; - break; - - } - - } - else{ //远离目标 - - isClosing=false; - - if(lastLeft<0 ){ //in alertdist - - if(lastLeft+alertDist>distForSayTurn){ //passed the target,between the target and say-turn point - if(speakCnt==0){ - speakRoadBook(targetWb,targetRoadbook); - } - break; - } - - } - - if(lastLeft>0 && lastCnt<-2){ //out alert scope,to next - - break; - } - - if(lastCnt>0)lastCnt=0; - lastCnt--; - } - - - isClosing=lastCnt>0; - - // // QLog.getLogger().dLog(TAG,TAG, "2 leftDistance: " +leftDistance+", lastLeft : " +lastLeft +", lastCnt "+ lastCnt +",getAvs() :" +""+getAvs() +",alertDist:" +alertDist); - - leftDistance=leftDistance>lastLeft?lastLeft:leftDistance; - - if( lastLeft>0 && isClosing &&getAvs()>0){ - checkOnWay(targetWb); - sleeptime =(int) (((leftDistance/(getAvs()/3.6))*1000)*(app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/QiYouConstant.MAX_GPS_SPAN:1)) ; - if(sleeptime>30000) - if(/*!isWrongWayAlert*/isNaviGood()){ - speakDistTimeToTarget(sleeptime,leftDistance+alertDist); - } - - sleeptime =getAvailableSleepTime(leftDistance); - if(QiYouConstant.DEVELOPER_MODE){ - updateUI(targetWb," 接近目标点,等待(s):" +sleeptime/1000); - } - - // // QLog.getLogger().dLog(TAG,TAG, " sleep:: " +sleeptime); - if(sleeptime>0){ - if(isNaviGood()){ - Thread.sleep(sleeptime); -// lastCheckNaviPoint =System.currentTimeMillis();//重新设定验证点时间 - } - } - - sayHi(); - - } - - lastLeft =getLeftDistance(targetWb,alertDist); - - if(lastCnt0 && lastCnt<-2 )) { - - // // QLog.getLogger().dLog(TAG,TAG, " it is away from the current target,isNotCheckedin :" +isNotCheckedin); - - if(isNotCheckedin){ - - setFromLast(false); - processNavigation(); - return; - } - - setFromLast(false); - processNavigation(); - return; - - } - - sleeptime= getinitialSleepTime(); - // // QLog.getLogger().dLog(TAG,TAG, " isClosing? "+isClosing +" , lastLeft,alertDist: "+lastLeft+","+alertDist); - - if(isClosing ){ -// ||lastLeft+alertDist<=0){ - - - int closeDist=lastLeft; -// closeDist=lastLeft-alertDist; - int lastCloseDist=closeDist; -// targetTurn= targetWb.getTurnFlag()==wpFlag.NORMAL?"":targetTurn; - while(isClosing -// && closeDist<0) {//in alert scope - && closeDist<=0) {//in alert scope -// && (closeDist+alertDist>distForSayTurn)){ //almost on target -// sleeptime= getinitialSleepTime(); - -// - if(closeDist +alertDist<=distForSayTurn){ //between the say-turn point and the target - - if(closeDist +alertDist>0){ - targetTurn= String.format("前行%s米 ,%s", closeDist +alertDist,targetTurn); - speakTurn(targetWb,targetTurn); - Thread.sleep((int) ((closeDist +alertDist)/(getAvs()/3.6)*1000)); - speakRoadBook(targetWb,targetRoadbook); - break; - } - speakTurn(targetWb,targetTurn); - speakRoadBook(targetWb,targetRoadbook); - break; - } - - if(!TextUtils.isEmpty(targetTurn) && closeDist +alertDist<2*distForSayTurn){ - speakTurn(targetWb,String.format("前行%s,%s",Utils.getFormatedDistance(closeDist +alertDist),LATERTHEN_TURN)); - - } - - - checkOnWay(targetWb); -// sleeptime =(int) ((((alertDist+closeDist-distForSayTurn)/(getAvs()/3.6))*1000)*(app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/QiYouConstant.MAX_GPS_SPAN:sleepFactor)); - sleeptime =getAvailableSleepTime(alertDist+closeDist-distForSayTurn); - if(sleeptime>0) - if(isNaviGood()) - Thread.sleep(sleeptime); - else{ - speakTurn(targetWb,String.format("前行%s,%s", Utils.getFormatedDistance(closeDist +alertDist),LATERTHEN_TURN)); - - break; - } - - // // QLog.getLogger().dLog(TAG,TAG, String.format(" wait for turn, sleeptime %s,speakCnt:%s", sleeptime,speakCnt) ); - - - sleeptime= 0; - - if(checkForNewLocation(targetWb )){ - - return; - } - - closeDist =getLeftDistance(targetWb,alertDist); -// isClosing =Math.abs(closeDist)<=Math.abs(lastCloseDist); - isClosing =closeDist+alertDist<= alertDist+lastCloseDist && closeDist+alertDist>0; - // // QLog.getLogger().dLog(TAG,TAG, String.format(" real distance to target %s,lastCloseDist %s, isClosing %s", closeDist+alertDist ,lastCloseDist+alertDist,isClosing) ); - lastCloseDist=closeDist; - // // QLog.getLogger().dLog(TAG,TAG, String.format(" speakCnt:%s", speakCnt) ); -// updateUI(targetWb," 距下个导航目标距离: "+ closeDist ); - if(QiYouConstant.DEVELOPER_MODE){ - updateUI(targetWb,String.format("??isclosing?%s,leftDist %s,alertDist %s", isClosing,closeDist,alertDist)); -// speachNav("这是测试1",4); -// speakRoadBook(targetWb,"这是测试1"); - } - -// if(isClosing ||closeDist+alertDist<0)break; - if(isClosing && speakCnt<3){ - - if( !app.playBack || speakCnt==0) - {// when playback/snavi,only speak once!!! - speakRoadBook(targetWb,String.format("前行%s, %s, %s",Utils.getFormatedDistance(closeDist +alertDist),LATERTHEN_TURN,targetRoadbook)); - } - speakCnt++; - - }else{ - break; - } - - if(!isClosing)break; - - checkOnWay(targetWb); -// sleeptime +=((closeDist/(getAvs()/3.6))*1000)*(app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/QiYouConstant.MAX_GPS_SPAN:sleepFactor); -// sleeptime =(int) ((((alertDist+closeDist)/(getAvs()/3.6))*1000)*(app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/QiYouConstant.MAX_GPS_SPAN:sleepFactor)); - sleeptime =getAvailableSleepTime(alertDist+closeDist); - // // QLog.getLogger().dLog(TAG,TAG, String.format(" sleeptime %s,speakCnt:%s", sleeptime,speakCnt) ); - if(sleeptime>0) - if(isNaviGood()) - Thread.sleep(sleeptime); -// Thread.sleep(getinitialSleepTime()); - closeDist =getLeftDistance(targetWb,alertDist); - lastCloseDist=closeDist; - - - } - -// Thread.sleep(getinitialSleepTime()); - } - if(speakCnt==0 && isNaviGood()){ -// && lastLeft<=0){ -// && lastLeft+alertDist>0) - speakRoadBook(targetWb,targetRoadbook); - } - - Thread.sleep(getinitialSleepTime()); - updateUI(targetWb," 开始下个导航点。。。。 " ); - // // QLog.getLogger().dLog(TAG,TAG, " goto next target... " ); - if(isNaviGood() && firedWbs.size() ==alertWbs.size()){ - - speakRoadBook(targetWb,"到达终点位置附近"); - } - - if(firedWbs.size() > alertWbs.size()){ //到达终点位置附近,重新寻找导航点 - // // QLog.getLogger().dLog(TAG,TAG, " 到达终点位置附近,重新寻找导航点 , goto next target... " ); - Thread.sleep(getinitialSleepTime()); - processNavigation(); - return; - } - - - } - - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - app.isNaving=false; - exitNav(); - }}.start(); - } - - - - - private void exitNav(){ - // // QLog.getLogger().dLog(TAG , " try to stop the service..."); - app.clearLastNavId(); - this.stopSelf(); - } - private int getinitialSleepTime(){ - int sl=app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL:QiYouConstant.MAX_GPS_SPAN;; - // // QLog.getLogger().dLog(TAG,TAG, " get initial sleeptime: " +sl); -// return sl; - return app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/10:QiYouConstant.MAX_GPS_SPAN; - } - - private int getAvailableSleepTime(float dist){ - int sleeptime =(int) (((dist/(getAvs()/3.6))*1000)*(app.playBack?QiYouConstant.PLAYBACK_TIME_INTERVAL/QiYouConstant.MAX_GPS_SPAN:1)) ; - sleeptime=sleeptime/2; - sleeptime =sleeptime>minSleeptime?sleeptime:0; - sleeptime=sleeptime>maxSleeptime?maxSleeptime:sleeptime; - return sleeptime; - } - - - - -// private boolean checkForNewLocation(Waypoint_bean targetWb, HashMap chkWps) throws InterruptedException{ - private boolean checkForNewLocation(Waypoint_bean targetWb) throws InterruptedException{ - int sleeptime= getinitialSleepTime(); - long lastLocationTime=app.lastNaviLocation==null?0:app.playBack?app.lastNaviLocation.getExtras().getLong("wptime"):app.lastNaviLocation.getTime(); - - while( app.lastNaviLocation==null ||lastLocationTime==app.lastNaviLocation.getTime() - ||app.playBack && (lastLocationTime==app.lastNaviLocation.getExtras().getLong("wptime"))){ - if(!app.playBack){ - // // QLog.getLogger().dLog(TAG,TAG, " No location got, waiting for GPS...,sleep: " +sleeptime); - } - Thread.sleep(sleeptime); - -// // // QLog.getLogger().dLog(TAG,TAG, "--------------- after sleep " ); - - sayHi(); - if(!app.playBack) - updateUI(targetWb," 导航进行中..."); - - if(isNaviDone()){ - // // QLog.getLogger().dLog(TAG,TAG + " to exit navigation"); - return true; - - } -// if(sleeptime<5*getinitialSleepTime()) -// sleeptime+=sleeptime/10; -// else -// sleeptime=getinitialSleepTime(); - } - - while(app.lastNaviLocation!=null && 0==app.lastNaviLocation.getSpeed()){ - if(!app.playBack){ - // // QLog.getLogger().dLog(TAG,TAG, " Not Moving... sleeptime: "+sleeptime); - } - Thread.sleep(sleeptime); - sayHi(); - if(!app.playBack) - updateUI(targetWb," 静止中"); -// if(sleeptime<5*getinitialSleepTime()) -// sleeptime+=sleeptime/10; -// else -// sleeptime=getinitialSleepTime(); - if(isNaviDone()){ - // // QLog.getLogger().dLog(TAG,TAG + " to exit navigation"); - return true; - - } - } - - - - - return false; - - } - - - - void checkOnWay(Waypoint_bean targetWb ) throws InterruptedException{ - - - - - if(app.lastNaviLocation!=null && app.lastNaviLocation.getSpeed()>0 && checkWps!=null && checkWps.keySet()!=null && checkWps.keySet().size()>0 ){ - /* float keyToCheck =getFloatKey((float)app.lastNaviLocation.getLatitude(),(float)app.lastNaviLocation.getLongitude());*/ - /* float keyToCheck =getFloatKey((float)app.lastNaviLocation.getLatitude());*/ - - String keyToCheck =getStringKey((float)app.lastNaviLocation.getLatitude(),(float)app.lastNaviLocation.getLongitude()); - - boolean isExist=checkWps.keySet().contains( keyToCheck ) ; - - if(isExist && isNotCheckedin){ - isNotCheckedin=false; - } - - if(isNotCheckedin) return ;//not in the route ever - - /* if(!isExist - && !canDistAlert() //not reach last waypoint - && wrongDirectionCnt==0 //when wrong direction cnt>0, go on check for next direction - ){ - // QLog.getLogger().dLog(TAG, " not reach the nextDist.......skip wrong way check..................."); - return; - }*/ - - if(wrongWayCnt==0){ //reset the lastCheckNaviDist, in case sleep dist in naviprocess - lastCheckNaviDist=app.sumNavDist; - } - - int chkCnt=0; - while (app.lastNaviLocation.getSpeed()>0 && !isExist && chkCnt<10 ||isWrongWayAlert){ - - if(isNaviDone()){ - // // QLog.getLogger().dLog(TAG,TAG + " to exit navigation"); - return; - - } - chkCnt++; - - keyToCheck =getStringKey((float)app.lastNaviLocation.getLatitude(),(float)app.lastNaviLocation.getLongitude()); - isExist=checkWps.keySet().contains( keyToCheck ) ; - - if(isExist){ - // // QLog.getLogger().dLog(TAG,TAG + String.format(" keytocheck %s exist", keyToCheck)); - break; - } - - // // QLog.getLogger().dLog(TAG,TAG + String.format(" keytocheck %s not exist", keyToCheck)); - - - Thread.sleep(getinitialSleepTime()); - - - long interVal=(long) ((avDist/(getAvs()/3.6))*1000) ; /*60000*/ - // QLog.getLogger().dLog(TAG, String.format("chkwps: missed wps check original interVal: %s",interVal)); - - interVal =interVal>WRONG_WAY_MAX_INTERVAL? WRONG_WAY_MAX_INTERVAL:interVal; - - - - if(wrongWayCnt>0){ - if(wrongWayCnt<=2) { - interVal=WRONG_WAY_MIN_INTERVAL/2; - }else{ - interVal-=15000*wrongWayCnt; - interVal=interVal0 && System.currentTimeMillis()-lastCheckNaviPoint> interVal ){ - if( canDistAlert() && lastCheckNaviPoint>0 && System.currentTimeMillis()-lastCheckNaviPoint> interVal ){ - -// // QLog.getLogger().dLog(TAG, String.format("chkwps: lat wrongWayAlert, time pass:%s s, since last pass",(System.currentTimeMillis()-lastCheckNaviPoint)/1000 ) ); - - wrongWayCnt++; - - isWrongWayAlert=wrongWayCnt>=WRONG_WAY_ALERT_CNT; - - if(isWrongWayAlert) { - updateUI(targetWb,WRONG_WAY ); - } - - wrongWayAlert(); - - lastCheckNaviPoint =System.currentTimeMillis(); - lastCheckNaviDist =app.sumNavDist; - - - } - - } - - - - if(isExist){ - - - lastCheckNaviPoint =System.currentTimeMillis(); - lastExistNaviDist=app.sumNavDist; - lastCheckNaviDist =app.sumNavDist; -// isWrongWayAlert=false; - isNotCheckedin =false; - - if(app.playBack){ - return; - } - - - lastDist=currentDist; - currentDist = checkWps.get(keyToCheck)[0]; - nextDist = checkWps.get(keyToCheck)[1]; - -// // QLog.getLogger().dLog(TAG, String.format(" Existed, keyToCheck : %s,currentDist = %s ,lastDist =%s", keyToCheck, currentDist,lastDist )); - - - // QLog.getLogger().dLog(TAG, String.format(" Existed, wrongDirectionCnt : %s,currentDist -lastDist = %s ,nextDist =%s", wrongDirectionCnt, (currentDist -lastDist),nextDist )); - - if(currentDistlastDist) { - wrongDirectionCnt=0; - isWrongWayAlert=false; - } - - if(wrongWayCnt>0 && wrongDirectionCnt==0 ){ - speachNav("导航路线正常。。。",1); - updateUI(targetWb,"导航进行中..." ); - - } - - wrongWayCnt=0; - } - - if(wrongDirectionCnt>4){ - // // QLog.getLogger().dLog(TAG, String.format("Wrong direction Alert! wrongDirectionCnt =%s", (currentDist -lastDist) )); - isWrongWayAlert=true; - speachNav("警告:方向错误",1); - vibratorAlert(vibratorWrongWayPattern,-1); - wrongDirectionCnt=0; - } - - - - - - - - } -// // // QLog.getLogger().dLog(TAG, String.format("chkwps: chkWps.keySet().contains :%s,value is %s",checkWps.keySet().contains( keyToCheck), checkWps.get( keyToCheck) ) ); -// -//// // // QLog.getLogger().dLog(TAG, String.format("chkwps: lat tocheck new location:%s,%s,eixst? %s",keyToCheck,getFloatKey((float)app.lastNaviLocation.getLongitude()),isExist)); -// // // QLog.getLogger().dLog(TAG, String.format("chkwps: lat tocheck new location:%s,eixst? %s",keyToCheck, isExist)); - - } - - - void initialParameters(){ - lastTime_avs=0; - last_avs=0f; - wrongWayCnt=0; - isNotCheckedin=true; - isWrongWayAlert=false; - lastCheckNaviPoint=0; - lastDist=0; - wrongDirectionCnt=0; - currentDist=0; - nextDist=0; - lastCheckNaviDist=0; - lastExistNaviDist=0; - } - - - - - /* - * km/h - */ - private float getAvs(){ - -// float avs=0f; - if(!app.playBack && System.currentTimeMillis()-lastTime_avs<5000){ -// lastTime_avs=System.currentTimeMillis(); //its bug!!!!! cause avs using old value, not updated in time - // // QLog.getLogger().dLog(TAG,TAG," return last avs:" +last_avs); - return last_avs>0?last_avs: 8 ; - } - - last_avs=app.getAVS(); - - if(app.playBack) return 20 ;//last_avs>0?last_avs:20; - - float lastSpeed= (float) (app.lastNaviLocation==null?0:app.lastNaviLocation.getSpeed()*3.6); -// // QLog.getLogger().dLog(TAG,TAG," app.lastNaviLocation.getSpeed()*3.6:" +lastSpeed); -// if(app.playBack) -// avs =app.getCurrentTrack().getTrackBean().getCAvs(); -// else -// avs = app.getRecordingTrack().getTrackBean().getCAvs(); - last_avs = app.getRecordingTrack().getTrackBean().getAvs(); -// // // QLog.getLogger().dLog(TAG,TAG, " app.getCurrentTrack().getTrackBean().getAvs(): "+app.getCurrentTrack().getTrackBean().getAvs() ); - -// // // QLog.getLogger().dLog(TAG,TAG," app.getRecordingTrack().getTrackBean().getAvs():" +last_avs); -// avs=avs >app.getAVS()?avs:app.getAVS(); - - -// last_avs=last_avs>0?last_avs:app.getAVS(); // app.getAVS() 可能比较大。。。 -// // // QLog.getLogger().dLog(TAG,TAG," app.getAVS():" +app.getAVS()); - - last_avs =last_avs>lastSpeed?last_avs:lastSpeed; - // // QLog.getLogger().dLog(TAG,TAG," return avs:" +last_avs); - // // QLog.getLogger().dLog(TAG,TAG,String.format("avs is %s,last speed is %s,return avs is %s" ,app.getRecordingTrack().getTrackBean().getAvs(), lastSpeed, last_avs)); - last_avs = last_avs>0?last_avs: 8 ; - - lastTime_avs=System.currentTimeMillis(); - - return last_avs ; -// return (float) (return_speed>0?return_speed:app.lastNaviLocation==null?0:app.lastNaviLocation.getSpeed()*3.6); - - - } - - - - - private int getLeftDistance(Waypoint_bean targetWb,int alertDist){ - Location targetLoc; - int distance=0; -// int radius=0; -// radius=(int) targetWb.getBearDist(); - targetLoc =new Location("fire"); - targetLoc.setLatitude(targetWb.getLatitude()); - targetLoc.setLongitude(targetWb.getLongitude()); - distance= (int) app.lastNaviLocation.distanceTo(targetLoc); - return (int) (distance-alertDist - distFactor*getAvs()/3.6*getinitialSleepTime()/1000); // 10*getAvs()*getinitialSleepTime(): 修正距离,+6个定位时间的距离 - } - - -// private void findTarget(){ -// // // QLog.getLogger().dLog(TAG,TAG, " trying to Find the target "); -// -// } -// - - /** - * check can sleep during navi process - * if wrongwaycnt >1, or wrongdirection then return false - * @return - */ -private boolean isNaviGood(){ - return wrongWayCnt<=1 // not in wrong way - && !isWrongWayAlert && wrongDirectionCnt==0; //with right direction -} - - private void validingWayAlert(){ -// if(!app.playBack) -// if(isWrongWayAlert) - if(wrongWayCnt > 1 ){ - speachNav("请检查导航路线是否正常...",1);//wrongwaycnt=2 - }else{ - speachNav("正在检查导航路线...",1); //wrongwaycnt=1 - } - } - - private void wrongWayAlert(){ - - // QLog.getLogger().dLog(TAG, String.format("chkwps: check dist can alert,wrongWayCnt is %s, minDistance is : %s",wrongWayCnt ,getMinDist())); - // // QLog.getLogger().dLog(TAG, String.format("chkwps: canDistAlert() : %s",canDistAlert())); - - /* if(!canDistAlert()){ - return; - }*/ - - if(/*isWrongWayAlert*/wrongWayCnt > INT_START_ALERT_CNT){ - speachNav("警告:偏离原设定路线",1); - vibratorAlert(vibratorWrongWayPattern,-1); - - }else{ - validingWayAlert(); - } - - /* if(wrongWayCnt==0){ - validingWayAlert(); - - } - else if(wrongWayCnt >= WRONG_WAY_ALERT_CNT ){ - // // QLog.getLogger().dLog(TAG, String.format("chkwps: speach alert,wrongWayCnt : %s",wrongWayCnt)); - speachNav("警告:偏离原设定路线",1); - - vibratorAlert(vibratorWrongWayPattern,-1); - }*/ - } - - /** - * get next roadpoint dist - * @return next roadpoint dist - */ - private float getMinDist(){ -// return wrongWayCnt>0?avDist:avDist*WRONG_WAY_ALERT_AVDIST_CNT; -// return nextDist>0?nextDist:wrongWayCnt>0?avDist:avDist*WRONG_WAY_ALERT_AVDIST_CNT; -// return wrongWayCnt>0?avDist/**1.5f*/:nextDist; - - switch(wrongWayCnt){ - case 0: return (avDist>nextDist?avDist:nextDist)*WRONG_WAY_ALERT_AVDIST_CNT +minDistPlus ; - case 1: return (avDist>nextDist?avDist:nextDist)*WRONG_WAY_ALERT_AVDIST_CNT +minDistPlus ; - // case 2: return (avDist>nextDist?avDist:nextDist)*WRONG_WAY_ALERT_AVDIST_CNT +minDistPlus ; - - default: return (avDist>nextDist?avDist:nextDist) +minDistPlus; - } - - -// return wrongWayCnt==0?(avDist>nextDist?avDist:nextDist)*WRONG_WAY_ALERT_AVDIST_CNT:avDist; - - } - /** - * distance limit for alert - * - */ - private boolean canDistAlert(){ - // QLog.getLogger().dLog(TAG, String.format("chkwps: getMinDist() : %s,app.sumNavDist:%s, lastCheckNaviDist: %s, lastExistNaviDist%s",getMinDist(),app.sumNavDist,lastCheckNaviDist,lastExistNaviDist )); - // QLog.getLogger().dLog(TAG,String.format("wrongWayCnt ?%s, can Dist Alert? %s", wrongWayCnt,app.sumNavDist - (wrongWayCnt>0?lastCheckNaviDist:lastExistNaviDist)>getMinDist())); - return app.sumNavDist - (wrongWayCnt>0?lastCheckNaviDist:lastExistNaviDist)>getMinDist(); - } - -/* private boolean isMaxDistAlert(){ - // // QLog.getLogger().dLog(TAG, String.format("chkwps: getMinDist() : %s,app.sumNavDist:%s, lastCheckNaviDist: %s, lastExistNaviDist%s",getMinDist(),app.sumNavDist,lastCheckNaviDist,lastExistNaviDist )); - return wrongWayCnt ==0 && (app.sumNavDist - (wrongWayCnt>0?lastCheckNaviDist:lastExistNaviDist)>avDist*4); - }*/ - - - private void speakDistTimeToTarget(long waitTime,int distance){ - if(isWrongWayAlert)return; -// String format = "距离下个位置还有%s,预计需要时间%s"; - String format = "继续前行%s,预计需要时间%s"; - String time = Utils.getTimeCnt4Read(waitTime,true); - time = TextUtils.isEmpty(time) ? "少于一分钟": time; - String distTime=String.format(format,Utils.getFormatedDistance(distance) ,time ); - // // QLog.getLogger().dLog(TAG,TAG, distTime); - speachNav(distTime,1); - - } - private String getTurnDesc(float leftDist,String targetTurn){ - return (leftDist>MIN_TURN_DIST)?String.format("前行%s ,%s", Utils.getFormatedDistance(leftDist),targetTurn):targetTurn; - - } - private void speakRoadBook(Waypoint_bean targetWb,String nextRoodbook){ - // // QLog.getLogger().dLog(TAG,TAG, " distance is:" +app.getRecordingTrack().getTrackBean().getDistance()); - // // QLog.getLogger().dLog(TAG,TAG, " Now it is the time for Speak:" +nextRoodbook); - - if(/*isWrongWayAlert*/!isNaviGood())return; -// if(isFirstWaypoint)return; -// if(wrongDirectionCnt>0)return; - - if(targetWb.getSumDist()==0) return; - - speachNav(nextRoodbook,1); - - updateUI(targetWb,targetWb.getRoadBook() ); - lastSay=System.currentTimeMillis(); - } - private void speakTurn(Waypoint_bean targetWb,String targetTurn){ - // // QLog.getLogger().dLog(TAG,TAG, " distance is:" +app.getRecordingTrack().getTrackBean().getDistance()); - // // QLog.getLogger().dLog(TAG,TAG, " Now it is the time for Speak turn right now:" +targetTurn); - - if(/*isWrongWayAlert*/!isNaviGood())return; - if(targetWb.getSumDist()==0) return; -// if(wrongDirectionCnt>0)return; - - updateUI(targetWb,targetTurn); - speachNav(targetTurn,2); - -// if(targetWb.getTurnFlag()==wpFlag.CHECK -// ||targetWb.getTurnFlag()==wpFlag.REST -// ||targetWb.getTurnFlag()==wpFlag.TENT -// ||targetWb.getTurnFlag()==wpFlag.TURNLEFT -// ||targetWb.getTurnFlag()==wpFlag.TURNRIGHT -// ){ -// vibratorAlert(getVibratorPattern(targetWb.getTurnFlag())/*vibratorTurnPattern*/,-1); -// } - if(targetWb.getTurnFlag()!=wpFlag.CUST && targetWb.getTurnFlag()!=wpFlag.NORMAL){ - vibratorAlert(getVibratorPattern(targetWb.getTurnFlag())/*vibratorTurnPattern*/,-1); - } - - - lastSay=System.currentTimeMillis(); - } - long [] getVibratorPattern (wpFlag flag){ - - switch (flag){ - case TURNRIGHT: return new long[]{100,500,100,500}; - case TURNLEFT: return new long[]{200,500,200,500,200,500}; - default :return new long[]{50,300}; - } - - // if(flag==wpFlag.TURNLEFT) {100,500,100,500}; - } - - private void updateUI(Waypoint_bean wb,String msg){ - if(!app.canSendLocation2UI || wb==null)return; - if(wrongWayCnt>1) msg=WRONG_WAY; - Location loc = new Location("nav"); - Bundle bd = new Bundle(); - bd.putString(QiYouConstant.NEW_NAVIFO_MSG, msg); - bd.putInt(QiYouConstant.NEW_NAVIFO_DIST_PROGRESS, (int)(wb.getSumDist()/totalDist*100)); - loc.setExtras(bd); - loc.setLatitude(wb.getLatitude()); - loc.setLongitude(wb.getLongitude()); - app.naviUI(loc, msg); - } - - - - -/* - public boolean addProximityAlert(double lat, double lon,String roadBook, final long eventID, int requestCode) { -// registerReceiver(new ProximityIntentReceiver(), getIntentFilter(requestCode)); - - // // QLog.getLogger().dLog(TAG,TAG, String.format("add new alert to Proximity alert list, lat %s lon %s requestCode %s",lat,lon,requestCode ) ); - return true; - }*/ - - - private void sayByebye(){ - // // QLog.getLogger().dLog(dTAG,TAG + " 导航结束"); - if(!app.playBack){ - speachNav("导航结束",1); - } - } - - private float totalDist=0.001f; - - private void sayHello(){ - String summary=""; - Track gpxTrack; -// speachNav("导航开始, "+"导航路径ID " +app.naviTrackId ); -// speachNav("导航开始" ); - if(app.naviTrackId>0){ - gpxTrack=app.getTrackCache().get(app.naviTrackId); - if(gpxTrack==null)return; - float spd=app.getAVS(); - spd=spd>0?spd:16; - - String time = Utils.getTimeCnt4Read((long) ((gpxTrack.getTrackBean().getDistance()/ ( spd/*getAvs()*/ /*app.getAVS()*//3.6))*1000l) , false); - time = TextUtils.isEmpty(time) ? "少于一分钟": time; - - summary=String.format("路线%s,%s。", - gpxTrack.getTrackBean().getName(), - gpxTrack.getGpxDistTime()+ - String.format("预计历时%s。", time) - ); - - totalDist+=gpxTrack.getTrackBean().getDistance(); - } - else{ - speachNav("导航轨迹加载错误",1); - sayByebye(); - exitNav(); - } - /* - for(Integer i:app.getGpxShowingTracks()){ - gpxTrack=app.tracks_cached.get(i); - // if(gpxTrack!=null) - // dist+=gpxTrack.getTrackBean().getDistance(); - summary+= String.format("路线%s,%s。", - gpxTrack.getTrackBean().getName(), - gpxTrack.getGpxDistTime() - ); - totalDist+=gpxTrack.getTrackBean().getDistance(); - }*/ - - String pref = app.playBack ? "" : "导航开始"; - speachNav( pref + summary,0); - // String sumary =String.format("路程全长%s公里,预计时间", args) - lastSay=System.currentTimeMillis(); - // // QLog.getLogger().d(dTAG,TAG + " 导航开始"); - - } - - @Override - public void onDestroy() { - // // QLog.getLogger().dLog(dTAG,TAG + "naviSvc Services onDestory"); -// Log.i(dTAG,TAG + " ------------------------------------------------------Navi Services onDestory"); - if(vibrator!=null){ - vibrator.cancel(); - } - app.naviTrackId=-1; - app.isNaving=false; - sayByebye(); - - } - - - public boolean isFromLast() { - return mIsFromLast; - } - - - public void setFromLast(boolean mIsFromLast) { - this.mIsFromLast = mIsFromLast; - } - private long lastSay=0; - private String HI="导航进行中"; - private void sayHi(){ - - if(System.currentTimeMillis() -lastSay>5*60*1000){ - if(isNaviDone()){ - // // QLog.getLogger().dLog(TAG,TAG + " to exit navigation"); - exitNav(); - } - speachNav(HI,0); - lastSay=System.currentTimeMillis(); - } - } - - private boolean isNaviDone(){ - - if(app.isNavPaused){ - speachNav("导航暂停",1); - } - - while(app.isNavPaused){ - try { - Thread.sleep(3000); -// updateUI(null,"导航暂停"); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -// // // QLog.getLogger().dLog(TAG, " navi track id "+ naviId +", app.naviTrackId " +app.naviTrackId); - if(app.naviTrackId !=naviId){ - // // QLog.getLogger().dLog(TAG, " navi need to be stoped."); - this.stopSelf(); - return true; - } - - - boolean isRecording =app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.RECORDING; - isRecording =isRecording ||app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.PAUSED; - boolean isPlayback =app.playBack && !app.playBackStopped; - // // QLog.getLogger().dLog(TAG, String.format("checkStatus: isRecording :%s,isPlayback:%s,app.isNaving: %s",isRecording,isPlayback,app.isNaving)); - boolean isExit =!(isRecording || isPlayback) || !app.isNaving; - - - if(isExit) - exitNav(); - else - return false; - - return !(isRecording || isPlayback) || !app.isNaving; - } -private void speachNav(String words,int priority){ - if(QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2) - app.speech(words,priority); - -} - - - - private void getChkWps(){ - - new Thread(){ - - @Override - public void run() { - Track gpxTrack=null; - long starttime=System.currentTimeMillis(); -// HashMap wps = new HashMap(); -// checkWps = new HashMap(); - checkWps = new HashMap(); -// Location loc; -// // // QLog.getLogger().dLog(TAG, String.format("chkwps: lat begin......................")); -// int wpsCnt=0; - if(app.naviTrackId>0){ - app.setLastNavId(); -// gpxTrack=app.tracks_cached.get(app.naviTrackId); - gpxTrack=app.getTrackCache().get(app.naviTrackId); - if(gpxTrack!=null){ -// for(Waypoint_bean wb:gpxTrack.getTrackBean().getTrkseg()){ - Waypoint_bean wb; - Waypoint_bean nextWb = null; - float nextd=0; - for(int i=0;i=startWb.getTime() && wb.getTime()<=targetWb.getTime() || - wb.getSumDist()>=startWb.getSumDist() && wb.getSumDist()<=targetWb.getSumDist()){*/ - -// // // QLog.getLogger().dLog(TAG, String.format("chkwps: lat-lng: %s",getStringKey(wb.getLatitude() ,wb.getLongitude()))); - String key=getStringKey(wb.getLatitude() ,wb.getLongitude()); - nextd=0; - if(i500){ - insertMoreKeys(wb,nextWb); - }else - if(!checkWps.containsKey(key) || checkWps.get(key)[0]targetWb.getTime() || wb.getSumDist()>targetWb.getSumDist()){ - break; - }*/ - } - } - - /* avDist =(targetWb.getSumDist() - startWb.getSumDist())/wpsCnt;*/ - if(checkWps.keySet()!=null && checkWps.keySet().size()>0) - avDist =(gpxTrack.getTrackBean().getDistance())/checkWps.keySet().size(); - QLog.getLogger().dLog(TAG, "build chkwps cost time:(s) " +(System.currentTimeMillis()-starttime)/1000); - QLog.getLogger().dLog(TAG, " build wps size: " +checkWps.keySet().size()); - QLog.getLogger().dLog(TAG, String.format(" track wps size: %s ,check key size %s,avDist: %s " ,gpxTrack.getTrackBean().getTrkseg().size(),checkWps.keySet().size(),avDist)); - - minDistPlus =/*(avDist/100f)**/avDist; - } - - - - } - - - }}.start(); - - } - - - - - void insertMoreKeys(Waypoint_bean wb,Waypoint_bean nextWb){ - - Waypoint_bean midWb = new Waypoint_bean(); - - midWb.setLatitude((wb.getLatitude()+nextWb.getLatitude())/2); - midWb.setLongitude((wb.getLongitude()+nextWb.getLongitude())/2); - midWb.setSumDist(wb.getSumDist()+(nextWb.getSumDist()-wb.getSumDist())/2); - - String key=getStringKey(midWb.getLatitude() ,midWb.getLongitude()); - float nextd = (float)Utils.getDistanceFromXtoY(wb.getLatitude(), wb.getLongitude(), - midWb.getLatitude(),midWb.getLongitude()); - - QLog.getLogger().dLog(TAG, String.format(" add mid wb key 0: %s, sumdist %s,nextd %s " , key,wb.getSumDist(),nextd)); - - - - if(nextd<500 && nextd>100 && (!checkWps.containsKey(key) || checkWps.get(key)[0] =300){ - - insertMoreKeys(wb,midWb ); - } - - Waypoint_bean midWb2 = new Waypoint_bean(); - midWb2.setLatitude((midWb.getLatitude()+nextWb.getLatitude())/2); - midWb2.setLongitude((midWb.getLongitude()+nextWb.getLongitude())/2); - midWb2.setSumDist(midWb.getSumDist()+(nextWb.getSumDist()-midWb.getSumDist())/2); - - - key=getStringKey(midWb2.getLatitude() ,midWb2.getLongitude()); - - nextd = (float)Utils.getDistanceFromXtoY(midWb.getLatitude(),midWb.getLongitude() - ,midWb2.getLatitude(), midWb2.getLongitude()) ; - - - QLog.getLogger().dLog(TAG, String.format(" add mid wb key 2: %s, sumdist %s,nextd %s " , key,wb.getSumDist(),nextd)); - - if(nextd<500 && nextd>100 &&(!checkWps.containsKey(key) || checkWps.get(key)[0]=300){ - - insertMoreKeys(midWb, midWb2); - } - - nextd = (float)Utils.getDistanceFromXtoY(midWb2.getLatitude(),midWb2.getLongitude() - ,nextWb.getLatitude(), nextWb.getLongitude()) ; - - if(nextd<5000 && nextd>=300){ - - insertMoreKeys(midWb2, nextWb); - } - - } - - - private String getStringKey(float lat,float lng){ - float rd=app.rd;//500f; - String rt=Math.round((lat*rd))/ rd +"-"+ Math.round((lng*rd))/ rd; - -// String rt=Math.round((lat*app.rd))/app.rd +"-"+ Math.round((lng*app.rd))/app.rd; -// // // QLog.getLogger().dLog(TAG, String.format("chkwps: lat +lng:%s",rt)); - return rt; -} - - private void vibratorAlert(long [] pattern,int repeatCnt ){ - - if(vibrator!=null && !QiYouConstant.PV_BL_NAVI_VIBRATOR_ON)return; - -// long [] pattern = {100,400,100,400}; // 停止 开启 停止 开启 - vibrator.cancel(); - vibrator.vibrate(pattern,repeatCnt); //重复两次上面的pattern 如果只想震动一次,index设为-1 - - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/TimtickService.java b/qy/src/main/java/com/qiyou/mb/android/service/TimtickService.java deleted file mode 100644 index 3e8f463..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/TimtickService.java +++ /dev/null @@ -1,807 +0,0 @@ -package com.qiyou.mb.android.service; - -import java.lang.reflect.Method; - -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.receivers.TimeTickReceiver; -import com.qiyou.mb.android.ui.MainActivity; -import com.qiyou.mb.android.ui.Welcome; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.log.QLog; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.os.Bundle; -import android.os.Handler; -import android.os.IBinder; -import android.os.Looper; -import android.os.PowerManager; -import android.util.Log; - - -import java.lang.reflect.InvocationTargetException; - - - -public class TimtickService extends Service /*implements Runnable*/ { - public final static String TAG = "com.qiyou.TimtickService"; - public static final String dTAG = "com.qiyou"; - Notification mNotification ; - NotificationManager mNotificationManager; - int NOTIFICATION_ID=1; - - int updateStaticsCnt=0; - final int GPS_REQUEST_MINUTES=5; - - TimeTickReceiver timeTickReceiver; - @Override - public IBinder onBind(Intent arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void onStart(Intent intent, int startId) { -//// QLog.getLogger()().d(dTAG,TAG+"... service TimtickService onStart.....," ); - if(intent!=null) - handleIntent(intent); - startAndroidGPSRequest(); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId){ - // QLog.getLogger().d(dTAG,TAG+"... service TimtickService onStartCommand.....," ); - handleIntent(intent); - // We want this service to continue running until it is explicitly - // stopped, so return sticky. - return START_STICKY; - } - - Handler mHandler; - long registTime=0; - protected QiYouApplication app; - @Override - public void onCreate(){ - /*mHandler = new Handler(Looper.getMainLooper()); - mHandler.post(this);*/ - super.onCreate(); - QLog.getLogger().d(dTAG,TAG+"... service TimtickService onCreate.....," ); - app = (QiYouApplication) this.getApplication(); - if(!app.isLastTrackExist()){ - // QLog.getLogger().d(dTAG,TAG+" no exist recording track exist,TimtickService return .............." ); - return; - - } - if(app.isRouting)return;//路书不需要启动下面 - - getForegroundMethod(); - try{ - setUpAsForeground("触摸可显示小驴子",Welcome.class); - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - - } -// setUpAsForeground("触摸可显示小驴子",MainActivity.class); - timeTickReceiver =new TimeTickReceiver(); - regTimeTick(); - acquireWakeLock(); - } - - - - - void regTimeTick(){ - IntentFilter javaFilter = new IntentFilter(); - javaFilter.addAction("android.intent.action.TIME_TICK"); - registerReceiver(timeTickReceiver, javaFilter); - registTime =System.currentTimeMillis(); - String debugstring=" TimtickService Time Tick regist at: " - + Utils.getFormatedTime( registTime) - + ", Application instance start time is:" - + Utils.getFormatedTime( app.startTime ) - + ",Time past:"+Utils.getTimeCnt( app.startTime -registTime,true); -//QLog.getLogger().d(dTAG,TAG+ debugstring); -//Utils.logStackTrace(new Exception(debugstring),dTAG); - QLog.getLogger().dLog( TAG, debugstring); - - } - - void unregTimeTick(){ - - unregisterReceiver(timeTickReceiver); - } - - private void setUpAsForeground(String text,Class cls) { - - Intent intent=new Intent(getApplicationContext(), cls); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.putExtra("noani", "1"); - PendingIntent pendingIntent = PendingIntent.getActivity( - getApplicationContext(), 0,/* new Intent(getApplicationContext(), cls)*/intent, PendingIntent.FLAG_UPDATE_CURRENT); - mNotification = new Notification(); - mNotification.tickerText = text; - mNotification.icon = R.drawable.ic_launcher;// TODO 更换服务前置的图标 - mNotification.flags = Notification.FLAG_ONGOING_EVENT; - -// mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - // mNotification.setLatestEventInfo(getApplicationContext(), "运动中", text, pendingIntent); - - /* Notification noti = new Notification.Builder(this) - .setContentTitle("运动中") - .setContentText("运动中") - .setSmallIcon(R.drawable.ic_launcher) -// .setLargeIcon(R.drawable.ic_launcher) - .build();*/ - - -// startForeground(NOTIFICATION_ID, mNotification); - startForegroundCompat(NOTIFICATION_ID, mNotification); - } - - - void handleIntent(Intent intent){ - - //to check if the application restart with new instances or not - // The check result is, the new application instance created, the original referenced application still exits. - - //TODO: to find what cause creating new application instances? - if(intent==null)return; - - /*if(QiYouApplication.lockStatic==null){ - QLog.getLogger().dLog( TAG ," lockStatic is null"); - }else{ - QLog.getLogger().dLog( TAG ," lockStatic.isHeld():"+QiYouApplication.lockStatic.isHeld()); - }*/ - - if(app.isLastTrackExist() - &&(QiYouApplication.lockStatic==null || !QiYouApplication.lockStatic.isHeld())){ - - getForegroundMethod(); - try{ - setUpAsForeground("触摸可显示小驴子",Welcome.class); - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - - } - // setUpAsForeground("触摸可显示小驴子",MainActivity.class); - if(timeTickReceiver==null) - timeTickReceiver =new TimeTickReceiver(); - else{ - unregTimeTick(); - } - - regTimeTick(); - - acquireWakeLock(); - } - - String key = QiYouConstant.EXTRA_KEY_START_GPS; - if (intent.hasExtra(key)){ - startAndroidGPSRequest(); - return; - } - key = QiYouConstant.EXTRA_KEY_STOP_GPS; - if (intent.hasExtra(key)){ - stopAndroidGPSRequest(); - return; - } - - key = QiYouConstant.EXTRA_KEY_TICK_UPDATE; - - if (intent.hasExtra(key)) { - QLog.getLogger().dLog(dTAG, TAG + " get notice to check gps.................., allower to update? QiYouConstant.PV_BL_SAVE_POWER: "+QiYouConstant.PV_BL_SAVE_POWER); - - if(QiYouConstant.PV_BL_SAVE_POWER){ - updateGPSstatus(); - } - - - - updateStaticsCnt++; - if( updateStaticsCnt%3==0){ //do it on each 3 minutes - // QLog.getLogger().dLog( TAG, " begin to update statistics, updateStaticsCnt: "+updateStaticsCnt +"updateStaticsCnt%3="+updateStaticsCnt%3); - updateStaticsCnt=0; - app.updateStatistics(); //update recording data into statistics. - - } - return; - } - - - } - - - - private static final Class[] mSetForegroundSignature = new Class[] { - boolean.class}; - private static final Class[] mStartForegroundSignature = new Class[] { - int.class, Notification.class}; - private static final Class[] mStopForegroundSignature = new Class[] { - boolean.class}; - - private NotificationManager mNM; - private Method mSetForeground; - private Method mStartForeground; - private Method mStopForeground; - private Object[] mSetForegroundArgs = new Object[1]; - private Object[] mStartForegroundArgs = new Object[2]; - private Object[] mStopForegroundArgs = new Object[1]; - - void invokeMethod(Method method, Object[] args) { - try { - method.invoke(this, args); - } catch (InvocationTargetException e) { - // Should not happen. - Log.w(dTAG, "Unable to invoke method", e); - } catch (IllegalAccessException e) { - // Should not happen. - Log.w(dTAG, "Unable to invoke method", e); - } - } -boolean isForeground=false; - /** - * This is a wrapper around the new startForeground method, using the older - * APIs if it is not available. - */ - void startForegroundCompat(int id, Notification notification) { - // If we have the new startForeground API, then use it. - isForeground=true; - if (mStartForeground != null) { - mStartForegroundArgs[0] = Integer.valueOf(id); - mStartForegroundArgs[1] = notification; - invokeMethod(mStartForeground, mStartForegroundArgs); - return; - } - - // Fall back on the old API. - mSetForegroundArgs[0] = Boolean.TRUE; - invokeMethod(mSetForeground, mSetForegroundArgs); - mNM.notify(id, notification); - - } - - /** - * This is a wrapper around the new stopForeground method, using the older - * APIs if it is not available. - */ - void stopForegroundCompat(int id) { - isForeground=false; - // If we have the new stopForeground API, then use it. - if (mStopForeground != null) { - mStopForegroundArgs[0] = Boolean.TRUE; - invokeMethod(mStopForeground, mStopForegroundArgs); - return; - } - - // Fall back on the old API. Note to cancel BEFORE changing the - // foreground state, since we could be killed at that point. - if(mNM==null)return; - mNM.cancel(id); - mSetForegroundArgs[0] = Boolean.FALSE; - invokeMethod(mSetForeground, mSetForegroundArgs); - } - - - public void getForegroundMethod() { - mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); - try { - mStartForeground = getClass().getMethod("startForeground", - mStartForegroundSignature); - mStopForeground = getClass().getMethod("stopForeground", - mStopForegroundSignature); - return; - } catch (NoSuchMethodException e) { - // Running on an older platform. - mStartForeground = mStopForeground = null; - } - try { - mSetForeground = getClass().getMethod("setForeground", - mSetForegroundSignature); - } catch (NoSuchMethodException e) { - throw new IllegalStateException( - "OS doesn't have Service.startForeground OR Service.setForeground!"); - } - } - - void updateGPSstatus() { - QLog.getLogger().dLog(dTAG, TAG + " app.isLastTrackExist():" +app.isLastTrackExist()); - if(!app.isLastTrackExist() ||app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.PAUSED)return; - - if (app.canSendLocation2UI &&System.currentTimeMillis() -app.lastLocationTime> app.getGPS_REQUEST_SPAN()*2) { -// if (!app.playBack) { -// broadcastIntent = new Intent(this, LocationMornitorService.class); // monitor the location - // change //change it to fragment - startService( new Intent(this, LocationMornitorService.class)); -// QLog.getLogger().d(dTAG, TAG + " start MORNITOR_LOCATION_SERVICE by ACTION_TIME_TICK."); - // QLog.getLogger().dLog( TAG, "start MORNITOR_LOCATION_SERVICE by ACTION_TIME_TICK."); -// } - } - -// QLog.getLogger().dLog( TAG , " app.isLostGps()? "+app.isLostGps()); - -// QLog.getLogger().d(dTAG, TAG -// + String.format(" app.isLostGps()?%s, app.isGPSstopped?%s,app.lastGpsStopTime?%s,app.lastGpsStartTime?%s" -// ,app.isLostGps(), app.isGPSstopped ,app.lastGpsStopTime ,app.lastGpsStartTime )); -// -// QLog.getLogger().dLog( TAG, String.format(" app.isLostGps()?%s, app.isGPSstopped?%s,app.lastGpsStopTime?%s,app.lastGpsStartTime?%s" -// ,app.isLostGps(), app.isGPSstopped ,Utils.getFormatedTime(app.lastGpsStopTime) ,Utils.getFormatedTime(app.lastGpsStartTime ))); - -// if (app.playBack && !app.isLostGps()) { -// app.stopAndroidGPSRequest(); -// return; -// } - - if (app.isLastTrackExist()) { - if(app.getExistTrackingID()>app.getRecordingTrack().getTrackBean().getTrackId()) - app.restoreLastTracking(); - } - -// boolean lostGPS = app.lastOfftime > 0; - // QLog.getLogger().dLog(dTAG, TAG + " app.isLostGps():" +app.isLostGps()); - if (app.isLostGps()) { -// if (app.lastGpsChkTime == 0) -// app.lastGpsChkTime = System.currentTimeMillis(); - app.GPS_SPAN_FACTOR =1; - -// QLog.getLogger().dLog( dTAG ,TAG+" System.currentTimeMillis() - app.startTime: " + Utils.getTimeCnt((System.currentTimeMillis() - app.startTime))); -// -// QLog.getLogger().dLog( dTAG ,TAG+" QiYouConstant.MAX_GPS_OFF_TIME : " + QiYouConstant.MAX_GPS_OFF_TIME ); -// -// QLog.getLogger().dLog(dTAG, TAG+"System.currentTimeMillis() - app.startTime< QiYouConstant.MAX_GPS_OFF_TIME " +(System.currentTimeMillis() - app.startTime< QiYouConstant.MAX_GPS_OFF_TIME )); -// QLog.getLogger().dLog(dTAG, TAG+"app.lastGpsStopTime>0 &&(app.startTime - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME) " +(app.lastGpsStopTime>0 &&(app.startTime - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME))); - - - - if( System.currentTimeMillis() - app.startTime< QiYouConstant.MAX_GPS_OFF_TIME - ||app.lastGpsStopTime>0 &&(app.startTime - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME)){ - -// QLog.getLogger().dLog( TAG ," System.currentTimeMillis() - app.startTime: " -// + Utils.getTimeCnt((System.currentTimeMillis() - app.startTime))); -// -// QLog.getLogger().dLog( TAG ," app.startTime - app.lastGpsStopTime: " -// + Utils.getTimeCnt((app.startTime - app.lastGpsStopTime))); - if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2) - app.speech("正在进行卫星定位",0); -// app.startAndroidGPSRequest(); - startAndroidGPSRequest(); - // QLog.getLogger().dLog( dTAG ,TAG+" Start the GPS request on the restart after app start if it is not started.) "); - return; - } - - - // QLog.getLogger().dLog(dTAG, TAG + " app.isGPSstopped:" + app.isGPSstopped); - if (app.isGPSstopped) { - -// QLog.getLogger().dLog( TAG ," System.currentTimeMillis() - app.lastGpsStopTime: " -// + Utils.getTimeCnt((System.currentTimeMillis() - app.lastGpsStopTime))); - startAndroidGPSRequest(); //after stopped for 1 minute,start it again -// QLog.getLogger().dLog( TAG ," app.isGPSstopped ? "+app.isGPSstopped -// + " startAndroidGPSRequest by timeStickService service."); - /*if (System.currentTimeMillis() - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME*0.8) { - startAndroidGPSRequest(); - QLog.getLogger().dLog( TAG ," app.isGPSstopped ? "+app.isGPSstopped - + " startAndroidGPSRequest by timeStickService service."); - }*/ - - } else { - - - // QLog.getLogger().dLog( dTAG ,TAG+" System.currentTimeMillis() - app.lastGpsStartTime > QiYouConstant.MAX_GPS_OFF_TIME * 5 " +(System.currentTimeMillis() - app.lastGpsStartTime > QiYouConstant.MAX_GPS_OFF_TIME * 5)); - // QLog.getLogger().dLog( dTAG ,TAG+" System.currentTimeMillis() - app.lastGpsStartTime " + Utils.getTimeCnt((System.currentTimeMillis() - app.lastGpsStartTime))); - - if( app.getRecordingTrack().getTrackBean().getTrackId() == 0 //app.gpsStartTime==0 //no gps ever got - &&(System.currentTimeMillis() - app.lastGpsStartTime > QiYouConstant.MAX_GPS_OFF_TIME * 5)//if the interval since last start is long enough,then to start again. - || //or got gps ever, but stopped for saving power -// app.lastGpsStartTime ==0 - app.lastGpsStopTime>0 - &&(System.currentTimeMillis() - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME) // interval since last stopped ,stop 1 minute for saving power. - - || app.lastGpsStopTime==0 && app.lastGpsStartTime ==0 //first time lostgps/stopped since last connected to gps. - - ){ -// app.startAndroidGPSRequest(); - startAndroidGPSRequest(); -// app.lastGpsStopTime =0; -// app.lastGpsStartTime = System.currentTimeMillis(); -// QLog.getLogger().dLog(TAG ," startAndroidGPSRequest again by timeStickService "); - return; - } - - -// if(app.canRecord() && app.lastGpsChkTime==0){ -// app.startAndroidGPSRequest(); -// -// } - - - /* - if(app.lastGpsStartTime ==0 - &&(System.currentTimeMillis() - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME) ){ - - app.startAndroidGPSRequest(); - app.lastGpsStopTime =0; - app.lastGpsStartTime = System.currentTimeMillis(); - } - */ - - - - long time2stop =QiYouConstant.MAX_GPS_OFF_TIME * GPS_REQUEST_MINUTES;//3; //每请求3分钟,停顿1分钟 -// long time2stop =app.getRecordingTrack().getTrackBean().getTrackId()>0?QiYouConstant.MAX_GPS_OFF_TIME * 2:QiYouConstant.MAX_GPS_OFF_TIME * 10; - - //to stop gps request for saving power. - if( app.getRecordingTrack().getTrackBean().getTrackId()>0 && - !app.canSendLocation2UI - && app.lastGpsStartTime>0 - &&(System.currentTimeMillis() - app.lastGpsStartTime > time2stop)) { //interval since last started,it need big enough to connect to gps. -// app.stopAndroidGPSRequest(); - stopAndroidGPSRequest(); -// app.lastGpsStartTime =0; -// app.lastGpsStopTime =System.currentTimeMillis(); -// QLog.getLogger().dLog(TAG , " stopAndroidGPSRequest by timeStickService."); - } - - - - } - - - }else { - if(app.isNotMoving()){ -// app.stopAndroidGPSRequest(); - // QLog.getLogger().dLog(TAG ," Not moving for long time,stop gps request by timeStickService "); -// QLog.getLogger().dLog(TAG ," Not moving for long time, update the gps_span interverl. "); - -// app.startAndroidGPSRequest(); - startAndroidGPSRequest(); - } - - app.lastGpsStartTime =0; - app.lastGpsStopTime =0; - } - - } - - - //TODO: if the lock is still not working, then put it to applicaiton class, - //lock/release the lock while regist /unregist timeticktservice. - - /* private static volatile PowerManager.WakeLock lockStatic=null; - - synchronized private static PowerManager.WakeLock getLock(Context context) { - if (lockStatic == null) { - PowerManager mgr= - (PowerManager)context.getSystemService(Context.POWER_SERVICE); - - lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); - lockStatic.setReferenceCounted(true); - } - - return(lockStatic); - } - */ - -// PowerManager.WakeLock wakeLock; -private void acquireWakeLock() { - /* if (wakeLock ==null) { - QLog.getLogger().dLog(TAG, " Acquiring wake lock"); - PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); - wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock"); - wakeLock.acquire(); - - }*/ - PowerManager.WakeLock lock=QiYouApplication.getLock(this.getApplicationContext()); - - if (!lock.isHeld()){ - lock.acquire(); -// QLog.getLogger().dLog(TAG, " Acquired wake lock"); - } - - } - - -private void releaseWakeLock() { - /*if (wakeLock !=null&& wakeLock.isHeld()) { - wakeLock.release(); - wakeLock =null; - // // QLog.getLogger().dLog(TAG, " Released wake lock"); - }*/ - PowerManager.WakeLock lock=QiYouApplication.getLock(this.getApplicationContext()); - - if (lock.isHeld()){ - lock.release(); - // QLog.getLogger().dLog(TAG, " Released wake lock"); - } - } - - - - - - - - LocationManager lm; - void startAndroidGPSRequest(){ - - if(app.getRecordingTrack().getTrackBean().getStatus() == TrackStatus.PAUSED) return; - - app.startNetworkLocationRequest(false);//先开启网络定位,收到gps信号后姜自动关闭网络定位 - - /* while(!Utils.isGpsEnabled(this)){ - try { - Thread.sleep(QiYouConstant.MAX_GPS_SPAN*5); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - app.speech("请开启手机卫星定位"); - } - */ - -// if(!Utils.isGpsPermited(this)){ -// if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2) -// app.speech(R.string.GPSNotPermited,1); -// }else - if(!Utils.isGpsEnabled(this)){ - if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2){ - app.speech("请开启手机卫星定位",1); - } - - return; - } -// if(!getGpsState(this)); -// { -// //TODO: let user to toggle the GPS on. -// } - if(lm==null)lm =app.lm;// (LocationManager)getSystemService(Context.LOCATION_SERVICE); - - if(!QiYouConstant.PV_BL_SAVE_POWER){ - app.GPS_SPAN_FACTOR=1; - } - - - -// canRecord =true; -// lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR,0, locationListenerPendingIntent); - lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR,0, listener, Looper.getMainLooper()); - // QLog.getLogger().dLog(dTAG, TAG+" QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR: " + QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR); - app.isGPSstopped =false; - app.lastGpsStopTime=0; - app.lastGpsStartTime = System.currentTimeMillis(); - // QLog.getLogger().dLog(dTAG, TAG+" TimtickService startAndroidGPSRequest"); - } - - - void stopAndroidGPSRequest(){ -// Log.d(dTAG,TAG + " stopping gps request "); - if(lm!=null){ -// lm.removeUpdates(locationListenerPendingIntent); - lm.removeUpdates(listener); -// Log.i(dTAG,TAG + " stopped gps request "); - } - app.isGPSstopped =true; - app.lastGpsStartTime =0; - app.lastGpsStopTime =System.currentTimeMillis(); -// this.canRecord =!this.playBack; - if(!app.canRecord()){ - app.cancelForceDbAlarm(); - } -// QLog.getLogger().dLog(TAG," TimtickService stopAndroidGPSRequest"); - -// Intent serviceIntent = new Intent(this, LocationService.class); -// stopService(serviceIntent); -// serviceIntent.putExtra(QiYouConstant.STOP_LOCATION_SERVICE, true); -// startService(serviceIntent); - } - - @Override - public void onDestroy() { - /* mHandler.removeCallbacks(this); */ - - if(registTime==0 && app.isRouting){ - stopAndroidGPSRequest(); - return; - } - if(registTime!=0){ - unregTimeTick(); - } - // Make sure our notification is gone. - if(isForeground) - stopForegroundCompat(NOTIFICATION_ID); -// QLog.getLogger().dLog(dTAG,TAG+"... service TimtickService onDestroy.....," ); - stopAndroidGPSRequest(); - releaseWakeLock(); - } -// boolean isMaxProcessed; - Location lastLocation; - private LocationListener listener = new LocationListener() { - - @Override - public void onLocationChanged(Location location) { - // TODO Auto-generated method stub - -// Log.e("Google", "Location Changed"); - - if (location == null) - return; - - app.lastLocationTime =System.currentTimeMillis(); - - if(location.getAccuracy()>30 || location.getSpeed()<0.25){ - if(location.getSpeed()>0){ -// QLog.getLogger().dLog(TAG," loacation accuracy:" +location.getAccuracy()); -// QLog.getLogger().dLog(TAG," loacation speed:" +location.getSpeed()); - location.setSpeed(0f); - } -// return; - } - - lastLocation= lastLocation ==null?(location):lastLocation; - if(location.getSpeed() >0 ||QiYouConstant.DEVELOPER_MODE){ - //to filter out the suddenly high speed. - - String pearTag="PEARTAG"; -/* QLog.getLogger().d(dTAG, " PEARTAG get location change notice.................---------------------------------------------------"); - QLog.getLogger().d(dTAG, " PEARTAG location.getSpeed() " +location.getSpeed()); - QLog.getLogger().d(dTAG, " PEARTAG lastLocation.getSpeed() " +lastLocation.getSpeed()); - QLog.getLogger().d(dTAG, " PEARTAG app.getRecordingTrack().getTrackBean().getTopSpeed() " +app.getRecordingTrack().getTrackBean().getTopSpeed()/3.6); - QLog.getLogger().d(dTAG, " PEARTAG location.getTime() -lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN " +(location.getTime() -lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN )); - QLog.getLogger().d(dTAG, " PEARTAG location.getTime() -lastLocation.getTime() " +(location.getTime() -lastLocation.getTime())); - QLog.getLogger().d(dTAG, " PEARTAG 2*app.getRecordingTrack().getTrackBean().getAvs()/3.6 " +2*app.getRecordingTrack().getTrackBean().getAvs()/3.6); -*/ if(lastLocation!=null - && ( lastLocation.getSpeed()>0 && location.getSpeed()>2*lastLocation.getSpeed() - || lastLocation.getSpeed()==0 - && ( app.getRecordingTrack().getTrackBean().getTopSpeed()>0 - && location.getSpeed()>app.getRecordingTrack().getTrackBean().getTopSpeed()/3.6 - || app.getRecordingTrack().getTrackBean().getTopSpeed()==0 - && location.getSpeed()*3.6>30 - ) - ) - && location.getTime() -lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN - && location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6){ - - /*QLog.getLogger().dLog(TAG,pearTag, " Get one peak point!-------"); - QLog.getLogger().dLog(TAG,pearTag, " location.getSpeed() "+location.getSpeed()*3.6); - QLog.getLogger().dLog(TAG,pearTag, " app.lastLocation.getSpeed() "+lastLocation.getSpeed()*3.6); - QLog.getLogger().dLog(TAG,pearTag, " 2*app.getRecordingTrack().getTrackBean().getAvs() "+ 2*app.getRecordingTrack().getTrackBean().getAvs() ); - */ - return; - - } - } - - - - - - if(app.lastSavedLocation==null)app.lastSavedLocation=location; - -// QLog.getLogger().d(dTAG, TAG+" gps locaiton change Receiver got noticed, and sending to locationService."); -// // QLog.getLogger().dLog(TAG," gps locaiton change Receiver got noticed "); -// QLog.getLogger().dLog(TAG," Location Receiver got the new location"); -// -// Log.e(TAG, "GPS time:" +Utils.getFormatedTime(location.getTime())); - - if(app.getRecordingTrack().getTrackBean().getStatus()== TrackStatus.RECORDING ){ - String key = LocationManager.KEY_LOCATION_CHANGED; - Intent serviceIntent = new Intent(app, LocationService.class); - - /* Bundle bd = new Bundle(); - if(app.lastSavedLocation==null ||app.lastSavedLocation.getTime()==0){ - app.lastSavedLocation=location; - QLog.getLogger().dLog( TAG, " app.lastSavedLocation is null. "); - } - - long diff = location.getTime() - lastLocation.getTime() ; - double sdist; - if( diff <= QiYouConstant.MAX_TIME_UPDATE_DB*10){ - -// sdist = (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastLocation)); - - sdist = Utils.getDistance3(location, lastLocation); -// app.sumDiff+=sdist -Utils.getDistance(location, app.lastSavedLocation) ; - -// QLog.getLogger().dLog(dTAG," currentLoc time "+Utils.getFormatedTime(currentLoc.getTime())); -// QLog.getLogger().dLog(dTAG," app.lastLocation time "+Utils.getFormatedTime(app.lastSavedLocation.getTime())); - -// sdist = (float) (isFirstwp?0:Utils.getDistance(currentLoc, app.lastLocation)); -// sdist = (float) (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastSavedLocation)); -// app.sumDiff+=sdist -Utils.getDistance(currentLoc, app.lastSavedLocation) ; -// QLog.getLogger().dLog(dTAG," app.sumDiff "+app.sumDiff ); - }else{ - sdist=0; //系统暂停或失联gps后恢复,总距离不计入 -// isMaxProcessed=true; - QLog.getLogger().dLog(TAG,"Caution! -------------------------------------- 系统暂停或失联gps后恢复,总距离不计入 , MAX_TIME_UPDATE_DB is" +QiYouConstant.MAX_TIME_UPDATE_DB +" ,diff is" +diff ); - - } - - - - if (Math.round(app.sumDist) == 0 || Double.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - app.sumDist2 = app.getRecordingTrack().getTrackBean() - .getDistance(); - } - if (Math.round(app.sumDist) == 0 || Double.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN - ) { - Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist); - QLog.getLogger().dLog(TAG," Distance is NaN? app.sumDist: " + app.sumDist); - app.sumDist2 = 0; - } - - app.sumDiff2+=sdist -Utils.getDistance(location, lastLocation) ; - QLog.getLogger().dLog(TAG," app.sumDiff2 " + app.sumDiff2); - app.sumDist2+=sdist; - bd.putDouble("sumdist", app.sumDist2); - location.setExtras(bd);*/ -// location.getExtras().put - - - serviceIntent.putExtra(key, location); - startService(serviceIntent); - - - - lastLocation=location; - } - -// QLog.getLogger().dLog(TAG," Location is here 01 "); - if(Utils.canUpdateUI(app)){ - Intent broadcastIntent = new Intent(); - broadcastIntent - .setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, location); - sendBroadcast(broadcastIntent); - } - app.lastNaviLocation= location; - - } - - @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - // TODO Auto-generated method stub - - } - - @Override - public void onProviderEnabled(String provider) { - // TODO Auto-generated method stub - - } - - @Override - public void onProviderDisabled(String provider) { - // TODO Auto-generated method stub - - } - - - }; - /*@Override - public void run() { - // TODO Auto-generated method stub - - }*/ - -} - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/service/TrackDbServiceBackground.java b/qy/src/main/java/com/qiyou/mb/android/service/TrackDbServiceBackground.java deleted file mode 100644 index dd5ce65..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/TrackDbServiceBackground.java +++ /dev/null @@ -1,1794 +0,0 @@ -package com.qiyou.mb.android.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import android.content.ContentValues; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.Statistics; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.CItem; -import com.qiyou.mb.android.beans.basic.GPItem; -import com.qiyou.mb.android.beans.basic.StatTrack; -import com.qiyou.mb.android.beans.basic.Statics_bean; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.TypeStatistics; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.log.QLog; - - -public class TrackDbServiceBackground extends DBservice { - public static String TAG ="com.qiyou.TrackDbServiceBackground"; - -//private final String WHERE_TRACK_AV_STATUS = " ( ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")!=" +TrackAvStatus.DELETED + -// " OR " + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")"; -//private final String WHERE_TRACK_AV_STATUS_NOT_DELETED = " ( ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")=" +TrackAvStatus.DELETED + -//" OR " + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")"; - -private final String WHERE_TRACK_AV_STATUS = TrackProvider.KEY_TRACK_AVSTATUS+" != " + TrackAvStatus.DELETED ; -private final String WHERE_TRACK_AV_STATUS_NOT_DELETED = TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED ; - -private final String WHERE_TYPE_NO_GPX=" and " +TrackProvider.KEY_TRACK_TYPE +"!="+TrackType.GPX; - -public TrackDbServiceBackground() - { - super(TAG); - } - public TrackDbServiceBackground(String name) { - super(name); - // TODO Auto-generated constructor stub - } - - @Override - public void onCreate() { - super.onCreate(); - QLog.getLogger().d(dTAG, TAG+" db service created"); - } - - - String[] newWps =new String[3] ; - @Override - protected void onHandleIntent(Intent intent) { - QLog.getLogger().d(dTAG, TAG+" start to check intent keys...."); - Bundle bd= intent.getExtras(); - for(String key:bd.keySet()){ - QLog.getLogger().d(dTAG, TAG+" get key of " +key); - - } - - -// } - // -// @Override -// protected void onHandleIntent(Intent intent) { - if(intent==null)return; - long bfdbTime = System.currentTimeMillis(); - - - Bundle extras = intent.getExtras(); - String key; - //锟斤拷录锟剿讹拷锟届迹 - key = QiYouConstant.NEW_LOCATION; //recording new waypoints - if (intent.hasExtra(key) ) { -// StringBuilder wps =new StringBuilder(); - - if(app.isRestoreLastTracking &&app.getRecordingTrack().getTrackBean().getTrackId()==0)return; - if ( app.getRecordingTrack().getTrackBean().getStatus() !=TrackStatus.RECORDING)return; - String rdWps ; - @SuppressWarnings("unchecked") - ArrayList locLst = (ArrayList)extras.get(key) ; - if(locLst!=null && locLst.size()>0){ - boolean setLastWpSucceed=false; - int i = 0; - StringBuilder wps =new StringBuilder(); -// QLog.getLogger().d(TAG,"---------------New wps insert db..........................."); - for(String wp :locLst) - { - //Log.e(TAG ,wp); - // app.getRecordingTrack().setLastWp(wp); - if(app.getRecordingTrack().setLastWp(wp)){ - /* wps.append(wp); - wps.append(",");*/ - setLastWpSucceed =true; -// QLog.getLogger().d(TAG,"new wp:" +wp); - } - -// setLastWpSucceed =app.getRecordingTrack().setLastWp(wp)||setLastWpSucceed;//|| app.getRecordingTrack().setLastWp(wp); //add last wp into list of track.track_bean.trkseg. - - } - - if (!app.canRecord()&& !QiYouConstant.DEVELOPER_MODE) return; - - rdWps = app.getRecordingTrack().getRdWpsJson().toString(); - if(setLastWpSucceed){ -// newWps = buildWps(wps.toString(),rdWps,app.getRecordingTrack().newMdWpsJson.toString()); - newWps = buildWps(wps.toString(),"",app.getRecordingTrack().newMdWpsJson.toString()); -// newWps = buildWps(wps.toString(),"','","','"); - persistTrack(app.getRecordingTrack() ); -// QLog.getLogger().d(dTAG,TAG+" wps size: "+ i +" , addNewWayPoints spend time " +String.valueOf((System.currentTimeMillis()-bfdbTime)) ); - - } - - - - - } - return; - } - - - key = QiYouConstant.NEW_GPX_TRACK; - - if (intent.hasExtra(key) ) { - - if(app.getImportedGpx().size()==0)return; - - for(Track tr:app.getImportedGpx()){ - if(tr==null)continue; - if(tr.getTrackBean().getTrackId()>0)continue; - - // QLog.getLogger().d(dTAG,TAG+" "+ " Begin to insert new Gpx to db " ); - -// newWps[0] =tr.getJsonWps().toString(); - if(tr.getTrackBean().getRoadWps().size()>0){ - tr.setBearWps(tr.getTrackBean().getRoadWps()); - } - - // QLog.getLogger().d(dTAG,TAG+" "+ " =tr.getRdWpsJson() " +tr.getRdWpsJson() ); - - newWps[1] =tr.getRdWpsJson().toString(); -// newWps[2] =tr.newMdWpsJson.toString(); - newWps[2] =Utils.getGsonString(tr.getTrackBean().getMdWps()); - persistTrack(tr); - - /* for(Waypoint_bean wb1:tr.getTrackBean().getRoadWps()){ - - QLog.getLogger().d(dTAG, "4 cust wp turn flag" + wb1.getTurnFlag().toCHString()); - } */ - } - - newWps =new String[3]; - return; - } - - - key = QiYouConstant.INITIAL_GPXS; - - if (intent.hasExtra(key) ) { - - ArrayList ids =app.getGpxShowingTracks(); - for(int i:ids){ - if(i>0) - this.getTrack(String.valueOf(i)); - } - - return; - } - - key = QiYouConstant.UPDATE_CATE_TRACK; - - if (intent.hasExtra(key) ) { - - HashMap> ids =app.getNewCategoryList(); -// QLog.getLogger().d(dTAG, TAG+" begin to add new cates, app.getNewCategoryList().size() "+ids.size()); - if(ids.size()>0){ - this.addNewCateTrack(ids); - } - - ids =app.getDelCategoryList(); - if(ids.size()>0){ - this.delCateTrack(ids); - } - - return; - } - - key = QiYouConstant.UPDATE_TRACK_AVSTATUS; - - - if (intent.hasExtra(key)) { -// if (!app.canRecord()) return; -// int id ;//= extras.getInt(key); - Object obj = extras.get(key); - int id =obj==null?0:Integer.parseInt(obj.toString()); -// if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){ -// updateTrackAvStatus(app.getRecordingTrack() ); -// app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache -// return; -// } - - - if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){ - updateTrackAvStatus(app.getCurrentTrack()); - app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache - } - - return; - } - - - - - - - - key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE; - if (intent.hasExtra(key)) { - if (!app.canRecord()) return; - if(app.getRecordingTrack().getTrackBean().getTrackId()>0 && - app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.RECORDING) { - app.getRecordingTrack().getTrackBean().setOffTime(app.getRecordingTrack().getTrackBean().getOffTime()+app.offtime); -// app.getRecordingTrack().getTrackBean().setPauseTime(app.getRecordingTrack().getTrackBean().getPauseTime()+app.sumPaused); -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: ForceUpdate sportTime:?" + Utils.getTimeCnt( app.getRecordingTrack().getTrackBean().getPauseTime() )); -// QLog.getLogger().d(dTAG, TAG+" MergeTrack: ForceUpdate offTime:?" + Utils.getTimeCnt( app.getRecordingTrack().getTrackBean().getOffTime() )); - - /*long endTime =app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime(); - endTime =System.currentTimeMillis() >endTime?System.currentTimeMillis():endTime+app.offtime+app.sumPaused; //in case,the phone's time is reset to 1970... - app.getRecordingTrack().getTrackBean().setEndTime(endTime); - */ - app.getRecordingTrack().getCalBurn();//calculate calories - - updateTrack(app.getRecordingTrack(),null); - app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache - - } - app.offtime =0; -// app.sumPaused=0; -// app.getStatisticsTrack(app.getRecordingTrack().getTrackBean().getType().toInt()); - return; - } - - /* key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE_STAT; - if (intent.hasExtra(key)) { -// if(app.isUIactive) - getStatisticTracks(100,System.currentTimeMillis(),app.getRecordingTrack().getTrackBean().getType().toInt(),true); //update the statics - return; - }*/ - -// key = QiYouConstant.QUERY_TRACKS; - - //update the current track, for finishing a record,will include the updated roadbears of maxR wp the lastwp. - key = QiYouConstant.UPDATE_TRACK; - if (intent.hasExtra(key)) { -// if (!app.canRecord()) return; -// int id ;//= extras.getInt(key); - Object obj = extras.get(key); - int id =obj==null?0:Integer.parseInt(obj.toString()); - if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){ - updateTrack(app.getRecordingTrack() ,null); - app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache - return; - } - - Track tr= app.getTrackCache().get(Integer.valueOf(id)); - if(tr==null)return; - updateTrack(tr,tr.getTrackBean().getType()==TrackType.GPX?tr.getRdWpsJson().toString():null); - app.getTrackCache().put(id,tr); //update the cache -// app.currentTrack= app.getTrackCache().get(Integer.valueOf(app.getCurrentTrack().getTrackBean().getTrackId())); - app.setCurrentTrack(app.getTrackCache().get(Integer.valueOf(app.getCurrentTrack().getTrackBean().getTrackId()))); - // QLog.getLogger().dLog(dTAG,TAG+" updated track, to merge statistics......"); - app.mStatistics.mergeTrack(tr); -// app.mStatistics.getStatisticsTracks().get(Integer.valueOf(tr.getTrackBean().getType().toInt())).getSbs().put(Integer.valueOf(id), new Statics_bean(tr.getTrackBean())); - - /* if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){ - updateTrack(app.getCurrentTrack(),null); - app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache - return; - }*/ - - -// QLog.getLogger().d(dTAG,TAG+" Current Track UPDATE done."); - return; - } - - - key = QiYouConstant.EXTR_KEY_FINISH_RECORDING; - if (intent.hasExtra(key)) { -// if (!app.canRecord()) return; //as it is for finish current recording, to skip the iscnareocord. -// int id ;//= extras.getInt(key); - Object obj = extras.get(key); - int id =obj==null?0:Integer.parseInt(obj.toString()); - if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){ - updateTrack(app.getCurrentTrack(),app.getCurrentTrack().getRdWpsJson().toString()); - app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache - } -// QLog.getLogger().d(dTAG,TAG+" Current Track UPDATE done."); - return; - } - - key = QiYouConstant.UPDATE_RECORDING_TRACK; //UDPATE TRACK STATUS - if (intent.hasExtra(key)) { - if (!app.canRecord()) return; -// int id = extras.getInt(key); - Object obj = extras.get(key); - int id =obj==null?0:Integer.parseInt(obj.toString()); - if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){ - app.getRecordingTrack().getTrackBean().setOffTime(app.getRecordingTrack().getTrackBean().getOffTime()+app.offtime); - app.getRecordingTrack().getTrackBean().setPauseTime(app.getRecordingTrack().getTrackBean().getPauseTime()+app.sumPaused); - updateTrack(app.getRecordingTrack(),null); - app.offtime =0; - app.sumPaused=0; - } -// QLog.getLogger().d(dTAG,TAG+" UPDATE RECORDING TRACK. UPDATE done."); - return; - } - - key =QiYouConstant.EXTRA_KEY_TRACK_GEOS; - if (intent.hasExtra(key)) { -// HashMap geoWps = (HashMap) intent.getExtras().getSerializable(key); - - // QLog.getLogger().d(dTAG,TAG+" GET KEY EXTRA_KEY_TRACK_GEOS"); - if(app.geoWps!=null){ - - for(int trackId :app.geoWps.keySet()){ - // QLog.getLogger().d(dTAG,TAG+" TO UPDATE GEO DATA..."); - updateWpsGEO(trackId,app.geoWps.get(trackId)); - // QLog.getLogger().d(dTAG,TAG+"UPDATE GEO DATA... DONE"); - } - - } - app.geoWps=null; - QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =false; -// // QLog.getLogger().d(dTAG, TAG+" app.geoWps.size():"+app.geoWps.size() ); - return; - } - - key = QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID; - - //get specified track by id - if (intent.hasExtra(key)) { - String id = extras.get(key).toString();// intent.getStringExtra(key); - -// if(QiYouConstant.DEVELOPER_MODE) bfdbTime = System.currentTimeMillis(); - - getTrack(id); - - // QLog.getLogger().d(dTAG,TAG+" fetch track " + id + "cost time: "+ String.valueOf((System.currentTimeMillis()-bfdbTime))); - - /* if(QiYouConstant.DEVELOPER_MODE) - { - Log.e(TAG+" 锟斤拷取track " + id + "锟斤拷锟狡猴拷时: ",String.valueOf((System.currentTimeMillis()-bfdbTime)) + "锟斤拷锟斤拷"); - // Log.e(TAG + "Current Track GJson String is:",app.getCurrentTrack().toGsonString()); - }*/ -// stopSelf(); - } - - - - //get statistics Tracks - key = QiYouConstant.EXTRA_KEY_GET_STSTICS_TRACKS; - if (intent.hasExtra(key) ) { -// QLog.getLogger().d(dTAG, TAG+ "--------------- get statistics begin at: "+(System.currentTimeMillis())); - -/* if(app.statTrackLoading)return; - app.statTrackLoading=true;*/ - long start=100; - long end= System.currentTimeMillis(); -// int type =QiYouConstant.TRACK_TYPE_BIKE; - int type =Integer.valueOf(extras.get(key).toString()); -// app.TypeStatistics = getStatisticTracks(start,end,type); - if(app.mStatistics==null ||app.mStatistics.getStatisticsTracks()==null && type>=0){ //to get all type's stat.. - type=-100; - } - initialStatistics(start,end,type,false); - /*if(type==-100) - app.mStatistics=new Statistics(); - - getStatisticTracks(start,end,type,false); - getTypeUsedList(); - getLastStatisticsTrack(QiYouConstant.TRACK_NUMBERS_IN_STATISTICS_CHART+1); - getCateTrackList(); - app.statTrackLoading=false;*/ - // QLog.getLogger().d(dTAG, TAG+ "--------------- get statistics cost time: "+(System.currentTimeMillis()-end)); - stopSelf(); -// return; - } - - - - key = QiYouConstant.EXTRA_KEY_UPDATE_WAYPOINTS; - if (intent.hasExtra(key)) { -// if (!app.canRecord()) return; -// int id ;//= extras.getInt(key); - Object obj = extras.get(key); - boolean isMd=extras.getBoolean(QiYouConstant.EXTRA_KEY_IS_MD); - int id =obj==null?0:Integer.parseInt(obj.toString()); - - if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){ - updateWps(app.getRecordingTrack() ,isMd); -// app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache - return; - } - - if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){ - updateWps(app.getCurrentTrack() ,isMd); -// app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache - } -// QLog.getLogger().d(dTAG,TAG+" wp comments UPDATE done."); - return; - } - - key = QiYouConstant.EXTRA_KEY_UPDATE_SVRNOS; - if (intent.hasExtra(key)) { - HashMapids = (HashMap) extras.getSerializable(key); - updateTrackSvrNo(ids); - return; - } - // to update medias after the upload to web. - key = QiYouConstant.EXTRA_KEY_UPDATE_MEDIAS; - if (intent.hasExtra(key)) { - Object obj = extras.get(QiYouConstant.EXTRA_KEY_ID); - int id =obj==null?0:Integer.parseInt(obj.toString()); - - String mdstr=extras.getString(QiYouConstant.EXTRA_KEY_UPDATE_MEDIAS); - // QLog.getLogger().d(dTAG,TAG+" ------------>>>>>>------to update md ------------------" ); - // QLog.getLogger().d(dTAG,TAG + " "+ mdstr); - ContentValues values = new ContentValues(); - values.put(TrackProvider.KEY_TRACK_MDWPS,mdstr); - updateTable(TrackProvider.TRACKS_URI,values, id,null); - return; - } -// app.getTrackCache().put(tb.getTrackId(), tr); - - /*QLog.getLogger().d(dTAG,TAG+" begin to get track of " + id); - Track track= getTrack( id ); - Media tmd =(Media) Utils.getGsonObject(mdstr, Media.class); - QLog.getLogger().d(dTAG,TAG+" to update md:" +mdstr); - String value = track.wps2json(track.getTrackBean().getMdWps()); - - QLog.getLogger().d(dTAG,TAG+" ......old value:" +value); - - for(Waypoint_bean wb:track.getTrackBean().getMdWps()){ - if(wb==null)continue; - for(Media md:wb.getMedias()){ - if(md!=null && md.getUri().equalsIgnoreCase(tmd.getUri())){ - md.setComment(tmd.getComment()); - md.setStatus(tmd.getStatus()); - md.setSvrUri(tmd.getSvrUri()); - updateWps(track ,true); - } - - } - } - value = track.wps2json(track.getTrackBean().getMdWps()); - - QLog.getLogger().d(dTAG,TAG+" ......new value:" +value); - return; - }*/ - - - - - - - } - - private void initialStatistics(long start,long end,int type,boolean isForceUpdate){ - app.statTrackLoading=true; - /*if(type==-100) - app.mStatistics=new Statistics();*/ - getStatisticTracks(start,end,type,false); - getTypeUsedList(); - getGpList(); - getLastStatisticsTrack(QiYouConstant.TRACK_NUMBERS_IN_STATISTICS_CHART+1); - getCateTrackList(); - app.statTrackLoading=false; - app.writeStatiscs(); - String tableName ="TRACKS"; - // QLog.getLogger().d(dTAG, TAG+" before update , getCurrentSeq( ) " +getCurrentSeq("TRACKS")); - // QLog.getLogger().d(dTAG, TAG+" app.mStatistics.getLastTrackId() " +app.mStatistics.getLastTrackId()); - if(getCurrentSeq(tableName)==-1){ - insertSeqId(tableName, app.mStatistics.getLastTrackId()); - }else if(getCurrentSeq("TRACKS")10){//only when the length >10 to update the wps geo info, to provent the wps to be cleared -// values.put(TrackProvider.KEY_TRACK_ROAD_BEARS, geoWps[0]);//TODO: to remove - Track tr = new Track( trackId,false, geoWps[0],null); - tr.saveBearContent(false); - - } - if(geoWps[1]!=null && geoWps[1].length()>10){ - values.put(TrackProvider.KEY_TRACK_START_WP, geoWps[1]); - } - if(geoWps[2]!=null && geoWps[2].length()>10){ - values.put(TrackProvider.KEY_TRACK_LAST_WP, geoWps[2]); - } - if(geoWps[3]!=null && geoWps[3].length()>10){ - values.put(TrackProvider.KEY_TRACK_MAXRD_WP, geoWps[3]); - } - if(geoWps[4]!=null && geoWps[4].length()>0){//network errors cnt - values.put(TrackProvider.KEY_TRACK_GEO_STATUS, geoWps[4]); - } - if(values.size()>0){ - values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis()); - updateTable(TrackProvider.TRACKS_URI,values,trackId,null); - } - - } - - - - - - - - protected void getTrack(String trackId) - { - if(Integer.valueOf(trackId)<=0)return; - Track track =getTrack( Integer.valueOf(trackId)); - if(track!=null){ - app.setCurrentTrack(track); - app.currentTrackId = Integer.valueOf(trackId); - } - else - app.currentTrackId=-1; - // QLog.getLogger().dLog(TAG, " finished get track of "+ trackId ); - - } - - - Track getTrack(int trackId){ - // QLog.getLogger().d(dTAG,TAG+" begin to get track of :"+trackId); - projection = new String[] { - TrackProvider.KEY_TRACK_NAME,TrackProvider. KEY_TRACK_USER_ID,TrackProvider.KEY_TRACK_COMMENT, - TrackProvider.KEY_TRACK_DESC ,TrackProvider.KEY_TRACK_START_WP,TrackProvider.KEY_TRACK_LAST_WP, - TrackProvider.KEY_TRACK_START_TIME,TrackProvider.KEY_TRACK_END_TIME,TrackProvider.KEY_TRACK_DISTANCE, - TrackProvider.KEY_TRACK_EDOWN_DIST, TrackProvider.KEY_TRACK_EUP_DIST, TrackProvider.KEY_TRACK_TOPSPEED, - TrackProvider.KEY_TRACK_SPORT_TIME,TrackProvider.KEY_TRACK_PAUSE_TIME,TrackProvider. KEY_TRACK_CONTENT, - TrackProvider.KEY_TRACK_IS_SETS,TrackProvider.KEY_SVR_NUMBER, TrackProvider.KEY_LAST_UPDATE_TIME, - TrackProvider.KEY_TRACK_STATUS,TrackProvider.KEY_TRACK_OFFTIME ,TrackProvider.KEY_TRACK_GPSSPAN, - TrackProvider.KEY_TRACK_ROAD_BEARS,TrackProvider.KEY_TRACK_MAXRD_WP,TrackProvider.KEY_TRACK_MAXRD, - TrackProvider.KEY_TRACK_MDWPS,TrackProvider.KEY_TRACK_TYPE,TrackProvider.KEY_TRACK_CAL_BURNING, - TrackProvider.KEY_TRACK_CREATOR,TrackProvider.KEY_TRACK_SRC,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_TRACK_CREATE_TIME}; - Track tr = null; - Uri uri = Uri.withAppendedPath(TrackProvider.TRACKS_URI, String.valueOf(trackId)); - Cursor cursor = contentResolver.query(uri, projection, WHERE_TRACK_AV_STATUS_NOT_DELETED, null, null); - - try { - if (cursor!=null && cursor.moveToFirst()) { - -// if( app.getTrackCache().containsKey(Integer.valueOf(trackId))) //check the cache, if exist, then check the timestamp, if timestamp is same,do not read db. - if( app.getTrackCache().get(Integer.valueOf(trackId))!=null) - { - if ( app.getTrackCache().get(Integer.valueOf(trackId)).getTrackBean().getLastdbTime() == cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME))) - { -// app.setCurrentTrack(app.getTrackCache().get(Integer.valueOf(trackId))); - //cursor.close(); -// app.currentTrack =app.getTrackCache().get(Integer.valueOf(trackId)); -// app.currentTrackId = Integer.valueOf(trackId); - // QLog.getLogger().dLog(TAG, "get the track from the cache instead of db. "+ trackId ); - cursor.close(); - return app.getTrackCache().get(Integer.valueOf(trackId)); - } - } - int id =Integer.valueOf(trackId); - String wpsJson= Utils.isContentExist(Utils.getContentPah(id))?null:cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CONTENT));; -// String wpsJson =cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CONTENT)); - String rdBearJson = Utils.isContentExist(Utils.getBearContentPah(id))?null:cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_ROAD_BEARS)); -// String rdBearJson =cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_ROAD_BEARS)); - String mdBearJson = cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MDWPS)); -// Track tr = new Track(null,wpsJson,rdBearJson,mdBearJson); - // QLog.getLogger().dLog(dTAG, " get trackContent from "+ (TextUtils.isEmpty(wpsJson)?" txt file":" track db" )); - - tr=TextUtils.isEmpty(wpsJson)? new Track(id,true,rdBearJson,mdBearJson): new Track(id,null,wpsJson,rdBearJson,mdBearJson); - -// tr.getTrackBean().setTrackId(Integer.valueOf(trackId)); - /*int idx = cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME); - String nm = cursor.getString(idx); - cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME));*/ - tr.getTrackBean().setName(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME))); - tr.getTrackBean().setUserid(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_USER_ID))); - tr.getTrackBean().setDescription(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DESC))); - tr.getTrackBean().setComment(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_COMMENT))); - tr.getTrackBean().setStartTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME))); - // tb.setStartWp( )(cursor.getString((cursor.getColumnIndex(TrackProvider.KEY_TRACK_DESC)))); - tr.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_WP))); - tr.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP))); - - tr.setMaxRdistWpJson(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP))); - tr.getTrackBean().setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD))); - - tr.getTrackBean().setEndTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME))); - tr.getTrackBean().setCreatTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATE_TIME))); - tr.getTrackBean().setDistance(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE))); - tr.getTrackBean().seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST))); - tr.getTrackBean().seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))); - tr.getTrackBean().setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED))); - tr.getTrackBean().setPauseTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME))); - tr.getTrackBean().setSvrNumber(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_SVR_NUMBER))); - tr.getTrackBean().setIsCheckedIn(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_IS_SETS))); - tr.getTrackBean().setLastdbTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME))); - tr.getTrackBean().setStatus(TrackStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_STATUS)))); - tr.getTrackBean().setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); - tr.getTrackBean().setGpsSpan(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_GPSSPAN))); - tr.getTrackBean().setType( TrackType.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE)))); - tr.getTrackBean().setSportTime( cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); - tr.getTrackBean().setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING))); - tr.getTrackBean().setCreator(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATOR))); - tr.getTrackBean().setSrc(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SRC))); - tr.getTrackBean().setAvStatus(TrackAvStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_AVSTATUS)))); - app.getTrackCache().put(trackId,tr); - } - - }catch(Exception er){ - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - } - return tr; - - } - protected void getLastStatisticsTrack(int lastNumber){ - - TypeStatistics lastStack =app.mStatistics.getLastStrack();// new TypeStatistics() ; - // QLog.getLogger().d(dTAG,TAG+" begin to get getStatisticsTracks "); - projection = new String[] { TrackProvider.KEY_ID, - TrackProvider.KEY_TRACK_NAME, TrackProvider. KEY_TRACK_USER_ID, - TrackProvider.KEY_TRACK_START_TIME, TrackProvider.KEY_TRACK_END_TIME, - TrackProvider.KEY_TRACK_DISTANCE, TrackProvider.KEY_TRACK_EDOWN_DIST, - TrackProvider.KEY_TRACK_EUP_DIST, TrackProvider.KEY_TRACK_TOPSPEED, - TrackProvider.KEY_TRACK_SPORT_TIME, TrackProvider.KEY_TRACK_PAUSE_TIME, - TrackProvider.KEY_TRACK_STATUS, TrackProvider.KEY_TRACK_OFFTIME, - TrackProvider.KEY_TRACK_MAXRD , TrackProvider.KEY_TRACK_TYPE, - TrackProvider.KEY_LAST_UPDATE_TIME,TrackProvider.KEY_TRACK_CAL_BURNING - ,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_SVR_NUMBER - }; - - Uri uri = TrackProvider.TRACKS_URI; - - - String where = WHERE_TRACK_AV_STATUS + // "ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")=="+TrackAvStatus.ACTIVE + - " and " +TrackProvider.KEY_TRACK_TYPE +"!="+TrackType.COPY; - where += WHERE_TYPE_NO_GPX;//" and " +TrackProvider.KEY_TRACK_TYPE +"!="+TrackType.GPX; - if(lastStack!=null) - where +=" and " + TrackProvider.KEY_TRACK_START_TIME + " > "+ lastStack.getEnd(); - - String orderBy= TrackProvider.KEY_TRACK_START_TIME +" DESC " ; - String limit =" LIMIT "+lastNumber; - Cursor cursor = contentResolver .query(uri, projection, where, null, orderBy+limit); - - - if(cursor==null ){ - - return; - } - if(cursor.getCount()==0){ - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - return; - } - if(cursor.getCount()>5){ - lastStack = new TypeStatistics() ; - } - - /* long earlistTime=System.currentTimeMillis(); - long latestTime=0; - long statStart=System.currentTimeMillis(); - long statEnd=0; - int LastType=type; - int currentType = 0; - int lastTrackId=0; - int trackId=0; - StatTrack maxAvTrack; */ - try { - // QLog.getLogger().d(dTAG, " Tracks got: " +cursor.getCount()); -// while(cursor.moveToNext()){ - for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) { - -// trackId =Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID))); - float topSpd =cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED)); - Statics_bean stb = new Statics_bean(); - stb .setTrackid(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)))); - stb .setSvrNo(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_SVR_NUMBER)))); - stb .setName(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME))); - stb .setUserid(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_USER_ID))); - stb .setStartTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME))); - stb .setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD))); - stb .setEndTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME))); - stb .setDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE))); - stb .seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST))); - stb. seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))); - stb. setTopSpeed(topSpd); - stb. setPause(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME))); - stb. setStatus(TrackStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_STATUS)))); - stb. setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); - stb.setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); - stb.setLastdbTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME))); - stb.setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING))); - stb. setType(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE))); -// stb. setType(currentType); -// float avSp = stb.getSportTime()>0? 3600*stb.getDistance()/stb.getSportTime():0; - stb.setAvs(stb.getSportTime()>0? 3600*stb.getDist()/stb.getSportTime():0); -// strack.getSbs().put(stb .getTrackid(), stb) ; - -// strack.getStaticsTrackBeans().add(stb); -// QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND stb.getTrackid(): " +stb.getTrackid()); -// QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND stb.GetOffTime(): " +stb.getOffTime()); -// QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND stb.GetPause(): " +stb.getPause()); - lastStack.getSbs().put(stb.getTrackid(), stb); -// strack.getTrackIds().put(trackId, lastTrackId); -// lastTrackId =trackId; -// long totalTime= cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME)) -// -cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)) ; - /* long totalTime = cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)) + - cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME)) + - cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME));*/ - - long totalTime = stb.getTotalTime(); - - - - if(totalTime>0) { - -// strack.getStatTrack().seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST))); -// strack.getStatTrack().seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))+cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST))); - lastStack.getStatTrack().setUpDistE(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))); - - lastStack.getStatTrack().setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED))); - lastStack.getStatTrack().setPause(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME))); - lastStack.getStatTrack().setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); - lastStack.getStatTrack().setDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE))); - lastStack.getStatTrack().setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD))); - lastStack.getStatTrack().setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); - lastStack.getStatTrack().setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING))); - - float avSp = cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)) >0? - 3600*cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)) - /cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)) - :0; - avSp = avSp>topSpd?0:avSp; -// QLog.getLogger().d(dTAG, TAG+" dddddddddddddd ID: " +cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID))); -// QLog.getLogger().d(dTAG, TAG+" dddddddddddddd avSp: " +avSp); - lastStack.getStatTrack().setAvSpeed(avSp); - float tavSp = 3600*cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)) /totalTime ; - tavSp = tavSp>topSpd?0:tavSp; - lastStack.getStatTrack().setTavSpeed(tavSp); - - lastStack.getStatTrack().setTotalTime(totalTime); - lastStack.setEnd(stb.getEndTime()); - } - } - - -// maxAvTrack = getMaxTrack(statStart,statEnd,currentType); - - app.mStatistics.setLastStrack(lastStack); - - // QLog.getLogger().d(dTAG,TAG+" "+ "finished get statitics tracks" ); - - - }catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - - } - } - - protected void getStatisticTracks(long start,long end,int type,boolean isForceUpdate) - { - if(app.mStatistics==null ){ - app.initialStatistics(); - } - -// if(QiYouConstant.DEVELOPER_MODE) -// return; - - - start =app.mStatistics.getLastTime()+100; - - TypeStatistics strack = new TypeStatistics() ; - // QLog.getLogger().d(dTAG,TAG+" begin to get getStatisticsTracks ,start time is "+ start); - projection = new String[] { TrackProvider.KEY_ID, - TrackProvider.KEY_TRACK_NAME, TrackProvider. KEY_TRACK_USER_ID, - TrackProvider.KEY_TRACK_START_TIME, TrackProvider.KEY_TRACK_END_TIME, - TrackProvider.KEY_TRACK_DISTANCE, TrackProvider.KEY_TRACK_EDOWN_DIST, - TrackProvider.KEY_TRACK_EUP_DIST, TrackProvider.KEY_TRACK_TOPSPEED, - TrackProvider.KEY_TRACK_SPORT_TIME, TrackProvider.KEY_TRACK_PAUSE_TIME, - TrackProvider.KEY_TRACK_STATUS, TrackProvider.KEY_TRACK_OFFTIME, - TrackProvider.KEY_TRACK_MAXRD , TrackProvider.KEY_TRACK_TYPE, - TrackProvider.KEY_LAST_UPDATE_TIME ,TrackProvider.KEY_TRACK_CAL_BURNING, - TrackProvider.KEY_TRACK_CREATOR, TrackProvider.KEY_TRACK_SRC - ,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_SVR_NUMBER - ,TrackProvider.KEY_TRACK_LAST_WP - }; - - Uri uri = TrackProvider.TRACKS_URI; - - String whereType =type>=0?" and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " = " + type:""; - String where = WHERE_TRACK_AV_STATUS + " and " //"ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE + " and " - + TrackProvider.KEY_TRACK_START_TIME + " > "+ start + " and " - + TrackProvider.KEY_TRACK_START_TIME + " < "+ end - + whereType; -// where += WHERE_TYPE_NO_GPX; - - -// String where = TrackProvider.KEY_TRACK_START_TIME + " >=? and " -// + TrackProvider.KEY_TRACK_START_TIME + " <=? " -// + " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " =? "; - - String orderBy=TrackProvider.KEY_TRACK_TYPE+","+ TrackProvider.KEY_TRACK_START_TIME ; -// String[] parameters = new String[3]; -// parameters[0] =String.valueOf(start); -// parameters[1] =String.valueOf(end) ; -// parameters[2] =String.valueOf(type) ; -// - // QLog.getLogger().dLog(dTAG, TAG+" where clause is: " +where); - // QLog.getLogger().d(dTAG, TAG+String.format(" where parameters are, start is %s,end is %s,type is %s",start,end,type)); -// Cursor cursor = contentResolver.query(uri, projection, where, parameters, orderBy); -// Cursor cursor = contentResolver.query(uri, projection, where, new String[]{ String.valueOf(start), String.valueOf(end), String.valueOf(type) }, orderBy); - Cursor cursor = contentResolver.query(uri, projection, where, null, orderBy); - - /* if(cursor!=null ){ - QLog.getLogger().dLog(dTAG, TAG+" get statistics from db cursor.getCount() " + cursor.getCount()); - }*/ - - if(cursor==null){ - - return; - } - if(cursor.getCount()==0){ - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - return; - } - - long earlistTime=System.currentTimeMillis(); - long latestTime=0; - long statStart=System.currentTimeMillis(); - long statEnd=0; - int LastType=type; - int currentType = 0; - int lastTrackId=0; - int trackId=0; - StatTrack maxAvTrack; - try { - // QLog.getLogger().d(dTAG, " Tracks got: " +cursor.getCount()); -// while(cursor.moveToNext()){ - for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) { - currentType= cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE)); - -// // QLog.getLogger().d(dTAG, TAG+" LastType: " +LastType); - trackId =Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID))); - if(cursor.getPosition()==0){ - LastType=currentType; - strack = app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType)); - /* QLog.getLogger().dLog(dTAG, TAG+" 0 app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType)) is null? " + - (app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType))==null) +",currentType:"+currentType - );*/ - strack = strack==null?new TypeStatistics():strack; - - // QLog.getLogger().d(dTAG, " 0 strack.getSbs().size(): " +strack.getSbs().size()); - }else - if( LastType!=currentType ){ - strack.setStart(statStart); - strack.setEnd(statEnd); - strack.setType(LastType); -// maxAvTrack = getMaxTrack(statStart,statEnd,LastType); -// StatTrack statTrack=strack.getStatTrack(); - - maxAvTrack = getMaxTrack(strack.getStatTrack(),strack.getStatTrack().getEnd(),System.currentTimeMillis(),LastType); - strack.setStatTrack(maxAvTrack); - app.mStatistics.setMaxAvStat(maxAvTrack); - app.mStatistics.getStatisticsTracks().put(LastType, strack); - strack = app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType)); - /* QLog.getLogger().dLog(dTAG, TAG+" 1 app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType)) is null? " + - (app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType))==null) +",currentType:"+currentType - );*/ - - - strack = strack==null?new TypeStatistics():strack; - // QLog.getLogger().d(dTAG, " 1 strack.getSbs().size(): " +strack.getSbs().size()); - LastType=currentType ; - statEnd=0; - statStart=System.currentTimeMillis(); - } - - - Track_bean tb = new Track_bean(); - tb .setTrackId(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)))); - tb .setSvrNumber(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_SVR_NUMBER)))); - tb .setName(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME))); - tb .setUserid(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_USER_ID))); - tb .setStartTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME))); - tb .setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD))); - tb .setEndTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME))); - tb .setDistance(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE))); - tb .seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST))); - tb. seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))); - tb. setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED))); - tb. setPauseTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME))); - tb. setStatus(TrackStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_STATUS)))); - tb. setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); - tb.setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); - tb.setLastdbTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME))); - tb.setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING))); - tb.setCreator(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATOR))); - tb.setSrc(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SRC))); - tb. setType(TrackType.valueOf(currentType)); - Waypoint wpobj = new Waypoint(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP))); - tb.setLastWp(wpobj); - Statics_bean stb = new Statics_bean(tb); -// stb. setType(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE))); - - -// float avSp = stb.getSportTime()>0? 3600*stb.getDistance()/stb.getSportTime():0; -// stb.setAVS(stb.getSportTime()>0? 3600*stb.getDistance()/stb.getSportTime():0); -// strack.getSbs().put(stb .getTrackid(), stb) ; - earlistTime=earlistTime>stb.getStartTime()?stb.getStartTime():earlistTime; - latestTime=latestTimestb.getStartTime()?stb.getStartTime():statStart ; - statEnd=statEnd0) - app.mStatistics.getExistedSvrNos().add(Integer.valueOf(tb.getSvrNumber())); - } - - - - } - - maxAvTrack = getMaxTrack(strack.getStatTrack(),strack.getStatTrack().getEnd(),System.currentTimeMillis(),currentType); - strack.setStart(statStart); - strack.setEnd(statEnd); - strack.setType(currentType); -// maxAvTrack = getMaxTrack(statStart,statEnd,currentType); -// maxAvTrack = getMaxTrack(strack.getStatTrack(),strack.getStatTrack().getEnd(),System.currentTimeMillis(),LastType); - strack.setStatTrack(maxAvTrack); -// QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND maxAvTrack.getSumTotalTime(): " +maxAvTrack.getSumTotalTime()); - app.mStatistics.setFirstTime(earlistTime); - app.mStatistics.setLastTime(latestTime); - if(type<0){ - //show all type's tracks. -// app.mStatistics.setCnt(cursor.getCount()); - app.mStatistics.setCnt(app.mStatistics.getCnt()+cursor.getCount()); - } - - if(!isForceUpdate){ - app.mStatistics.setMaxAvStat(maxAvTrack); -// - }else{ -// CItem citem =new CItem (String.valueOf(type),TrackType.valueOf(type).toCHString()); -// citem.setCnt(1); - /* boolean isExist = false; - for(CItem ci:app.mStatistics.getTypeUsedLst()){ - if(Integer.valueOf(ci.GetID())==type){ - isExist=true; - break; - } - } - */ - if(!app.mStatistics.typeExitsInTypeUsedLst(type)){ - CItem citem =new CItem (String.valueOf(type),TrackType.valueOf(type).toCHString()); - citem.setCnt(1); - app.mStatistics.getTypeUsedLst().add(citem); - } - } - if(strack.getSbs().size()>0) - app.mStatistics.getStatisticsTracks().put(currentType, strack); //put the last one of types - - - // QLog.getLogger().d(dTAG,TAG+" "+ "finished get statitics tracks" ); - - - }catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - - } -// return strack; - - } - - - protected StatTrack getMaxTrack(StatTrack statTrack ,long start,long end,int type){ - -// QLog.getLogger().d(dTAG,TAG+" begin to get max value track"); - projection = new String[] { - TrackProvider.KEY_ID, - TrackProvider.KEY_TRACK_DISTANCE, - TrackProvider.KEY_TRACK_EDOWN_DIST, TrackProvider.KEY_TRACK_EUP_DIST, - TrackProvider.KEY_TRACK_TOPSPEED, - TrackProvider.KEY_TRACK_SPORT_TIME,TrackProvider.KEY_TRACK_PAUSE_TIME, - TrackProvider.KEY_TRACK_OFFTIME , - TrackProvider.KEY_TRACK_MAXRD,TrackProvider.KEY_TRACK_CAL_BURNING - ,TrackProvider.KEY_TRACK_START_TIME,TrackProvider.KEY_TRACK_END_TIME - ,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_TRACK_LAST_WP - }; - -// Uri uri = Uri.withAppendedPath(TrackProvider.TRACKS_URI, null); -// String where = TrackProvider.KEY_TRACK_START_TIME + " > 0 and " -// + "ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + "!=" + QiYouConstant.TRACK_TYPE_COPY; - - String where = WHERE_TRACK_AV_STATUS //"ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE - + " and " - + TrackProvider.KEY_TRACK_START_TIME + " >= "+ start + " and " - + TrackProvider.KEY_TRACK_START_TIME + " <= "+ end -// + " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",0)" + " != " + QiYouConstant.TRACK_TYPE_COPY - + " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",0)" + " = " + type -// + " and _id=70" - ; - where += WHERE_TYPE_NO_GPX; - -// QLog.getLogger().d(dTAG, TAG+" where clause is: " +where); - Cursor cursor = contentResolver.query(TrackProvider.TRACKS_URI, projection, where, null, null); -// StatTrack statTrack= new StatTrack(); - statTrack.setType(type); - try { - if (cursor!=null ) { -// QLog.getLogger().d(dTAG, TAG+" Max Average Tracks got: " +cursor.getCount()); -// int processedCnt=0; -// while(processedCnttotalTime1?totalTime1:totalTime; - -// long totalTime= cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME)) -// -cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)) ; - float topSpd =cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED)); - if(totalTime>0) { -// statTrack.seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST))); -// statTrack.seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))+cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST))); - statTrack.setUpDistE(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))); - statTrack.setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED))); - statTrack.setPause(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME))); - statTrack.setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); - statTrack.setDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE))); - statTrack.setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD))); - statTrack.setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); - statTrack.setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING))); - statTrack.setStart(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)) ); - statTrack.setEnd(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME)) ); - Waypoint wpobj = new Waypoint(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP))); - statTrack.setMaxEle(wpobj.getWb().getMaxEle()); - statTrack.setMinEle(wpobj.getWb().getMinEle()); - statTrack.setUpDist(wpobj.getWb().getUpDist()); - statTrack.setDownDist(wpobj.getWb().getDownDist()); -// QLog.getLogger().d(dTAG, "id,KEY_TRACK_SPORT_TIME: " -// + cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID))+"," -// + cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); - long sptime=cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)); - float distance=cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)); - float avSp = sptime >0? - 3600*distance/sptime - :0; - avSp = avSp>topSpd?0:avSp; - statTrack.setAvSpeed(avSp); - - float tavSp = 3600*distance /totalTime ; - - tavSp = tavSp>topSpd?0:tavSp; - statTrack.setTavSpeed(tavSp); - - statTrack.setTotalTime(totalTime); - - if(sptime>0 - &&distance>100){ - statTrack.setMinTimeKm((long) (sptime*1000/distance)); - } - - - } -// processedCnt++; -// cursor.moveToNext(); -// QLog.getLogger().d(dTAG, "processedCnt: " + processedCnt); - - - } - - } - } catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - } - - // QLog.getLogger().d(dTAG, "Initialized statTrack...of type "+TrackType.valueOf(type).toCHString()); - return statTrack; - - } - - /* - * get the ordered used track type list - */ - void getTypeUsedList(){ - - String TYPES_COUNT="tpes_cnt"; - projection = new String[] { - TrackProvider.KEY_TRACK_TYPE, - "COUNT(*) AS " + TYPES_COUNT - }; - String selection = "0==0) GROUP BY ("+ - TrackProvider.KEY_TRACK_TYPE; -// String orderBy=TrackProvider.KEY_TRACK_TYPE + " DESC "; - -// "ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +") - String where =WHERE_TRACK_AV_STATUS //"ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE - + " and " +selection -// + " and " +TrackProvider.KEY_TRACK_TYPE +"!=" + TrackType.GPX; - ; - - - String orderBy=TYPES_COUNT + " DESC "; - Cursor cursor = contentResolver.query(TrackProvider.TRACKS_URI, projection, where, null, orderBy); - try { - if (cursor!=null) { -// QLog.getLogger().d(dTAG, TAG+" Used track type got: " +cursor.getCount()); -// int processedCnt=0; - CItem citem; - boolean exist; - if( app.mStatistics ==null){ -// app.mStatistics =new Statistics(); - app.initialStatistics(); - } -// app.mStatistics.getTypeUsedLst().clear(); - -// ArrayList typeUsedLst = new ArrayList();//new SparseArray(); -// while(cursor.moveToNext() ){ - for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) { -// QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx cursor.getString(0): " +cursor.getString(0)); -// QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx TrackType.valueOf(cursor.getInt(0)).toCHString(): " +TrackType.valueOf(cursor.getInt(0)).toCHString()); - - if(cursor.getInt(0)==TrackType.GPX.toInt())continue; - - citem =new CItem (cursor.getString(0),TrackType.valueOf(cursor.getInt(0)).toCHString()); - - exist=false; - for(CItem i:app.mStatistics.getTypeUsedLst()){ - if(Integer.valueOf(i.getId()) == Integer.valueOf(citem.getId())){ - exist=true; - break; - } - } - if(exist)continue; - citem.setCnt(cursor.getInt(1)); - app.mStatistics.getTypeUsedLst().add(citem); - -// processedCnt++; -// cursor.moveToNext(); - -// QLog.getLogger().d(dTAG, TAG+ "%%%%%%% track Type:" +cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE) +", count:"+cursor.getColumnIndex(TYPES_COUNT) ); - } -// app.typeUsedLst = typeUsedLst ; - } - } catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - } - - } - - - - void getGpList(){ - String GEO_COUNT="geo_cnt"; - projection = new String[] { - TrackProvider.KEY_GEO_LAT, - TrackProvider.KEY_GEO_LON, - TrackProvider.KEY_LAST_UPDATE_TIME, - " (select count(*) from track_geos where "+ TrackProvider.KEY_TRACK_GEO_GID +" =geos._id) " + GEO_COUNT - }; -// String selection = "0==0) GROUP BY ("+ -// TrackProvider.KEY_TRACK_TYPE; -// String orderBy=TrackProvider.KEY_TRACK_TYPE + " DESC "; - -// "ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +") - String where =TrackProvider.KEY_GEO_TYPE +" = " + QiYouConstant.GEO_STREETNO; - where +=" and " +TrackProvider.KEY_LAST_UPDATE_TIME +" > " + app.mStatistics.getLastGeo(); -// int i=0; - int i =app.mStatistics.getGpList().size(); - long lastGeoDate = 0; - Cursor cursor = contentResolver.query(TrackProvider.GEOS_URI, projection, where, null, null); - try { - if (cursor!=null) { -// -// app.mStatistics.getGpList().clear(); -// ArrayList typeUsedLst = new ArrayList();//new SparseArray(); -// while(cursor.moveToNext() ){ - - for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) { -// QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx cursor.getString(0): " +cursor.getString(0)); -// QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx TrackType.valueOf(cursor.getInt(0)).toCHString(): " +TrackType.valueOf(cursor.getInt(0)).toCHString()); - if( cursor.getDouble(0)>0 && cursor.getDouble(1)>0){ - lastGeoDate =cursor.getLong(2)>lastGeoDate?cursor.getLong(2):lastGeoDate; - -// app.mStatistics.getGpList().put(i++, new GPItem(cursor.getInt(3),Utils.getGeoPoint(cursor.getDouble(0), cursor.getDouble(1)),-1)); - app.mStatistics.getGpList().put(i++, new GPItem(cursor.getInt(3), cursor.getDouble(0) , cursor.getDouble(1) ,-1)); - - } - -// QLog.getLogger().d(dTAG, TAG+ "%%%%%%% geo Cnt: " +cursor.getInt(2)+", geo: "+cursor.getDouble(0)+","+ cursor.getDouble(1) ); - } - app.mStatistics.setLastGeo(lastGeoDate); -// app.typeUsedLst = typeUsedLst ; - - - } - - String bearString = Utils.readSDFile(QiYouConstant.BEAR_TEXT); - if(TextUtils.isEmpty(bearString)){ - return; - } - String[] gps = bearString.split(";"); - String[] latlon; - GPItem gp = null; - for(String bear:gps){ - latlon=bear.split(","); - if(latlon.length==0||TextUtils.isEmpty(latlon[0])||TextUtils.isEmpty(latlon[1]))continue; - gp = null; - try{ - // gp= new GPItem(1,new GeoPoint(Double.valueOf(latlon[0]),Double.valueOf(latlon[1]))); -// gp= new GPItem(1,Utils.getGeoPoint(Double.valueOf(latlon[0]),Double.valueOf(latlon[1])),5); - gp = new GPItem(1, Double.valueOf(latlon[0]) ,Double.valueOf(latlon[1]) ,5); - - if(gp!=null) - app.mStatistics.getGpList().put(i++, gp); - }catch(NumberFormatException e) { - Utils.logStackTrace(e, TAG); - } - - } - Utils.writeSDFile(QiYouConstant.BEAR_TEXT,"");//update bear text to null on each mStatistics reading. - - } catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - } - - - - - } - - void getCateTrackList(){ - -// private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?"; -// -// TrackProvider.getTracksDB().rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)}); -// - projection = new String[] {TrackProvider.KEY_CATE_NAME,TrackProvider.KEY_TRACK_ID }; - -// String orderBy=TrackProvider.KEY_TRACK_TYPE + " DESC "; - -// String where = "ifnull(" + TrackProvider.KEY_CATE_TRACK_STATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE ; - String where = "( ifnull(" + TrackProvider.KEY_CATE_TRACK_STATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE + - " OR " + TrackProvider.KEY_CATE_TRACK_STATUS+" = "+TrackAvStatus.ACTIVE +")"; - String orderBy= TrackProvider.KEY_CATE_NAME ; - - Cursor cursor = contentResolver.query(TrackProvider.CATE_TRACK_URI, projection, where, null, orderBy); - try { - if (cursor!=null) { -// QLog.getLogger().d(dTAG, TAG+" Category track get cnt: " +cursor.getCount()); -// int processedCnt=0; - if( app.mStatistics ==null){ - app.mStatistics =new Statistics(); - } - -// ArrayList typeUsedLst = new ArrayList();//new SparseArray(); -// while(cursor.moveToNext() ){ - String lastCate=""; - String cate=""; - ArrayList trackIds=new ArrayList(); - HashMap> mCategoryList= new HashMap> (); - for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) { - cate =cursor.getString(0); - if(!TextUtils.isEmpty(lastCate) && !lastCate.equalsIgnoreCase(cate)) { -// QLog.getLogger().d(dTAG, TAG+"got category: " +lastCate); - mCategoryList.put(lastCate, trackIds); - trackIds= new ArrayList(); - } - trackIds.add(cursor.getInt(1)); - lastCate=cate; - if(cursor.isLast()){ - mCategoryList.put(lastCate, trackIds); - } - } - app.mStatistics.setCategoryList(mCategoryList); - app.initialCates();//check and insert default Cates - } - }catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - } - - } - - void addNewCateTrack(HashMap> mCategoryList){ - if(mCategoryList==null)return; - ContentValues[] values = new ContentValues[mCategoryList.size()]; - List valueList = new ArrayList(); - ContentValues value; - int i=0; - for(int id :mCategoryList.keySet()){ - if(mCategoryList.get(id)==null)continue; - for(String key:mCategoryList.get(id)){ - value = new ContentValues(); - value.put(TrackProvider.KEY_CATE_NAME, key); - value.put(TrackProvider.KEY_TRACK_ID, id); -// QLog.getLogger().d(dTAG, TAG+" adding new cate is "+key); - valueList.add(value); - } - - } - try { - contentResolver.bulkInsert(TrackProvider.CATE_TRACK_URI, valueList.toArray(values)); - app.getNewCategoryList().clear(); - } - catch (Exception er) { - Utils.logStackTrace(er, dTAG); - } - - } - - void delCateTrack(HashMap> mCategoryList){ - if(mCategoryList==null)return; - String where=""; - String[] args=new String[2]; - int errCnt=0; - for( int id:mCategoryList.keySet()){ - if(mCategoryList.get(id)==null)continue; - for(String key:mCategoryList.get(id)){ - - where = TrackProvider.KEY_CATE_NAME +"=? and "+ TrackProvider.KEY_TRACK_ID +"=?"; - args[0]=key; - args[1]=String.valueOf(id); - try { - contentResolver.delete(TrackProvider.CATE_TRACK_URI, where, args); - - } - catch (Exception er) { - Utils.logStackTrace(er, dTAG); - errCnt++; - } - } - - } - if(errCnt==0) - app.getDelCategoryList().clear(); - } - - - /* - * update track,no normal wps will be updated, roadwps, mdwps can be updated. - */ - protected void updateCateTrack(int trackId,int status) - { -// app.saveLocationParameters(false); - -// int trackId= tb.getTrackId(); - - ContentValues values = new ContentValues(); - - values.put(TrackProvider.KEY_CATE_TRACK_STATUS,status); - - String where = TrackProvider.KEY_TRACK_ID + "==" + trackId; - if (contentResolver.update(TrackProvider.CATE_TRACK_URI, values, where, null) == 0) { - //没有找到记录,新增track. - Log.e(dTAG,TAG+" "+"没有可匹配更新。"); -// - } - -// updateTable(TrackProvider.CATE_TRACK_URI,values, trackId,null); -// QLog.getLogger().d(dTAG, TAG+" updateTrack: "+ trackId +", track status is" + status); - - } - - /* - * update track server Number - */ -/* protected void updateTrackSvrNo(Track_bean tb) - { -// app.saveLocationParameters(false); - -// int trackId= tb.getTrackId(); -// Track_bean tb =tr.getTrackBean(); - ContentValues values = new ContentValues(); - - tb.setLastdbTime(System.currentTimeMillis()) ; - values.put(TrackProvider.KEY_SVR_NUMBER, tb.getNumber()); - values.put(TrackProvider.KEY_LAST_UPDATE_TIME, tb.getLastdbTime()); - updateTable(TrackProvider.TRACKS_URI,values, tb.getTrackId(),null); - QLog.getLogger().d(dTAG, TAG+" updateTrack: "+ tb.getTrackId() +", track available status is" +tb.getAvStatus()); - - }*/ - - /* - * update track server Number - */ - protected void updateTrackSvrNo(Map ids) - { - if(ids==null)return; - - ContentValues values = new ContentValues(); ; - int svrNo=0; - Track tr; - for(int id :ids.keySet()){ -// if(mCategoryList.get(id)==null)continue; - svrNo=ids.get(Integer.valueOf(id)); - // QLog.getLogger().d(dTAG, TAG+" get track id: "+id+", svrnumber"+svrNo); - svrNo=ids.get(Integer.valueOf(id)); - if(svrNo<=0)continue; - values.put(TrackProvider.KEY_SVR_NUMBER,svrNo ); - values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis()); - updateTable(TrackProvider.TRACKS_URI,values, id,null); - - tr =app.getTrackCache().get(Integer.valueOf(id)); - if(tr!=null) - tr.getTrackBean().setSvrNumber(svrNo); - - // QLog.getLogger().d(dTAG, TAG+" srvnumber updated: " +svrNo); - } -// try { -// contentResolver。(TrackProvider.CATE_TRACK_URI, valueList.toArray(values)); -// app.getNewCategoryList().clear(); -// } -// catch (Exception er) { -// Utils.logStackTrace(er, dTAG); -// } - - } - - int getCurrentSeq(String tableName){ - String sql ="select seq from sqlite_sequence where name=?"; - // QLog.getLogger().d(dTAG, TAG+" sequence query sql: " +sql); - Cursor cursor = TrackProvider.getTracksDB().rawQuery(sql, new String[]{tableName }); - - try{ - if(cursor!=null && cursor.moveToFirst() ){ - // QLog.getLogger().d(dTAG, TAG+" sequence query cursor.getCount() : " +cursor.getCount()); - return cursor.getInt(cursor.getColumnIndex("seq")); - } - }catch(Exception er){ - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null && !cursor.isClosed()) - cursor.close(); - } - - return -1; - } - void updateSeqId(String tableName,int seq){ - String sql ="update sqlite_sequence set seq="+ seq +" where name="+"'" + tableName + "'"; - sql ="update sqlite_sequence set seq=? where name=?"; - - // QLog.getLogger().d(dTAG, TAG+" sequence updated: ------------- " +sql); -// TrackProvider.getTracksDB().beginTransaction(); - TrackProvider.getTracksDB().execSQL(sql,new Object[]{seq,tableName}); -// TrackProvider.getTracksDB().endTransaction(); - } - - void insertSeqId(String tableName,int seq){ - String sql ="insert into sqlite_sequence(name,seq) values(?,?)"; - - // QLog.getLogger().d(dTAG, TAG+" sequence insert sql: ------------- " +sql); -// TrackProvider.getTracksDB().beginTransaction(); - TrackProvider.getTracksDB().execSQL(sql,new Object[]{tableName,seq}); -// TrackProvider.getTracksDB().endTransaction(); - } - - @Override - public void onDestroy() { - - // isStop=true;//锟斤拷使service锟斤拷锟斤拷锟竭筹拷也锟斤拷锟斤拷停止锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷通锟斤拷锟斤拷锟斤拷isStop锟斤拷停止锟竭筹拷 - // QLog.getLogger().d(dTAG, TAG+" db service destory"); - super.onDestroy(); -// app.saveLocationParameters(false); - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/service/TrackGEOService.java b/qy/src/main/java/com/qiyou/mb/android/service/TrackGEOService.java deleted file mode 100644 index 51e01fa..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/TrackGEOService.java +++ /dev/null @@ -1,1297 +0,0 @@ -package com.qiyou.mb.android.service; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; - -import android.app.IntentService; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.text.TextUtils; -import android.util.Log; - -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.search.geocode.GeoCodeResult; -import com.baidu.mapapi.search.geocode.GeoCoder; -import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; -import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption; -import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; -import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent; -import com.google.gson.Gson; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.GEO_bean; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; - -public class TrackGEOService extends IntentService implements OnGetGeoCoderResultListener { - - GeoCoder mSearch = null; // 搜索模块,也可去掉地图模块独立使用 - - public final static String TAG="com.qiyou.TrackGEOService"; - public static final String dTAG ="com.qiyou"; - protected QiYouApplication app; - int topWaiting=0; - boolean isBreak=false; - boolean isContinue=false; - Track track; - int trackId =-1; - int trackGeoType=-2; - int networkErrors=0; - int geoCnt=0; -// float trackDist=0; - String pathPoints=""; -// boolean canUpdate =false; - - protected ContentResolver contentResolver; - protected String[] projection; - - - int width ; - int height ; - /*String center=""; - String pathStyle ; - String format; - String staticMapUrl; - String baiduUrl ="http://api.map.baidu.com/staticimage";*/ - String whereUserId; - boolean isSpecifiedTrackMap=false; - public TrackGEOService( ) { - super(TAG); - // TODO Auto-generated constructor stub - - - } - public TrackGEOService(String name) { - super(name); - // TODO Auto-generated constructor stub - - } - @Override - public void onCreate() { - super.onCreate(); - app =(QiYouApplication)this.getApplication(); - whereUserId =" and " +TrackProvider.KEY_TRACK_USER_ID +" = " +app.user.getUserbean().getId(); - contentResolver = getContentResolver(); -// initialStaticMapParameters(); - - // 初始化搜索模块,注册事件监听 - mSearch = GeoCoder.newInstance(); - mSearch.setOnGetGeoCodeResultListener(this); - - } - /* private void initialStaticMapParameters(){ - width= QiYouConstant.PV_INT_SCREEN_WIDTH>0? QiYouConstant.PV_INT_SCREEN_WIDTH:720; -// width =width/2; - height=width/3; - center=""; - pathStyle="0xff0000,5,1"; - format ="?" -// + center +"&" -// +"zoom=13&" - +"width=%s&height=%s&paths=%s&pathStyles=%s" + - "©right=1"; - }*/ - - @Override - protected void onHandleIntent(Intent intent) { - - // TODO Auto-generated method stub -// - QLog.getLogger().d(dTAG, TAG+" app.geoWps.size():"+(app.geoWps!=null?app.geoWps.size():null) ); -// if(Utils.getNetworkType(this)==QiYouConstant.NETWORK_TYPE_OFF) return; - if(!QiYouConstant.NETWORK_CONNECTED - || QiYouConstant.IS_PROCESSING_GEO_FOOTMARK - || app.geoWps!=null && app.geoWps.size()>0 - ) - return; - - QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =true; - populateGEOs(0);//populate the province list - isSpecifiedTrackMap=false; - String key = QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID; - - //get specified track by id - if (intent.hasExtra(key)) { - trackId = intent.getExtras().getInt(key); - isSpecifiedTrackMap=true; - updateTrackGEO(); - return; - } - - key = QiYouConstant.EXTRA_KEY_TRACK_GEOS; - if (intent.hasExtra(key)) { - trackId=-1; - app.setlastGeoRequestTime(); - updateTrackGEO(); - return; - } - - - key = QiYouConstant.ACTION_CONNECTIVITY_CHANGE ; - - if (intent.hasExtra(key)) { -// if(!Utils.canUpdateGEOfootmark(this) ){ -//// if(app.lastWifiTime>0 || System.currentTimeMillis()-app.lastWifiTime <30*1000){ -//// Log.e(dTAG, TAG+" 检测到上次联网更新 GEO在30秒内,本次不再执行。" ); -// return; -// } -// - - QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =true; - app.setlastGeoRequestTime(); - - trackId=-1; - updateTrackGEO(); - - - - app.setlastGeoRequestTime(); - -// app.checkVersionUpdate(); - return; - } - - - - - - //after the geo, to start the offlineMap service. -// app.startNetworkLocationRequest(); - - - } - - void updateRoadWps(){ - long lastTime=0; - - /*CopyOnWriteArrayList wbs=new CopyOnWriteArrayList();*/ - ArrayList wbs=new ArrayList(); - - for(Waypoint_bean wb:track.getTrackBean().getRoadWps() ){ - - if(wb==null)continue; - - if(wb!=null && wb.getTime()>lastTime|| wb.getTurnFlag()!=null && wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()) - wbs.add(wb); - else{ - // QLog.getLogger().d(TAG, "wb==null :"+(wb==null)); - // QLog.getLogger().d(TAG, "wb.getTurnFlag()!=null && wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt() :"+(wb.getTurnFlag()!=null && wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt())); - // QLog.getLogger().d(TAG, "wb.getTurnFlag().toInt() :"+wb.getTurnFlag().toInt()); - } - // tb.getRoadWps().remove(wb); - if(wb!=null)lastTime =wb.getTime(); - - } - if(wbs.size() geoWps = new HashMap(); - String[] wps ; - // QLog.getLogger().d(dTAG, TAG+" 开始geo数据处理" ); - if(trackId >0 && trackId == app.getCurrentTrack().getTrackBean().getTrackId()){ - track = app.getCurrentTrack(); - if(track.getTrackBean().getRoadWps().size()==0) return; - track.getTrackBean().setTrackId(trackId); -// trackDist =track.getLastWp().getWb().getSumDist(); - - updateRoadWps(); - /* ArrayList roadWps =new ArrayList(); - - if( track.getTrackBean().getType()==TrackType.GPX){ - - for(Waypoint_bean wb:track.getTrackBean().getRoadWps()){ - if(wb==null)continue; - QLog.getLogger().d(dTAG,TAG+" 1 wb turnflag is "+ wb.getTurnFlag() ); - if( wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()){ - roadWps.add(wb); - - } - - } - }else{ - roadWps=track.getTrackBean().getRoadWps(); - } - */ - wps = new String[5]; -// wps[0] = buildRoadBookGEO(roadWps); - wps[0] = buildRoadBookGEO(track.getTrackBean().getRoadWps()); - wps[1] = buildWoGEO(track.getStartWp()); - wps[2] = buildWoGEO(track.getLastWp()); - wps[3] = buildWoGEO(track.getMaxDistWp()); - -// geoWps.put(trackId, wps); - - - networkErrors=generateStaticMap(track)?networkErrors:networkErrors+1; - if(geoCnt>0) wps[4] = String.valueOf(networkErrors); - - if(newGEOcnt>0){ - geoWps.put(trackId, wps); - track.TruncateFootMark(); - newGEOcnt =0; - } - - - }else{ - Cursor cursor =getWps(); - try { - // QLog.getLogger().d(dTAG, TAG+" 共"+cursor.getCount() +" 条track记录需要更新。" ); - if (cursor.moveToFirst()) { - int processedCnt =0; - while(processedCnt < cursor.getCount()){ - networkErrors=0; - geoCnt=0; - trackId =cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)); - String rdBearJson =cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_ROAD_BEARS)); -// track =new Track(null,null, rdBearJson,null); -// track.getTrackBean().setTrackId(trackId); - track =new Track(trackId,false,rdBearJson, null); -// track =new Track(trackId,false,null, null); - track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_WP))); - track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP))); - track.setMaxRdistWpJson(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP))); - track.getTrackBean().setType(TrackType.valueOf( cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE)))); - track.getTrackBean().setCreator(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATOR))); -// trackDist =track.getLastWp().getWb().getSumDist(); - - // QLog.getLogger().d(dTAG, TAG+" -------------------------------------正在处理track: "+ trackId); - - updateRoadWps(); - - wps = new String[5]; - wps[0] = buildRoadBookGEO(track.getTrackBean().getRoadWps()); - wps[1] = buildWoGEO(track.getStartWp()); - wps[2] = buildWoGEO(track.getLastWp()); - wps[3] = buildWoGEO(track.getMaxDistWp()); - -// geoWps.put(trackId, wps); - - processedCnt++; - - - networkErrors=generateStaticMap(track)?networkErrors:networkErrors+1; - if(geoCnt>0) wps[4] = String.valueOf(networkErrors); - if(newGEOcnt>0){ - geoWps.put(trackId, wps); - track.TruncateFootMark(); - newGEOcnt =0; - } - cursor.moveToNext(); - } - } - }catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null) cursor.close(); - } - - genStaticMap4gpx(); - } - - -// boolean canUpdate = true; //wps!=null && wps[0].length()>0 || wps[1].length()>0 || wps[2].length()>0 || wps[3].length()>0; -// if(canUpdate && geoWps.keySet().size()>0){ - if( geoWps.keySet().size()>0){ - /* Intent serviceIntent = new Intent(app, TrackDbServiceBackground.class); -// serviceIntent.putExtra(QiYouConstant.UPDATE_TRACK_GEO, true); -// serviceIntent.putExtra( QiYouConstant.EXTRA_KEY_ID, Integer.valueOf(trackId)); - serviceIntent.putExtra( QiYouConstant.EXTRA_KEY_TRACK_GEOS, geoWps); - startService(serviceIntent); */ - -// app.getStaticsTracks(); - app.updateGEOs(geoWps); - - QLog.getLogger().d(dTAG, TAG+" --------------------已提交数据更新. " ); - - }else{ - QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =false; - } - - - // QLog.getLogger().d(dTAG, TAG+" 本次GEO处理结束.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ); - app.syncStatistics(); - // QLog.getLogger().d(dTAG, TAG+" xxxxxxxxxxxx XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ); - - } - - - - - String buildWoGEO(Waypoint wp){ - String wpJson =""; - if(wp.getWb()!=null && wp.getWb().getGeo()==null && getGEOinfo(wp.getWb().getLatitude(),wp.getWb().getLongitude())){ - GEOaddress geo= new GEOaddress(); - geo.setProvince(GEOadress.province); - geo.setCity(GEOadress.city); - geo.setDistrict(GEOadress.district); - geo.setStreet(GEOadress.street); - geo.setStreetNo(GEOadress.streetNumber); - geo.setLat(wp.getWb().getLatitude()); - geo.setLon(wp.getWb().getLongitude()); - wp.getWb().setGeo(geo); - wpJson =wp.toJsonWp(); - if(!TextUtils.isEmpty(geo.toString(","))){ - newGEOcnt++; - } - - } - return wpJson; - } - - - - boolean getGEOinfo(Float lat,Float lon){ - - isBreak=false; - isContinue=false; - topWaiting =0; -// app.getBdGEOadress(lat,lon); - -// QLog.getLogger().d(dTAG,TAG+ String.format(" app.getBdGEOadres lat: %s; lon: %s", lat,lon)); - - /* app.*/getBdGEOadress(lat,lon); - geoCnt++; -// while(GEOadress==null && !isGEOerror) - while(true) - try { - Thread.sleep(200); -// app.getBdGEOadress(lat,lon); - topWaiting+=200; - -// QLog.getLogger().d(dTAG,TAG+"get GEOadress waiting for "+ topWaiting ); - - if(/*app.*/GEOadress!=null && !/*app.*/isGEOerror){ -// QLog.getLogger().d(dTAG,TAG+"GEOadress " + GEOadress.province+GEOadress.city+GEOadress.district); - break; - } - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB/3) - { - networkErrors++; - // QLog.getLogger().d(dTAG,TAG+" 获取地址超时. topWaiting: "+topWaiting); - // QLog.getLogger().d(dTAG,TAG+String.format("lat %s,lon %s,GEOadress==null?%s,isGEOerror?%s", lat,lon,GEOadress==null,isGEOerror)); - - - if(Utils.getNetworkType(this)==QiYouConstant.NETWORK_TYPE_OFF){ - isBreak =true; -// Toast toast= Toast.makeText(this, "获取地址失败,请检查网络." , Toast.LENGTH_LONG ); -// toast.show(); - break; - }else{ - isContinue =true; - break; - - } - - - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - /* if(!canUpdate){ - if(!(isBreak || isContinue))canUpdate=true; - }*/ - return !(isBreak || isContinue); - - } - -// String buildRoadBookGEO(CopyOnWriteArrayList _roadWps){ - String buildRoadBookGEO( ArrayList _roadWps){ - - long lastTime=0; - /* CopyOnWriteArrayList roadWps =new CopyOnWriteArrayList();*/ - ArrayList roadWps =new ArrayList(); - for(Waypoint_bean wb:_roadWps){ - if(wb==null)continue; - - if( wb.getTime()>lastTime|| wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()){ - roadWps.add(wb); - lastTime =wb.getTime(); - } - - } -// int topWaiting=0; -// boolean isBreak=false; -// boolean isContinue=false; - - /* if(roadWps.size()>300){ - roadWps=(ArrayList) roadWps.subList(0, 300); - - }*/ - - if(roadWps.size()==0) return""; - - String lastAddress=""; - -// float skiptDist=0; - -// ArrayList geoWps = new ArrayList(); - /* for(Waypoint_bean b:roadWps) - { - if (null !=b) - al.add(b); - } - if(al.size()==0) return""; - */ - Waypoint_bean wb; - Waypoint_bean lastWb = null; -// Waypoint_bean lastWb4map = null; - GEOaddress lastGeo =new GEOaddress();;// new GEOaddress();; -// final int MAXLATLNGS=50; - int geocnt=0; -// float stepValue =roadWps.size()>MAXLATLNGS &&trackDist>0 ?trackDist/MAXLATLNGS:0; -// pathPoints=""; -// float skipDist=0; - -// // QLog.getLogger().d(dTAG, TAG+" roadWps.size() is " + roadWps.size() +"----------------------------"); -// // QLog.getLogger().d(dTAG, TAG+" MAXLATLNGS is " + MAXLATLNGS ); -// // QLog.getLogger().d(dTAG, TAG+" trackDist/MAXLATLNGS " + trackDist/MAXLATLNGS ); - -// // QLog.getLogger().d(dTAG, TAG+" stepValue is " + stepValue); - - for(int i=0;ilastWb4map.getTime()) - if(QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK ||!track.isStaticMapExist()){ - -// // QLog.getLogger().d(dTAG, TAG+" No.i,lastwb.gettime():"+i+"," + Utils.getFormatedTime(lastWb4map.getTime())); -// // QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()" + (wb.getSumDist()-lastWb.getSumDist())); - // QLog.getLogger().d(dTAG, TAG+" skipDist" + skipDist); -// // QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()+skipDist" + (wb.getSumDist()-lastWb.getSumDist()+skipDist)); - float f =wb.getSumDist()-lastWb.getSumDist()+skipDist; - if(TextUtils.isEmpty(pathPoints)||f>=stepValue){ - - pathPoints=pathPoints+Utils.getbdLon(wb.getLatitude(), wb.getLongitude())+","+Utils.getbdLat(wb.getLatitude(), wb.getLongitude())+";"; - skipDist=0; - } - else - skipDist =wb.getSumDist()-lastWb.getSumDist(); - lastWb4map =wb; - } - - if(wb.getTime()0?i -1:i); -// if(lastWb!=null)lastGeo =lastWb.getGeo(); -// else lastGeo =new GEOaddress(); - - if( lastWb.getGeo()!=null){ - - if(lastWb.getGeo().getProvince()!=null && !lastWb.getGeo().getProvince().equalsIgnoreCase( lastGeo.getProvince())) - lastGeo.setProvince(lastWb.getGeo().getProvince()); - if(lastWb.getGeo().getCity()!=null && !lastWb.getGeo().getCity().equalsIgnoreCase( lastGeo.getCity())) - lastGeo.setCity(lastWb.getGeo().getCity()); - if(lastWb.getGeo().getDistrict()!=null && !lastWb.getGeo().getDistrict().equalsIgnoreCase( lastGeo.getDistrict())) - lastGeo.setDistrict(lastWb.getGeo().getDistrict()); - if( lastWb.getGeo().getStreet()!=null && !lastWb.getGeo().getStreet().equalsIgnoreCase( lastGeo.getStreet())) - lastGeo.setStreet(lastWb.getGeo().getStreet()); - if(lastWb.getGeo().getStreetNo()!=null && !lastWb.getGeo().getStreetNo().equalsIgnoreCase( lastGeo.getStreetNo())){ - lastGeo.setStreet(lastWb.getGeo().getStreet()); - lastGeo.setStreetNo(lastWb.getGeo().getStreetNo()); - } - - } - - - - -// updateGEOs(lastGeo); //check if the geo exits or not, if not, insert to db. - - - if(QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK ||wb.getGeo() ==null) - { - - getGEOinfo(wb.getLatitude(),wb.getLongitude()) ; - - if(isBreak)break; - if(isContinue || isGEOerror){ -// Track.saveBear(wb); - continue; - } - - if(!isGEOerror){ - - if( - ( wb.getTurnFlag()==wpFlag.MAXR - || wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt() - || wb.getTurnFlag()==wpFlag.TENT - || wb.getTurnFlag()==wpFlag.REST - || i == roadWps.size()-1 - || i == 0 - ) - && TextUtils.isEmpty(GEOadress.streetNumber)){ - if(!track.isLushu()) - Track.saveBear(wb); - } - String address = GEOadress.district+GEOadress.street +GEOadress.streetNumber; - /* if(TextUtils.isEmpty(lastAddress)){ - - - GEOaddress geo= new GEOaddress(); - - - if( !GEOadress.province.equalsIgnoreCase( lastGeo.getProvince())) - geo.setProvince(GEOadress.province); - if( !GEOadress.city.equalsIgnoreCase( lastGeo.getCity())) - geo.setCity(GEOadress.city); - if( !GEOadress.district.equalsIgnoreCase( lastGeo.getDistrict())) - geo.setDistrict(GEOadress.district); - if( !GEOadress.street.equalsIgnoreCase( lastGeo.getStreet())) - geo.setStreet(GEOadress.street); - if( !GEOadress.streetNumber.equalsIgnoreCase( lastGeo.getStreetNo())){ - geo.setStreet(GEOadress.street); - geo.setStreetNo(GEOadress.streetNumber); - } - - wb.setGeo(geo); - lastGeo =lastWb.getGeo()!=null?lastWb.getGeo():geo; - - - - }else - */ - - if(!lastAddress.equals(address) ) { //丢弃重复geo点 - -// if(lastWb.getGeo()!=null) -// lastGeo =lastWb.getGeo() ; - - GEOaddress geo= new GEOaddress(); - if( !GEOadress.province.equalsIgnoreCase( lastGeo.getProvince()) ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() ) - geo.setProvince(GEOadress.province); - if( !GEOadress.city.equalsIgnoreCase( lastGeo.getCity()) ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() ) - geo.setCity(GEOadress.city); - if( !GEOadress.district.equalsIgnoreCase( lastGeo.getDistrict()) ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() ) - geo.setDistrict(GEOadress.district); - if( !GEOadress.street.equalsIgnoreCase( lastGeo.getStreet()) ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() ) - geo.setStreet(GEOadress.street); - if( !GEOadress.streetNumber.equalsIgnoreCase( lastGeo.getStreetNo()) ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() ){ - geo.setStreet(GEOadress.street); - geo.setStreetNo(GEOadress.streetNumber); - } - /* if(addressResult!=null && addressResult.poiList!=null && addressResult.poiList.get(0)!=null){ - geo.setName(addressResult.poiList.get(0).name); - }*/ - if(addressResult!=null && addressResult.getPoiList()!=null && addressResult.getPoiList().size()>0 && addressResult.getPoiList().get(0)!=null){ - geo.setName(addressResult.getPoiList().get(0).name); - } - wb.setGeo(geo); - - if(!TextUtils.isEmpty(geo.toString(","))){ - geocnt++; -// if(wb.getGeo()!=null || wb.getTurnFlag() >2){ //maxR or end point need to be kept. - - // if(wb.getGeo()!=null || wb.getTurnFlag()>2){ //0,start;-1,left;1,right;2,back;3,maxR;4,end -// wb.setBearDist(wb.getBearDist()+skiptDist); //丢弃重复geo点 -// skiptDist=0; - - // updateGEOs(geo); //check if the geo exits or not, if not, insert to db. - if(wb.getTurnFlag()!=null) - trackGeoType =wb.getTurnFlag().toInt(); -// QLog.getLogger().d(dTAG,TAG+" wb turnflag is "+ wb.getTurnFlag()); - -// if(wb.getGeo()!=null && !TextUtils.isEmpty(wb.getGeo().toString(","))) - addNewTrackGeo(updateGEOs(wb), trackId,trackGeoType,wb.getTime());//check if the geo exits or not, if not, insert to db. And if new streetNo then insert trackgeo relation ship table. - - /* if( - ( lastWb.getGeo()==null || TextUtils.isEmpty(lastWb.getGeo().toString(","))) - && i>0 ) - - lastWb.setRoadBook( lastWb.getRoadBook().replace("\"", "") + ", \n 到达:"+ wb.getGeo().toString(",") +"\""); - */ - newGEOcnt++; - - }else{ - -// skiptDist+=wb.getBearDist(); - } - - } else if(wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()){ - GEOaddress geo= new GEOaddress(); - - geo.setProvince(GEOadress.province); - - geo.setCity(GEOadress.city); - - geo.setDistrict(GEOadress.district); - - geo.setStreet(GEOadress.street); - - geo.setStreetNo(GEOadress.streetNumber); - if(addressResult!=null && addressResult.getPoiList()!=null && addressResult.getPoiList().size()>0 && addressResult.getPoiList().get(0)!=null){ - geo.setName(addressResult.getPoiList().get(0).name); - } - wb.setGeo(geo); - } - lastAddress = address; - } - } else - continue; - lastWb =wb; - } - -// if(j>0) -// geoWps.get(j-1).setRoadBook( ", 当前位置::"+ lastWb.getGeo().toString(",") +"\n"+ geoWps.get(j-1).getRoadBook().replace("\"", "") +"\""); - -// geoWps.get(geoWps.size()-1).setRoadBook( geoWps.get(geoWps.size()-1).getRoadBook().replace("\"", "") + ", \n 到达重点位置:"+ geoWps.get(geoWps.size()-1).getGeo().toString(",") +"\""); - String rdbs =""; - if(geocnt==0) return rdbs; -// else if( app.tracks_cached.containsKey(trackId) && roadWps.size()>0){ - else if( app.getTrackCache().get(trackId)!=null && roadWps.size()>0){ - if(trackId == app.getCurrentTrack().getTrackBean().getTrackId() ){ - app.getCurrentTrack().setBearWps(roadWps); - rdbs =app.getCurrentTrack().getRdWpsJson().toString(); - // QLog.getLogger().d(dTAG,TAG+" roadbears "+ rdbs); - app.getTrackCache().put(trackId, app.getCurrentTrack()); - }else{ - app.getTrackCache().get(trackId).setBearWps(roadWps); - rdbs =app.getTrackCache().get(trackId).getRdWpsJson().toString(); - } - } - else{ - Gson gson = new Gson(); - try{ - rdbs = gson.toJson(roadWps) ; - }catch(Exception e) - { - Utils.logStackTrace(e, dTAG); - } - } - - return rdbs; - - } - - - - ArrayList gbs = new ArrayList(); - public int updateGEOs(Waypoint_bean wb){ - - - - int geoId =-1; - if(GEOadress == null) return geoId; -// if(TextUtils.isEmpty(lastGeo.toString(","))) return geoId; - - if(TextUtils.isEmpty(GEOadress.province)){ - return geoId; - } - - //check province - int provinceId =0; - int cityId=0; - int districtId=0; - int streetId=0; - - if( !app.geos.provinces.containsKey(GEOadress.province) ){ - GEO_bean gb = new GEO_bean(); - gb.setGeoType(QiYouConstant.GEO_PROVINCE); - gb.setName(GEOadress.province); - gb.setParentId(0); - provinceId =addNewGeos(gb); - app.geos.cities.clear(); - app.geos.GEOcities.clear(); - app.geos.districts.clear(); - app.geos.GEOdistricts.clear(); - app.geos.streets.clear(); - app.geos.GEOstreets.clear(); - app.geos.streetNos.clear(); - app.geos.GEOstreetNos.clear(); - }else{ - provinceId =app.geos.provinces.get(GEOadress.province); - - //check if the cities are under the province, if not,clear and populate the cities. - if(app.geos.GEOcities.size()==0 - || app.geos.GEOcities.size()>0 - && app.geos.GEOcities.get(app.geos.cities.keySet().toArray()[0].toString()).getParentId()!=provinceId ){ - app.geos.cities.clear(); - app.geos.GEOcities.clear(); - populateGEOs(provinceId); - // QLog.getLogger().d(dTAG, TAG+ " Populate province "+ GEOadress.province); - } - } - - - if(TextUtils.isEmpty(GEOadress.city)){ - return geoId; - } - - if( !app.geos.cities.containsKey(GEOadress.city)){ - /* if(provinceId ==0){ - if(lastGeo.getProvince()==null)return; - provinceId =app.geos.provinces.get(lastGeo.getProvince()); - } - if(!app.geos.GEOprovinces.get(lastGeo.getProvince()).getName().equalsIgnoreCase(lastGeo.getProvince())){ - app.geos.cities.clear(); - populateGEOs(provinceId); - } - - if(!app.geos.cities.containsKey(lastGeo.getCity()))*/{ - GEO_bean gb = new GEO_bean(); - gb.setGeoType(QiYouConstant.GEO_CITY); - gb.setName(GEOadress.city); - gb.setParentId(provinceId); - cityId =addNewGeos(gb); - app.geos.districts.clear(); - app.geos.GEOdistricts.clear(); - app.geos.streets.clear(); - app.geos.GEOstreets.clear(); - app.geos.streetNos.clear(); - app.geos.GEOstreetNos.clear(); - } - - }else{ - cityId =app.geos.cities.get(GEOadress.city); - if(app.geos.GEOdistricts.size()==0 - || app.geos.GEOdistricts.size()>0 - && app.geos.GEOdistricts.get(app.geos.districts.keySet().toArray()[0].toString()).getParentId()!=cityId ){ - app.geos.GEOdistricts.clear(); - app.geos.districts.clear(); - populateGEOs(cityId); - // QLog.getLogger().d(dTAG, TAG+ " Populate city "+GEOadress.city); - } - - - } - - if(TextUtils.isEmpty(GEOadress.district)){ - return geoId; - } - - - if( !app.geos.districts.containsKey(GEOadress.district) ){ - /* if(cityId ==0){ - if(lastGeo.getCity()==null)return; - cityId =app.geos.cities.get(lastGeo.getCity()); - } - if(!app.geos.GEOcities.get(lastGeo.getCity()).getName().equalsIgnoreCase(lastGeo.getCity())){ - app.geos.districts.clear(); - populateGEOs(cityId); - } - - if(!app.geos.districts.containsKey(lastGeo.getDistrict()))*/{ - GEO_bean gb = new GEO_bean(); - gb.setGeoType(QiYouConstant.GEO_DISTRICT); - gb.setName(GEOadress.district); - gb.setParentId(cityId); - - districtId =addNewGeos(gb); - app.geos.streets.clear(); - app.geos.GEOstreets.clear(); - app.geos.streetNos.clear(); - app.geos.GEOstreetNos.clear(); - } - - }else{ - districtId =app.geos.districts.get(GEOadress.district); - if(app.geos.GEOstreets.size()==0 - || app.geos.GEOstreets.size()>0 - && app.geos.GEOstreets.get(app.geos.streets.keySet().toArray()[0].toString()).getParentId()!=districtId ){ - app.geos.GEOstreets.clear(); - app.geos.streets.clear(); - populateGEOs(districtId); - // QLog.getLogger().d(dTAG, TAG+ " Populate district "+ GEOadress.district); - } - - } - - if(TextUtils.isEmpty(GEOadress.street )){ - return geoId; - } - - if( !app.geos.streets.containsKey(GEOadress.street)){ - /* if(districtId ==0){ - if(lastGeo.getDistrict()==null)return; - districtId =app.geos.districts.get(lastGeo.getDistrict()); - } - if(!app.geos.GEOdistricts.get(lastGeo.getDistrict()).getName().equalsIgnoreCase(lastGeo.getDistrict())){ - app.geos.streets.clear(); - populateGEOs(districtId); - } - - if(!app.geos.streets.containsKey(lastGeo.getStreet()))*/{ - GEO_bean gb = new GEO_bean(); - gb.setGeoType(QiYouConstant.GEO_STREET); - gb.setName(GEOadress.street); - gb.setParentId(districtId); - streetId =addNewGeos(gb); - app.geos.streetNos.clear(); - app.geos.GEOstreetNos.clear(); - } - }else{ - streetId =app.geos.streets.get(GEOadress.street); - if(app.geos.GEOstreetNos.size()==0 - || app.geos.GEOstreetNos.size()>0 - && app.geos.GEOstreetNos.get(app.geos.streetNos.keySet().toArray()[0].toString()).getParentId()!=streetId ){ - app.geos.GEOstreetNos.clear(); - app.geos.streetNos.clear(); - populateGEOs(streetId); -// // QLog.getLogger().d(dTAG, TAG+ " Populate street "+ GEOadress.street); - } - - } - if(TextUtils.isEmpty(GEOadress.streetNumber)){ - return geoId; - } - - if(!app.geos.streetNos.containsKey(GEOadress.streetNumber)){ - /* if(streetId ==0){ - if(lastGeo.getStreet()==null)return; - streetId =app.geos.streets.get(lastGeo.getStreet()); - } - if(!app.geos.GEOstreets.get(lastGeo.getStreet()).getName().equalsIgnoreCase(lastGeo.getStreet())){ - app.geos.streetNos.clear(); - populateGEOs(streetId); - } - - if(!app.geos.streetNos.containsKey(lastGeo.getStreetNo()))*/{ - GEO_bean gb = new GEO_bean(); - gb.setGeoType(QiYouConstant.GEO_STREETNO); - if(addressResult!=null && addressResult.getPoiList().size()>0 && addressResult.getPoiList().get(0)!=null){ - gb.setName(addressResult.getPoiList().get(0).name); - } -// gb.setName(GEOadress.streetNumber); - gb.setAddress(GEOadress.streetNumber); - gb.setParentId(streetId); - gb.setLat(wb.getLatitude()); - gb.setLon(wb.getLongitude()); - geoId= addNewGeos(gb); - - } - }else - geoId =app.geos.streetNos.get(GEOadress.streetNumber); - - - return geoId; - } - - void addNewTrackGeo(int geoId,int trackId,int type,long time){ - - if(geoId ==-1) return; - ContentValues values = new ContentValues(); - values.put(TrackProvider.KEY_TRACK_GEO_GID, geoId); - values.put(TrackProvider.KEY_TRACK_GEO_TID, trackId); - values.put(TrackProvider.KEY_TRACK_GEO_TYPE,type); - values.put(TrackProvider.KEY_TRACK_GEO_TIME,time); - values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis()); - - try { - contentResolver.insert(TrackProvider.TRACK_GEOS_URI, values); //TODO: remove the try/catch - QLog.getLogger().d(dTAG,TAG+" "+ "Added new track-geo: " + trackId+"-"+geoId); - } - catch (Exception er) { - Log.e(dTAG, TAG +" Update db" +TrackProvider.TRACK_GEOS_URI + " Adding/Update failed."); - Utils.logStackTrace(er, dTAG); - } - - } - - - int addNewGeos(GEO_bean gb){ - - ContentValues values = new ContentValues(); - int id=-1; - values.put(TrackProvider.KEY_GEO_PARENTID, gb.getParentId()); - values.put(TrackProvider.KEY_GEO_NAME, gb.getName()); - values.put(TrackProvider.KEY_GEO_TYPE, gb.getGeoType()); - values.put(TrackProvider.KEY_GEO_COMMENT, gb.getComment()); - values.put(TrackProvider.KEY_GEO_LAT, gb.getLat()); - values.put(TrackProvider.KEY_GEO_LON, gb.getLon()); - values.put(TrackProvider.KEY_GEO_3, gb.getAddress()); - values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis()); - try { - Uri uri =contentResolver.insert(TrackProvider.GEOS_URI, values); - if(uri !=null) { - id = Integer.valueOf(uri.getPathSegments().get(1)) ; - gb.setId(id); - app.geos.putValues(gb); -// // QLog.getLogger().d(dTAG,TAG+" "+ "Added new geo with ID " + uri.getPathSegments().get(1)); - // QLog.getLogger().d(dTAG,TAG+" "+ "Added new geo: " + gb.getName()); - } - - - } - catch (Exception er) { - Log.e("Update Tracks db", "Adding/Update failed."); - Utils.logStackTrace(er, dTAG); - } - return id; - } - - - - void populateGEOs(int parentId){ - Cursor cursor =getGEOs(parentId); - int geoId ; - int geoType =0; - String value=""; - try { - if (cursor!=null && cursor.moveToFirst()) { - int processedCnt=0; - while(processedCnt '" + QiYouConstant.GEO_STREETNO + "'";//TODO: when data is big, use the filter. - // String where ="ifnull(" + TrackProvider.KEY_GEO_PARENTID +",-1)" + " = '" + parentId + "'";//TODO: when data is big, use the filter. - String where = TrackProvider.KEY_GEO_PARENTID + " = '" + parentId + "'"; //TODO: use selection args - return contentResolver.query(TrackProvider.GEOS_URI, projection, where, null, null); - - } - - - Cursor getWps(){ - projection = new String[] { TrackProvider.KEY_ID, - TrackProvider.KEY_TRACK_START_WP,TrackProvider.KEY_TRACK_LAST_WP, - TrackProvider.KEY_TRACK_ROAD_BEARS,TrackProvider.KEY_TRACK_MAXRD_WP ,TrackProvider.KEY_TRACK_TYPE - ,TrackProvider.KEY_TRACK_CREATOR - }; - -// Uri uri = Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId)); - Uri uri =TrackProvider.TRACKS_URI;//Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId)); -// String where ="ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 -// +" and "+ TrackProvider.KEY_TRACK_TYPE +"!=" +TrackType.GPX.toInt(); - String where ="1=1 " ;//+ TrackProvider.KEY_TRACK_TYPE +"!=" +TrackType.GPX.toInt(); - - where += " and "+ TrackProvider.KEY_TRACK_TYPE +"!=" +TrackType.GPX.toInt(); //not include gpx - - if(!QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK) { - where +=" and ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 ; - where+=whereUserId; - } -// where += " and "+ TrackProvider.KEY_ID +" =1"; - - QLog.getLogger().d(dTAG, TAG+" get wps where is: "+ where); - return contentResolver.query(uri, projection, where, null, null); - - - } - - Cursor getWps4gpx(){ - projection = new String[] { TrackProvider.KEY_ID, - TrackProvider.KEY_TRACK_START_WP,TrackProvider.KEY_TRACK_LAST_WP, - TrackProvider.KEY_TRACK_MAXRD_WP - }; - -// Uri uri = Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId)); - Uri uri =TrackProvider.TRACKS_URI;//Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId)); -// String where ="ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 -// +" and "+ TrackProvider.KEY_TRACK_TYPE +"=" +TrackType.GPX.toInt(); -// -// if(QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK) where =null; - - - String where = TrackProvider.KEY_TRACK_TYPE +"=" +TrackType.GPX.toInt(); - - if(!QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK) - where +=" and ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 ; - - where+=whereUserId; - - return contentResolver.query(uri, projection, where, null, null); - - - } - - - void genStaticMap4gpx(){ - Cursor cursor =getWps4gpx(); - try { - // QLog.getLogger().d(dTAG, TAG+" 共"+cursor.getCount() +" 条gpx track记录需要更新。" ); - for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) { - - networkErrors=0; - geoCnt=0; - trackId =cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)); - track = new Track(); - track.getTrackBean().setTrackId(trackId); - - if(!QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK && track.isStaticMapExist()) return; - // QLog.getLogger().d(dTAG, TAG+" start get staticMap of track "+trackId ); -// track.getTrackBean().setTrackId(trackId); -// track =new Track(null,cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CONTENT)),null, null); - - track =new Track(trackId,true,null, null); - - track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_WP))); - track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP))); -// track.setMaxDistWp(new Waypoint(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP)))); - track.setMaxRdistWpJson(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP))); - track.getTrackBean().setType(TrackType.GPX); - generateStaticMap(track); - - } - }catch(Exception er) - { - Utils.logStackTrace(er, dTAG); - } - finally { - if(cursor!=null) cursor.close(); - } - - } - /* - void buildPathPoints(ArrayList wps){ - Waypoint_bean wb; -// Waypoint_bean lastWb = null; - Waypoint_bean lastWb4map = null; - final int MAXLATLNGS=50-3; - trackDist =track.getLastWp().getWb().getSumDist(); - float stepValue =wps.size()>MAXLATLNGS &&trackDist>0 ?trackDist/MAXLATLNGS:0; - pathPoints=""; - float skipDist=0; -// float skiptDist=0; -// // QLog.getLogger().d(dTAG, TAG+" wps.size() is " + wps.size() +"----------------------------"); -// // QLog.getLogger().d(dTAG, TAG+" MAXLATLNGS is " + MAXLATLNGS ); -// // QLog.getLogger().d(dTAG, TAG+" trackDist/MAXLATLNGS " + trackDist/MAXLATLNGS ); -// -// // QLog.getLogger().d(dTAG, TAG+" stepValue is " + stepValue); - - for(int i=0;ilastWb4map.getTime()) -// // QLog.getLogger().d(dTAG, TAG+" No.i,lastwb.gettime():"+i+"," + Utils.getFormatedTime(lastWb4map.getTime())); -// // QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()" + (wb.getSumDist()-lastWb.getSumDist())); -// // QLog.getLogger().d(dTAG, TAG+" skipDist" + skipDist); -// // QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()+skipDist" + (wb.getSumDist()-lastWb.getSumDist()+skipDist)); - float f =wb.getSumDist()-lastWb4map.getSumDist()+skipDist; -// // QLog.getLogger().d(dTAG, TAG+" current dist " + f +", stepvalue is "+ stepValue +" dist >stepvalue?"+(f>=stepValue)); - if(TextUtils.isEmpty(pathPoints)||f>=stepValue - ||wb.getTime()==track.getStartWp().getWb().getTime() - ||wb.getTime()==track.getLastWp().getWb().getTime() - ||wb.getTime()==track.getMaxDistWp().getWb().getTime()){ - - pathPoints=pathPoints+Utils.getbdLon(wb.getLatitude(), wb.getLongitude())+","+Utils.getbdLat(wb.getLatitude(), wb.getLongitude())+";"; - skipDist=0; - } - else - skipDist +=wb.getSumDist()-lastWb4map.getSumDist(); - - lastWb4map =wb; - -// lastWb=wb; - if(wb.getTime() bears; - @Override - protected void onHandleIntent(Intent intent) { - - // TODO Auto-generated method stub - - String key = QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID; - - - - //get specified track by id - if (intent.hasExtra(key)) { - trackId = intent.getExtras().getInt(key); - } - - if(app.playBackTrackId != trackId) return; - - if(QiYouConstant.PLAYBACK_CAN_RECORD) { - serviceIntent = new Intent(this, LocationService.class); - } - - - -// if(trackId<=0) return; - -// Intent sintent = new Intent(this,SplashActivity.class); -// sintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); -// this.startActivity(sintent); - - /*while( app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId)){ - - try { - Thread.sleep(100); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }*/ - - getCurrentPlayBackTrackWps(); -// gps_span=app.currentTrack.getTrackBean().getGpsSpan(); -// gps_span =gps_span<=0?QiYouConstant.MAX_GPS_SPAN:gps_span; - - } - - void getCurrentPlayBackTrackWps() { - - - //TODO: replace the sleep with a started activity/fragment for waiting db. - while(app.getCurrentTrack().getTrackBean().getTrackId() !=app.playBackTrackId - && - app.getCurrentTrack().getTrackBean().getSvrNumber() !=app.playBackTrackId) - { - try { - Thread.sleep(100); -// app.setCurrentTrack(app.getTrackCache().get(Integer.valueOf(app.playBackTrackId)), -// app.getCurrentTrack().getTrackBean().getSvrNumber() ==app.playBackTrackId -// ); - app.currentTrack =app.getTrackCache().get(Integer.valueOf(app.playBackTrackId)); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } -// long bfdbTime = System.currentTimeMillis(); - /* CopyOnWriteArrayList al = new CopyOnWriteArrayList(); - for(Waypoint_bean b:app.getCurrentTrack().getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - - Collections.sort(al, new SortByTime()); - app.getCurrentTrack().getTrackBean().setTrksegs(al);*/ - // QLog.getLogger().d(dTAG,TAG+" Sort the wps spend time " +String.valueOf((System.currentTimeMillis()-bfdbTime)) ); - - - - bears= new HashMap(); -// int i=0; -// Waypoint_bean nextWb; -// /*CopyOnWriteArrayList al2=app.getCurrentTrack().getTrackBean().getRoadWps();*/ - ArrayList al2=app.getCurrentTrack().getTrackBean().getRoadWps(); - - for(Waypoint_bean wb:al2){ -// i++; - if(wb==null)return; - -// if( app.getCurrentTrack().isLushu()){ -// if(i al = new CopyOnWriteArrayList() - sendLocations(app.getCurrentTrack().getTrackBean().getTrkseg() ); -// sendLocations(al ); - - } - int target=-1; - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) - /*void sendLocations(CopyOnWriteArrayList al){*/ - void sendLocations( ArrayList al){ - Location loc; -// long last_old_time =0; -// long last_new_time =0; -// Track tr1 = new Track(null,jsonWps); -// ArrayList al =tr1.getTrackBean().getTrkseg(); - - //TODO: find some way to terminate the loop when the playback quit. -// long startTime =System.currentTimeMillis(); - int i = 0; -// QLog.getLogger().d(dTAG,TAG+" size of wps to playback: " +al.size()); - Long lasttime =0L; //to remove - float lastDist = 0; - float maxR=0; - float lastspdDist = 0; -// synchronized(al) - { - - /*String mocLocationProvider ="mockLp"; - if(QiYouConstant.DEVELOPER_MODE &&app.lm.getProvider(mocLocationProvider)==null){ - QLog.getLogger().d(dTAG, "set mock test provider"); - app.lm.addTestProvider(mocLocationProvider, false, false, - false, false, true, true, true, 0, 5); - app.lm.setTestProviderEnabled(mocLocationProvider, true); - }*/ - -// QiYouConstant.PLAYBACK_TIME_INTERVAL =2000; - - for(Waypoint_bean wb:al) { - - if(!app.playBack ||app.playBackStopped)break; - - if(app.playBackTrackId != trackId - || app.getCurrentTrack().getTrackBean().getTrackId()!=app.playBackTrackId - && app.getCurrentTrack().getTrackBean().getSvrNumber() !=app.playBackTrackId){ - // QLog.getLogger().d(dTAG,TAG+" playBackTrackId != trackId , retart the playback service. "); - app.startPlayBackService(app.playBackTrackId); - break; - } - if(wb ==null)continue; - - //back to target - if( app.playProgressTarget>-1 && wb.getSumDist()> app.playProgressTarget){ - target=app.playProgressTarget; - app.playProgressTarget=-1; - sendLocations(al); - return; - } - - - if(wb.getSumDist() < target){ - continue; - } - // forward to target - if( wb.getSumDist()< app.playProgressTarget){ - target=app.playProgressTarget; - app.playProgressTarget=-1; - continue; - } - - - if (lasttime ==0L) lasttime =wb.getTime(); - if (lastDist ==0 ){ - lastDist = wb.getSumDist(); - } - if(wb.getTime()< lasttime || wb.getSumDist() < lastDist ){ - // QLog.getLogger().d(dTAG,TAG+" get bad duplicated wp:"+ String.valueOf(wb.getTime() )); - continue; - } - - - - - loc = new Location(LocationManager.GPS_PROVIDER); -// loc = new Location("playback"); - loc.setAltitude(wb.getElevation()); - loc.setLatitude(wb.getLatitude()); - loc.setLongitude(wb.getLongitude()); - loc.setSpeed( wb.getSpeed()/3.6f) ; - Bundle bd = new Bundle(); - bd.putLong("wptime",wb.getTime()); - bd.putLong("sptime",wb.getSportTime()); - bd.putLong("pausetime",wb.getPauseTime()); - bd.putLong("offtime",wb.getOfftime()); - bd.putFloat("dist",wb.getSumDist()); - - double r=Utils.getDistanceFromXtoY(wb.getLatitude(),wb.getLongitude(), - app.getCurrentTrack().getStartWp().getWb().getLatitude(), app.getCurrentTrack().getStartWp().getWb().getLongitude()); - maxR =(float) (maxR0) - loc.setBearing( wb.getBearing() ); - - - - loc.setTime(System.currentTimeMillis()); - - if(QiYouConstant.PLAYBACK_CAN_RECORD) { - serviceIntent.putExtra(LocationManager.KEY_LOCATION_CHANGED, loc); - startService(serviceIntent); - } - - lasttime =wb.getTime(); - lastDist = wb.getSumDist(); - - - i++; -// QLog.getLogger().d(dTAG,TAG+" sent location No. " + i +" of "+al.size()); -// QLog.getLogger().d(dTAG,TAG+" wb detail, lat:" + wb.getLatitude()+",lon:" +wb.getLatitude() +",speed:"+wb.getSpeed() ); -// - - - try { - if(!app.playBack ||app.playBackStopped)break; - - //TODO: CHECK WHY STUCK HERE WHEN CHANGE CURRENT PLAY BACK TRACK. - int totalSleep =0; - while(i>1 /*&& totalSleep<6000 */ &&(app.playbackPaused ||QiYouConstant.CAN_SPEAK && app.isSpeaking())){ - -// QLog.getLogger().d(dTAG,String.format(" is speeaking ?%s, total sleep %s",QiYouConstant.CAN_SPEAK && app.isSpeaking(), totalSleep)); - - Thread.sleep(500); - totalSleep+=500; - if( app.playBackStopped){ - break; - } - } - - Thread.sleep(QiYouConstant.PLAYBACK_TIME_INTERVAL); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - - Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, loc); - sendBroadcast(broadcastIntent); - if(QiYouConstant.IS_TEST_NAV) - app.lastNaviLocation= loc; - - - - - - - /* - if(QiYouConstant.DEVELOPER_MODE){ - Location mockLocation = new Location(mocLocationProvider); // a string - mockLocation.setLatitude(wb.getLatitude()); // double - mockLocation.setLongitude(wb.getLongitude()); - mockLocation.setAltitude(wb.getElevation()); - mockLocation.setTime(System.currentTimeMillis()); - mockLocation.setAccuracy(wb.getAccuracy()>0?wb.getAccuracy():3f); - mockLocation.setBearing(wb.getBearing()>0?wb.getBearing():1); - mockLocation.setElapsedRealtimeNanos(android.os.SystemClock.elapsedRealtimeNanos()); - - app.lm.setTestProviderLocation( mocLocationProvider, mockLocation); - }*/ - } - } - - if(app.playBackTrackId != trackId - || app.getCurrentTrack().getTrackBean().getTrackId()!=app.playBackTrackId - && app.getCurrentTrack().getTrackBean().getSvrNumber() !=app.playBackTrackId ){ - app.startPlayBackService(app.playBackTrackId); - }else - { - // QLog.getLogger().d(dTAG,TAG+" playBackTrackId,trackId "+app.playBackTrackId+" , "+ trackId ); -// app.playBack =false;//playback was over. - app.playBackStopped=true; - // QLog.getLogger().d(dTAG,TAG+" track "+trackId+" play back is done."); - loc =new Location("playback"); - loc.setSpeed(-1); - Intent broadcastIntent = new Intent(); - broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); - broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, loc); - sendBroadcast(broadcastIntent); - } - - } - - - @Override - public void onDestroy() { - -// QLog.getLogger().d(dTAG,TAG + " Services onDestory"); -// Log.i(dTAG,TAG + " Services onDestory"); - - // // isStop=true;//即使service销毁线程也不会停止,所以这里通过设置isStop来停止线程 - // // QLog.getLogger().d(TAG," save app.sumPaused "+app.sumPaused ); - // QLog.getLogger().d(TAG," save app.sumOfftime: "+app.sumOfftime ); - // QLog.getLogger().d(TAG,"---------app.sumPause loop----------------------------" ); - - super.onDestroy(); - - } - - - } - - - class SortByTime implements Comparator { - @Override - public int compare(Waypoint_bean wb1, Waypoint_bean wb2) { - if (wb1.getTime() > wb2.getTime()) - return 1; - return 0; - } - } - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/service/sync.java b/qy/src/main/java/com/qiyou/mb/android/service/sync.java deleted file mode 100644 index 6295f27..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/service/sync.java +++ /dev/null @@ -1,690 +0,0 @@ -package com.qiyou.mb.android.service; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; - -import org.apache.http.Header; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHeader; -import org.apache.http.protocol.HTTP; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.JsonHttpResponseHandler; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.Statistics; -import com.qiyou.mb.android.beans.basic.GPItem; -import com.qiyou.mb.android.beans.basic.Statics_bean; -import com.qiyou.mb.android.utils.FileUtil; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; - -import android.app.Service; -import android.content.Intent; -import android.os.IBinder; -import android.text.TextUtils; - -public class sync extends Service { - public final static String TAG="com.qiyou.sync"; - public static final String dTAG ="com.qiyou"; - protected QiYouApplication app; - - - @Override - public IBinder onBind(Intent intent) { - // TODO Auto-generated method stub - return null; - } - @Override - public void onCreate() { - // TODO Auto-generated method stub - super.onCreate(); - // QLog.getLogger().d(dTAG,TAG+"... service sync onCreate.....," ); - if(app==null) - app =(QiYouApplication)this.getApplication(); - } - @Override - public void onStart(Intent intent, int startId) { - QLog.getLogger().d(dTAG,TAG+"... service sync onStart.....," ); - if(app==null) - app =(QiYouApplication)this.getApplication(); - if(intent!=null) - handleIntent(intent); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId){ - QLog.getLogger().d(dTAG,TAG+"... service sync onStartCommand.....," ); - handleIntent(intent); - // We want this service to continue running until it is explicitly - // stopped, so return sticky. - return START_STICKY; - } - protected void handleIntent(Intent intent){ - - - if(intent==null)return; - - String key = QiYouConstant.ACTION_SYNC_STATISTICS ; - - if (intent.hasExtra(key)) { -// QLog.getLogger().d(dTAG, TAG+(app.isStaticsticsDone?" it is ready for sync.... ":" it has been in sycing, return... ")); - -// return; - - int exit =Integer.valueOf(intent.getExtras().get(key).toString()); - isExitApp = exit ==1; - - if(app.isStaticsticsDone || isExitApp){ - app.isStaticsticsDone=false; - checkStatiscsStatus(); //同步statistic - } - } - } - - int userId; - boolean isExitApp = false; -// boolean isStaticsticsDone=false; - void checkStatiscsStatus(){ -// QLog.getLogger().d(dTAG, TAG+" begin do the statistics sync.................."); - int topWaiting=0; - if (app.mStatistics==null || app.statTrackLoading){ - app.isStaticsticsDone=true; - return; - } - while(app.mStatistics==null || app.statTrackLoading) - try { - Thread.sleep(100); -// app.getBdGEOadress(lat,lon); - topWaiting+=100; - QLog.getLogger().d(dTAG,TAG+" statistics 初始化中。。。"+topWaiting); - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB*5) { - break; - - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - -// QLog.getLogger().d(dTAG,TAG+" statistics is:" + Utils.getGsonString(app.mStatistics)); - - - userId=app.user.getUserbean().getId(); - - if(userId<=0 && !QiYouConstant.DEVELOPER_MODE){ //only sync known user. - app.isStaticsticsDone=true; - return; - } - - userId=userId>0?userId:app.getPhoneId(); - - QLog.getLogger().dLog(dTAG,TAG+" statitics identify id is "+userId); - - - if(app.mStatistics==null ||userId ==-1){ - - exitService(); - return; - } - - QLog.getLogger().dLog(dTAG, TAG+" check timestamp, need to check with web? " + (app.mStatistics.getLastTime()==app.getLastStatSyncTime()) ); - if(app.getLastStatSyncTime()>0 && app.mStatistics.getLastTime()==app.getLastStatSyncTime()){ - - if (!QiYouConstant.DEVELOPER_MODE){ - QLog.getLogger().d(dTAG,TAG+" 。。。。。。。。。。。。。。。。。。。。。没有更新需要同步"); - exitService(); - return; - } - - } - - RequestParams params = new RequestParams(); - params.add("userid", String.valueOf(userId)); - params.add("from", String.valueOf(app.mStatistics.getFirstTime())); - params.add("to", String.valueOf(app.mStatistics.getLastTime())); - params.add("dist", String.valueOf((int)app.mStatistics.getSumDist())); - QLog.getLogger().d(dTAG, TAG+" begin to check web statistics........., web query params: "+params); - getJsonWs(params, RestMethods.USER_G_USER_STAT_STATUS/*"mb/user/statistics/status"*/); - - - } - - - - - - boolean isPostStatics; - String lastStatName=QiYouConstant.STAT_TEXT+"_last" ; - Statistics deltaStatistics=null; - - void postStatiscs(){ - - if(isPostStatics)return; - - isPostStatics=false; - - Statistics mLastStatistics=null; - - StringBuffer statJson=new StringBuffer(); - - String deltaName=QiYouConstant.STAT_TEXT; - try { - lastStatName=QiYouConstant.STAT_TEXT+"_last"+userId; //use the phoneid/userid as last synced name. -// QLog.getLogger().d(dTAG, TAG+" begin to read last Statistics from "+ lastStatName +" ..........................................." ); - -// FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_en", QiYouConstant.STAT_TEXT, crypto, entity); -// statJson.append(Utils.readSDFile(QiYouConstant.STAT_TEXT)); - statJson.append(FileUtil.readEncodedFile(lastStatName, app.crypto, app.entity)); -// QLog.getLogger().d(dTAG, " QiYouConstant.STAT_TEXT is: "+QiYouConstant.STAT_TEXT ); - QLog.getLogger().dLog(dTAG, TAG+" last statJsn is: "+statJson.toString() ); - -// Utils.writeSDFile(lastStatName +"_de", statJson.toString()); -// Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); - - mLastStatistics= (Statistics)Utils.getGsonObject(statJson.toString(), Statistics.class) ; - -// QLog.getLogger().d(dTAG, " read Statistics from "+ QiYouConstant.STAT_TEXT+"_en ........................................... done" ); - - }catch( JsonSyntaxException je){ - Utils.logStackTrace(je, TAG); - mLastStatistics=null; - }/* catch (IOException e) { -// // TODO Auto-generated catch block - e.printStackTrace(); - } */ -// mLastStatistics =mLastStatistics==null?new Statistics():mLastStatistics; - statJson=new StringBuffer(); - - try { - QLog.getLogger().d(dTAG, TAG+" begin to read delta Statistics from "+ deltaName +" ..........................................." ); - -// FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_en", QiYouConstant.STAT_TEXT, crypto, entity); -// statJson.append(Utils.readSDFile(QiYouConstant.STAT_TEXT)); - statJson.append(FileUtil.readEncodedFile(deltaName, app.crypto, app.entity)); -// QLog.getLogger().d(dTAG, " QiYouConstant.STAT_TEXT is: "+QiYouConstant.STAT_TEXT ); - QLog.getLogger().dLog(dTAG, TAG+" delta statJsn is: "+statJson.toString() ); - -// Utils.writeSDFile(deltaName +"delta_de", statJson.toString()); -// Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); - - deltaStatistics= (Statistics)Utils.getGsonObject(statJson.toString(), Statistics.class) ; - -// QLog.getLogger().d(dTAG, " read Statistics from "+ QiYouConstant.STAT_TEXT+"_en ........................................... done" ); - - }catch( JsonSyntaxException je){ - Utils.logStackTrace(je, TAG); - deltaStatistics=null; - this.exitService(); - } /* catch (IOException e) { -// // TODO Auto-generated catch block - e.printStackTrace(); - } */ - - QLog.getLogger().dLog(dTAG, TAG+" lastStaitistics is null? "+(mLastStatistics==null) ); - - /* HashMap deltaList=new HashMap(); - HashMap lastList=new HashMap(); - if(deltaStatistics!=null && deltaStatistics.getGpList().size()>100){ //remove duplicated ones - int ikey=0; - GPItem item; - for(Integer key:deltaStatistics.getGpList().keySet()){ - item =deltaStatistics.getGpList().get(key); - if(item!=null){ - deltaList.put(item.getLat()+"_"+item.getLng(), item); - } - } - - deltaStatistics.getGpList().clear(); - for(String key:deltaList.keySet()){ - item =deltaList.get(key); - if(item!=null){ - deltaStatistics.getGpList().put(ikey, item); - ikey++; - } - } - - - - if(mLastStatistics!=null){ - for(Integer key:mLastStatistics.getGpList().keySet()){ - item =mLastStatistics.getGpList().get(key); - if(item!=null){ - lastList.put(item.getLat()+"_"+item.getLng(), item); - } - } - - ikey=0; - mLastStatistics.getGpList().clear(); - for(String key:lastList.keySet()){ - item =lastList.get(key); - if(item!=null){ - mLastStatistics.getGpList().put(ikey, item); - ikey++; - } - } - } - - }*/ - - if(mLastStatistics!=null && deltaStatistics!=null){ - QLog.getLogger().d(dTAG, TAG+" begin to build data for sync..........................................." ); - -// ConcurrentHashMap StatisticsTracks =new ConcurrentHashMap(); - // to get delta sbs - for(Integer key:deltaStatistics.getStatisticsTracks().keySet()){ - - QLog.getLogger().dLog(dTAG, TAG+ String.format(" checking track type, GPX type value is %s, current type value %s ", TrackType.GPX.toInt(), key.intValue()) ); - - if (key.intValue()==TrackType.GPX.toInt()){ // will equal? - deltaStatistics.getStatisticsTracks().remove(key); - continue; - } - if(mLastStatistics.getStatisticsTracks().keySet().contains(key)){ - if(deltaStatistics.getStatisticsTracks().get(key).getEnd()>0 && - deltaStatistics.getStatisticsTracks().get(key).getEnd() - > mLastStatistics.getStatisticsTracks().get(key).getEnd()){ - Statics_bean sb=null; - - for(Integer trackId: deltaStatistics.getStatisticsTracks().get(key).getSbs().keySet()){ - sb =deltaStatistics.getStatisticsTracks().get(key).getSbs().get(trackId); - if(sb!=null && sb.getStartTime()<=mLastStatistics.getStatisticsTracks().get(key).getEnd()){ - deltaStatistics.getStatisticsTracks().get(key).getSbs().remove(trackId); - QLog.getLogger().dLog(dTAG, TAG+" deltaStatistics removed " +trackId ); - } - } - } - - } - } - - - //to get delta gp - HashMap gpList=new HashMap(); - - /* - * NOT TO UPLOAD FOOTMARKS TO SERVER 2016.01.06 - * - * - * QLog.getLogger().dLog(dTAG, TAG+ String.format(" 1 delta gp size %s,last stat gp size %s",deltaStatistics.getGpList().size(),mLastStatistics.getGpList().size()) ); - */ - int ikey=0; - if(deltaStatistics.getGpList().size() > mLastStatistics.getGpList().size()){ - QLog.getLogger().dLog(dTAG, TAG+ String.format(" 2 delta gp size %s,last stat gp size %s",deltaStatistics.getGpList().size(),mLastStatistics.getGpList().size()) ); - for(Integer key:deltaStatistics.getGpList().keySet()){ - if(!mLastStatistics.getGpList().containsValue(deltaStatistics.getGpList().get(key))){ - gpList.put(ikey, deltaStatistics.getGpList().get(key)); - QLog.getLogger().dLog(dTAG, TAG+String.format(" key is %s,new key is %s,put in gp %s " ,key,ikey, Utils.getGsonString(deltaStatistics.getGpList().get(key))) ); - ikey++; - if(ikey>100){ //limit to 100 for each sync - break; - } - } - } - } - - deltaStatistics.setGpList(gpList); - - } - - - - deltaStatistics.setUserId(userId); - isPostStatics=true; - this.postJsonWS(Utils.getGsonString(deltaStatistics) , RestMethods.USER_P_USER_STAT/* "mb/user/statistics"*/); - - QLog.getLogger().dLog(dTAG, TAG+" post delta statistics jason is " + Utils.getGsonString(deltaStatistics) ); - - - } - - void getStatiscs(){ -// int userId=app.user.getUserbean().getId(); -// if(userId<=0)return; - - RequestParams params = new RequestParams(); - params.add("userid", String.valueOf(userId)); - QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params, RestMethods.USER_G_USER_STAT/*"mb/user/statistics"*/); - - - } - - - - - void writeLastStatistics(){ - try { - app.setLastStatSyncTime(app.mStatistics.getLastTime()); - QLog.getLogger().d(dTAG,TAG +" last sync stat time is " + app.mStatistics.getLastTime()); - Utils.writeSDFile(lastStatName+"_tmp",Utils.getGsonString(app.mStatistics)); - FileUtil.encodeFile(lastStatName, lastStatName+"_tmp", app.crypto, app.entity); - -// FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_conseal_en", QiYouConstant.STAT_TEXT+"_conseal_plain", crypto, entity); - - -// FileUtil.writeFile(this.crypto,this.entity, QiYouConstant.STAT_TEXT+"_conseal", gson.toJson(mStatistics) ); -// FileUtil.writeFile(this.crypto,this.entity, QiYouConstant.STAT_TEXT+"_test", "a" ); -// Utils.writeSDFile( QiYouConstant.STAT_TEXT+"_test_a","a" ); -// Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_a_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - /*} catch (CryptoInitializationException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } catch (KeyChainException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - */ - } - } - - - void processJsonObject(JSONObject jsonObject)throws JSONException{ - if(isPostStatics){ - isPostStatics=false; - QLog.getLogger().d(dTAG,TAG +" statistics 上传成功 "); - - - - - writeLastStatistics(); -// app.isStaticsticsDone=true; - exitService(); - QLog.getLogger().d(dTAG,TAG+ " statistics 同步结束"); - } - } - - void processWebStatistics(JSONObject jsonObject){ - - try { - - String msg =jsonObject.getString(QiYouConstant.MSG_KEY); - - if( !TextUtils.isEmpty(msg) && !msg.equalsIgnoreCase("null")){ //检验当前手机端的statistics相对server端的时间戳 - - boolean toGet = false; - boolean toPost = false; - - int i =-1; - try{ - i =Integer.valueOf(msg); - toGet =i==0; - toPost=i==1; - - - }catch(NumberFormatException e){ - - } - - - QLog.getLogger().d(dTAG,TAG+" returnned statistics status is "+msg); - QLog.getLogger().d(dTAG,TAG+" "+(toGet?"begin to get statistics from web....":toPost?" begin to post statistics to web....":" nothing need to do, return...")); - - /*if(jo.has("get")){ - toGet =jo.getBoolean("get"); - } - if(jo.has("post")){ - toPost = jo.getBoolean("post"); - }*/ - - - if ( QiYouConstant.DEVELOPER_MODE){ -// toGet = true; -// toPost = true; - } - if(toGet){ - getStatiscs(); - }else if(toPost){ - postStatiscs(); - }else{ - exitService(); - } - - return; - } - - - - //取到服务端的statistic,更新本地的statiscs - QLog.getLogger().d(dTAG,TAG+" to store statistics........ "); - JSONObject jo =jsonObject.getJSONObject(QiYouConstant.JSONOBJECT_KEY); - - if(jo==null){ -// app.isStaticsticsDone=true; - QLog.getLogger().d(dTAG,TAG+" statistics 同步结束"); - exitService(); - return; - } - - app.mStatistics = (Statistics)Utils.getGsonObject(jo.toString(), Statistics.class); - app.getStaticsTracks(); //合并本地数据库数据并保存 -// checkStatiscsStatus(); //do sync with new statistics -// app.isStaticsticsDone=true; - writeLastStatistics(); //write last stat. - - - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - - }catch(Exception e){ - Utils.logStackTrace(e, dTAG); - - } - - QLog.getLogger().d(dTAG,TAG+" statistics 同步结束"); - exitService(); - - - } - - - - void postJsonWS(String json,String url) { - - - StringEntity entity =null; - try { - entity = new StringEntity(json,HTTP.UTF_8); - } catch (UnsupportedEncodingException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - if(entity==null)return; - - entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); - -// QiyouRestClient.post(activity,url, entity,"application/json", - QiYouApplication.post( app,url, entity,"application/json", - new JsonHttpResponseHandler(){ - @Override - public void onSuccess(int statusCode, org.apache.http.Header[] headers, JSONObject response){ -// isPostStatics=false; - if (response != null) { - try { -// processJsonObject( response.getJSONObject(QiYouConstant.JSONOBJECT_KEY)); - processJsonObject( null); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - - } - } - - String msg = ""; - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { - QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONObject) was received"); - isPostStatics=false; - try { - msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - asynClientOnFailure(statusCode,msg,headers); - } - - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { - isPostStatics=false; - QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONArray) was received" ); - asynClientOnFailure(statusCode,msg,headers); - } - - - - @Override - public void onFailure(int statusCode, org.apache.http.Header[] headers, String errorResponse, java.lang.Throwable throwable ) { - isPostStatics=false; - QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], String, Throwable) was received" ); - QLog.getLogger().d(dTAG, TAG+"errorResponse: "+errorResponse); - asynClientOnFailure(statusCode,msg,headers); - } - @Override - public void onProgress(int bytesWritten, int totalSize) { - // TODO Auto-generated method stub - super.onProgress(bytesWritten, totalSize); - int count = (int) ((bytesWritten * 1.0 / totalSize) * 100); - // 上传进度显示 - - QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize); - } - }); - - } - - void getJsonWs(RequestParams params,String url){ - - - QiYouApplication.get(url, params, new JsonHttpResponseHandler() { - @Override - public void onSuccess(int statusCode, Header[] headers, JSONObject response) { - - QLog.getLogger().d(dTAG, TAG+", onSuccess(int statusCode, Header[] headers, JSONObject response) was received"); - - processWebStatistics( response); - - -// } - } - - - String msg = ""; - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { - QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONObject) was received"); - - try { - msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - asynClientOnFailure(statusCode,msg,headers); - } - - @Override - public void onFailure(int statusCode, org.apache.http.Header[] headers, String errorResponse, java.lang.Throwable throwable ) { - QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], String, Throwable) was received" ); - QLog.getLogger().d(dTAG, TAG+"errorResponse: "+errorResponse); - asynClientOnFailure(statusCode,msg,headers); - } - - @Override - public void onProgress(int bytesWritten, int totalSize) { - // TODO Auto-generated method stub - super.onProgress(bytesWritten, totalSize); - int count = (int) ((bytesWritten * 1.0 / totalSize) * 100); - // 上传进度显示 - - QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize); - } - - }); - - } - - - void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){ - // Response failed :( - - if(headers!=null) - for (Header h : headers) { - QLog.getLogger().d(dTAG, TAG+" "+ h.getName() + " " + " " + h.getValue() + ""); - } - - QLog.getLogger().d(dTAG, TAG+" failure msg: "+ msg); - QLog.getLogger().d(dTAG, TAG+" failure statusCode: "+ statusCode); - // Hide Progress Dialog - - // When Http response code is '404' - if (statusCode == 404) { -// Toast.makeText(activity, -// "Requested resource not found" +msg, -// Toast.LENGTH_LONG).show(); - - } - // When Http response code is '500' - else if (statusCode == 500) { -// Toast.makeText(activity, -// "Something went wrong at server end" +msg, -// Toast.LENGTH_LONG).show(); - - } - // When Http response code is '500' - else if (statusCode == 417) { - - } - // When Http response code other than 404, 500 - else { -// Toast.makeText( -// activity, -// "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]" +msg, -// Toast.LENGTH_LONG).show(); - - } - exitService(); - } - - void exitService(){ - app.isStaticsticsDone=true; - app.isNewLogin=false; - this.stopSelf(); - } - - @Override - public void onDestroy() { - QLog.getLogger().d(dTAG, TAG+" going to destory"); - super.onDestroy(); - if (isExitApp){ -// this.getApplicationContext() -// System.exit(0); - } - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/About.java b/qy/src/main/java/com/qiyou/mb/android/ui/About.java deleted file mode 100644 index d0f46a2..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/About.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.qiyou.mb.android.ui; - -import android.os.Bundle; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.Button; -import android.widget.TextView; - -import com.qiyou.mb.android.Activity_qiyouBase; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.upgrade.UpdateManager; - -public class About extends Activity_qiyouBase { - public static final String TAG ="com.qiyou.About"; - public static final String dTAG ="com.qiyou"; - @Override - protected void onCreate(Bundle savedInstanceState) { -// updateActionBar(false); - super.onCreate(savedInstanceState); - app = (QiYouApplication) getApplication(); - setContentView(R.layout.readme); - setVersion(); -// initialSpeech(); - - } - private void setVersion(){ - final Button updateBtn = (Button) findViewById(R.id.readme_btnUpdate); - updateBtn.setOnClickListener( new OnClickListener() - { - @Override - public void onClick(View v) - { - checkUpdate(false); - } - }); - TextView versionName =(TextView)findViewById(R.id.readme_version); - versionName.setText(UpdateManager.getVersionName(app)+(QiYouConstant.DEVELOPER_MODE?":-D":"")); - - } - - //中文test - //中文测试 -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/ChartSpeedKm.java b/qy/src/main/java/com/qiyou/mb/android/ui/ChartSpeedKm.java deleted file mode 100644 index 625f296..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/ChartSpeedKm.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.qiyou.mb.android.ui; - -import android.os.Bundle; -import android.view.View; -import android.view.ViewGroup.LayoutParams; -import android.widget.LinearLayout; -import android.widget.TextView; - -import com.qiyou.mb.android.Activity_qiyouBase; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.ui.charts.AbstractChart; -import com.qiyou.mb.android.ui.charts.DistEleChartNoDown; -import com.qiyou.mb.android.ui.charts.DistKmSpeedChart; -import com.qiyou.mb.android.ui.charts.DistSpeedChart; -import com.qiyou.mb.android.utils.Utils; - -import java.util.ArrayList; - -//import com.iflytek.speech.ErrorCode; -//import com.iflytek.speech.ISpeechModule; -//import com.iflytek.speech.InitListener; -//import com.iflytek.speech.SpeechConstant; -//import com.iflytek.speech.SpeechSynthesizer; -//import com.iflytek.speech.SpeechUtility; -//import com.iflytek.speech.SynthesizerListener; - -public class ChartSpeedKm extends Activity_qiyouBase { - public static final String TAG ="com.qiyou.About"; - public static final String dTAG ="com.qiyou"; - @Override - protected void onCreate(Bundle savedInstanceState) { -// updateActionBar(false); - super.onCreate(savedInstanceState); - app = (QiYouApplication) getApplication(); - setContentView(R.layout.chart_speekm); - -// initialSpeech(); - - Bundle bundle = this.getIntent().getExtras(); - //接收name值 - chartType = bundle.getInt("type"); - trackId =bundle.getInt("id"); - setChartView(); - } - LinearLayout ll ; - int chartType=1; - int trackId; - private void setChartView(){ - TextView txt =(TextView) this.findViewById(R.id.txt_view_chart); -// if(app.getCurrentTrack()==null) return; - ll = (LinearLayout)this.findViewById(R.id.td_chart_speekm); - ArrayList trs = new ArrayList(); - if(app.getRecordingTrack().getTrackBean().getTrackId()==trackId) - trs.add(app.getRecordingTrack()); - else if(app.getCurrentTrack().getTrackBean().getTrackId()==trackId || trackId>0 && app.getCurrentTrack().getTrackBean().getSvrNumber()==trackId ) - trs.add(app.getCurrentTrack()); - else{ - ll.setVisibility(View.GONE); - txt.setText("图表加载错误"); - - return; - } - - - if(chartType==1){ - txt.setText("速度变化曲线图"); - geChart(trs,new DistSpeedChart()); - } - else if(chartType ==2){ - txt.setText("配速变化柱状图"); - geChart(trs,new DistKmSpeedChart()); - } - else if(chartType ==3){ - txt.setText("高度变化曲线图"); - geChart(trs,new DistEleChartNoDown()); - } - - } - - - void geChart(ArrayList trs,AbstractChart chart){ - - chart.setTrs(trs); - showCharts(chart.getChartView(this)); - - } - - - void showCharts(View v) - { - try{ - if(ll==null)return; - if(ll.getChildCount()>0) - ll.removeAllViews(); //this is must. -// int height=500; -// height =QiYouConstant.PV_INT_SCREEN_WIDTH/2; - int height=LayoutParams.MATCH_PARENT; - v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,height)); //set the layout, or will not show out - ll.addView(v); - }catch (Exception e) - { - Utils.logStackTrace(e, TAG); - } - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/MainActivity.java b/qy/src/main/java/com/qiyou/mb/android/ui/MainActivity.java deleted file mode 100644 index ab21dee..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/MainActivity.java +++ /dev/null @@ -1,2417 +0,0 @@ -package com.qiyou.mb.android.ui; - - -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.app.ActionBar; -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.app.Instrumentation; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.res.ColorStateList; -import android.graphics.Bitmap; -import android.graphics.Point; -import android.graphics.Typeface; -import android.location.Location; -import android.media.AudioManager; -import android.media.MediaScannerConnection; -import android.media.MediaScannerConnection.MediaScannerConnectionClient; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.StrictMode; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentTransaction; -import android.text.TextUtils; -import android.util.Log; -import android.util.TypedValue; -import android.view.GestureDetector; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.ShareActionProvider; -import android.widget.TabHost; -import android.widget.TabWidget; -import android.widget.TextView; -import android.widget.Toast; - -import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent; -import com.qiyou.mb.android.Activity_qiyouBase; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.Note; -import com.qiyou.mb.android.beans.basic.NoteMessage; -import com.qiyou.mb.android.beans.basic.StatTrack; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.service.LocationService; -import com.qiyou.mb.android.service.QNaviSvc; -import com.qiyou.mb.android.ui.charts.DistanceChart; -import com.qiyou.mb.android.ui.fragments.ActivityDetail; -import com.qiyou.mb.android.ui.fragments.ActivityHome; -import com.qiyou.mb.android.ui.fragments.GpxDetail_fragment; -import com.qiyou.mb.android.ui.fragments.GroupDetail; -import com.qiyou.mb.android.ui.fragments.GroupHome; -import com.qiyou.mb.android.ui.fragments.ImageDetailFragment; -import com.qiyou.mb.android.ui.fragments.ImagePager_fragment; -import com.qiyou.mb.android.ui.fragments.LocationPickerFragment; -import com.qiyou.mb.android.ui.fragments.LoginFragment; -import com.qiyou.mb.android.ui.fragments.NoteDetail; -import com.qiyou.mb.android.ui.fragments.NoteList; -import com.qiyou.mb.android.ui.fragments.NoteNew; -import com.qiyou.mb.android.ui.fragments.OfflineMaps_fragment; -import com.qiyou.mb.android.ui.fragments.Playback_fragment; -import com.qiyou.mb.android.ui.fragments.RegistFragment; -import com.qiyou.mb.android.ui.fragments.Route_fragment; -import com.qiyou.mb.android.ui.fragments.Scan_fragment; -import com.qiyou.mb.android.ui.fragments.TrackDetail_fragment; -import com.qiyou.mb.android.ui.fragments.TrackList_fragment; -import com.qiyou.mb.android.ui.fragments.TrackStatics_fragment; -import com.qiyou.mb.android.ui.fragments.TrackTabs_fragment; -import com.qiyou.mb.android.ui.fragments.Track_fragment; -import com.qiyou.mb.android.ui.fragments.UserDetails; -import com.qiyou.mb.android.ui.fragments.UserHome; -import com.qiyou.mb.android.ui.fragments.WebList_fragment; -import com.qiyou.mb.android.utils.DummyTabContent; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.log.QLog; -import com.tencent.tauth.IUiListener; -import com.tencent.tauth.Tencent; -import com.tencent.tauth.UiError; -import com.umeng.analytics.MobclickAgent; -import com.umeng.analytics.MobclickAgent.UMAnalyticsConfig; -import com.umeng.message.PushAgent; -import com.umeng.socialize.bean.RequestType; -import com.umeng.socialize.bean.SHARE_MEDIA; -import com.umeng.socialize.controller.UMServiceFactory; -import com.umeng.socialize.controller.UMSocialService; -import com.umeng.socialize.media.QQShareContent; -import com.umeng.socialize.media.QZoneShareContent; -import com.umeng.socialize.media.UMImage; -import com.umeng.socialize.sso.QZoneSsoHandler; -import com.umeng.socialize.sso.UMQQSsoHandler; -import com.umeng.socialize.weixin.controller.UMWXHandler; -import com.umeng.socialize.weixin.media.CircleShareContent; -import com.umeng.socialize.weixin.media.WeiXinShareContent; -import com.qiyou.mb.android.ui.fragments.QCode_fragment; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; - -import me.dm7.barcodescanner.zxing.ZXingScannerView; - -//import com.google.zxing.BarcodeFormat; - - -//@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) -//@SuppressLint("NewApi") -@SuppressLint("NewApi") -public class MainActivity extends Activity_qiyouBase{ - public static final String TAG ="com.qiyou.MainActivity"; - public static final String dTAG ="com.qiyou"; - - final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share",RequestType.SOCIAL); - - protected Handler handler = new Handler(); -// Nav_fragment nav_fragment; - public StatTrack statTrack; - LocationSendBackReceiver receiver; - IntentFilter filter; -// public boolean isShowingInput=false; - public boolean isMapActive=false; - public boolean is4Login=false; -// final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share"); - //found address - public AddressComponent addressComponent; - public String sharedAddressUrl; - public GEOaddress geoAddress; - public int addressTextId; - public float latToshow; - public float lngToshow; - public Tencent mTencent ; - - public boolean isNeedFresh = false; -// public Activity_bean currentAcitiviy; -// public Group_bean currentGroup; -// public User_bean currentUser; - private ZXingScannerView mScannerView; - - @Override - protected void onCreate(Bundle savedInstanceState) { -// startWelcome(); -// updateActionBar(false); - if (QiYouConstant.STRICT_MODE){ - - StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() - .detectLeakedSqlLiteObjects() - .detectLeakedClosableObjects() - .penaltyLog() - .penaltyDeath() - .build()); - } - -// app = (QiYouApplication) getApplication(); - super.onCreate(savedInstanceState); - long startTime =System.currentTimeMillis(); - -// Intent it = new Intent(MainActivity.this,Welcome.class); -// startActivity(it); - - - - // // QLog.getLogger().d(dTAG,TAG+" MainActivity.onCreate() called. time: " + startTime); - setContentView(R.layout.activity_main_new); - this.initialTabs(); - - /* app.restoreLastTracking(); - // QLog.getLogger().d(dTAG, TAG+"@@@@@@ activity.app.startTime : " +app.startTime); - app.getStaticsTracks();//异步获取track statistics - //TODO: review and to add waiting progress bar for the statistics,lasttrack,etc loading done. - app.initMapview(this); - app.startNetworkLocationRequest(true); - */ -// app.initialApplication(); - -// app.initMapview(this); - filter = new IntentFilter(QiYouConstant.ACTION_NEW_LOCATION_GETBACK); - filter.addCategory(Intent.CATEGORY_DEFAULT); - receiver = new LocationSendBackReceiver(); -// registerReceiver(receiver, filter); - - - - // // QLog.getLogger().d(dTAG,TAG+" MainActivity.onCreate(). cost time: " + (System.currentTimeMillis() - startTime)); - -// onReceive(getIntent()); - - app.initialImageLoader(); - - getScreenSize(); - - checkUpdate(true); - - - //-----umeng - - /*// 设置分享内容 - mController.setShareContent("友盟社会化组件(SDK)让移动应用快速整合社交分享功能,http://www.umeng.com/social"); - // 设置分享图片, 参数2为图片的url地址 - mController.setShareMedia(new UMImage(this, "http://www.umeng.com/images/pic/banner_module_social.png")); - - mController.getConfig().removePlatform( SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);*/ - initialUMSocialService(); - setVolume(); - initialQQAuth20(); - - } - - -// @Override -// public View onCreateView(View parent,String name, Context context,AttributeSet attrs){ -// return parent; -// -// } - - private void initialQQAuth20(){ - mTencent = Tencent.createInstance(QiYouConstant.TENCENT_APP_ID, this.getApplicationContext()); - mTencent.setOpenId(QiYouConstant.PV_OPEN_ID); - mTencent.setAccessToken(QiYouConstant.PV_ACCESS_TOKEN, String.valueOf(app.getTokenExpiresIn())); - } - -// String TENCENT_APPID="1104563148"; - - private void initialUMSocialService(){ - com.umeng.socialize.utils.Log.LOG = QiYouConstant.DEVELOPER_MODE; - String key ="550aa4e4fd98c5a25c000284" ; //old "4eaee02c527015373b000003" - if (!QiYouConstant.DEVELOPER_MODE){ - UMAnalyticsConfig config = new UMAnalyticsConfig(this,key , "huawei"); - MobclickAgent. startWithConfigure(config); - MobclickAgent.openActivityDurationTrack(false); - } - - PushAgent.getInstance(this).onAppStart(); //push start - - mController.getConfig().removePlatform(SHARE_MEDIA.DOUBAN, SHARE_MEDIA.RENREN); - //分享给QQ好友 - UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, QiYouConstant.TENCENT_APP_ID, "bB5QKjxU4MpHoCq0"); - qqSsoHandler.addToSocialSDK(); - - //分享到QQ空间 - QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, QiYouConstant.TENCENT_APP_ID, "bB5QKjxU4MpHoCq0"); - qZoneSsoHandler.addToSocialSDK(); - - String appID = "wxd929b04a9846a889"; - String appSecret = "8730a983fb9f0962b2f6610ddd2bf0b6"; - // 添加微信平台 - UMWXHandler wxHandler = new UMWXHandler(this,appID,appSecret); - wxHandler.addToSocialSDK(); - - // 支持微信朋友圈 - UMWXHandler wxCircleHandler = new UMWXHandler(this,appID,appSecret); - wxCircleHandler.setToCircle(true); - wxCircleHandler.addToSocialSDK(); - - mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, - SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA, SHARE_MEDIA.SMS); - } - - public UMSocialService defaultShare() { - return doShare("我在用爱骑驴记录运动数据","","",null,QiYouConstant.BASE_URL ); -// return shareImage("我在用爱骑驴记录运动数据","",getViewImage(),QiYouConstant.BASE_URL ); - } - - private UMSocialService shareImage( String title,String content, Bitmap bit, String targetUrl) { - -// mController.setShareMedia( new UMImage(this, getViewImage())); - mController.setShareImage( new UMImage(this, bit)); -// mController.setAppWebSite(targetUrl); -// content ="绿色出行,快乐运动,爱骑驴\n" +content; -// mController.setShareContent(content); - - - mController.openShare(this, true); - return mController; - } - -public UMSocialService doShareTrack( String title,String content, String imageUrl,Bitmap bit, String targetUrl) { - - /* - mController.getConfig().removePlatform(SHARE_MEDIA.DOUBAN, SHARE_MEDIA.RENREN); - //分享给QQ好友 - UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(ctx, "1104563148", "bB5QKjxU4MpHoCq0"); - qqSsoHandler.addToSocialSDK(); - - - mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, - SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA, SHARE_MEDIA.SMS); -*/ - // 设置分享图片, 参数2为图片的url地址 -// mController.setShareMedia( new UMImage(this, getViewImage())); - -// content ="绿色出行,快乐运动,爱骑驴\n" +content; - - content =TextUtils.isEmpty(content)?"绿色出行,快乐运动,爱骑驴\n" :content; - -// // QLog.getLogger().d(dTAG,"shared imgage url is:"+ imageUrl); - // // QLog.getLogger().d(dTAG,"shared targetUrl url is:"+ targetUrl); - - UMImage img; - if(bit!=null) - img = new UMImage(this, bit); - else - if(!TextUtils.isEmpty(imageUrl)){ - img = new UMImage(this, imageUrl); - }else{ -// if( isMapActive) -// img = new UMImage(this, R.drawable.ic_launcher); -// else - img = new UMImage(this, getViewImage()); - } - - mController.setShareMedia(img); -// mController.setShareContent(content); - - - QQShareContent qqShareContent = new QQShareContent(); - //设置分享文字 - qqShareContent.setShareContent(content); - //设置分享title - qqShareContent.setTitle(title); - //设置分享图片 - qqShareContent.setShareImage(img); - //设置点击分享内容的跳转链接 - qqShareContent.setTargetUrl(targetUrl); - mController.setShareMedia(qqShareContent); - - QZoneShareContent qqzoneShareContent = new QZoneShareContent (); - qqzoneShareContent.setShareContent(content); - //设置qq title - qqzoneShareContent.setTitle(title); - qqzoneShareContent.setShareImage(img); - qqzoneShareContent.setTargetUrl(targetUrl); - mController.setShareMedia(qqzoneShareContent); - - - WeiXinShareContent weixinContent = new WeiXinShareContent(); - //设置分享文字 -// weixinContent.setShareContent(content); - //设置title - weixinContent.setTitle(title); - //设置分享内容跳转URL -// weixinContent.setTargetUrl(targetUrl); - weixinContent.setShareImage(img); - mController.setShareMedia(weixinContent); - - - //CircleShareContent是和分享到微信好友不同的地方 - CircleShareContent circleMedia = new CircleShareContent(); -// circleMedia.setShareContent(content); - //设置朋友圈title - circleMedia.setTitle(title+"\n"+content); - circleMedia.setShareImage(img); -// circleMedia.setTargetUrl(targetUrl); - mController.setShareMedia(circleMedia); - - /* //分享到QQ空间 - QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(ctx, "1104563148", "bB5QKjxU4MpHoCq0"); - qZoneSsoHandler.addToSocialSDK(); - - mController.getConfig().setSsoHandler(new SinaSsoHandler()); - - mController.getConfig().setSsoHandler(new TencentWBSsoHandler()); - - String appID = "wxd929b04a9846a889"; - String appSecret = "8730a983fb9f0962b2f6610ddd2bf0b6"; - // 添加微信平台 - UMWXHandler wxHandler = new UMWXHandler(ctx,appID,appSecret); - wxHandler.addToSocialSDK(); - - // 支持微信朋友圈 - UMWXHandler wxCircleHandler = new UMWXHandler(ctx,appID,appSecret); - wxCircleHandler.setToCircle(true); - wxCircleHandler.addToSocialSDK();*/ - - mController.openShare(this, false); - - return mController; - } -public UMSocialService doShare( String title,String content, String imageUrl,Bitmap bit, String targetUrl) { - - /* - mController.getConfig().removePlatform(SHARE_MEDIA.DOUBAN, SHARE_MEDIA.RENREN); - //分享给QQ好友 - UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(ctx, "1104563148", "bB5QKjxU4MpHoCq0"); - qqSsoHandler.addToSocialSDK(); - - - mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, - SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA, SHARE_MEDIA.SMS); - */ - // 设置分享图片, 参数2为图片的url地址 -// mController.setShareMedia( new UMImage(this, getViewImage())); - -// content ="绿色出行,快乐运动,爱骑驴\n" +content; - - content =TextUtils.isEmpty(content)?"绿色出行,快乐运动,爱骑驴\n" :content; - -// // QLog.getLogger().d(dTAG,"shared imgage url is:"+ imageUrl); - // // QLog.getLogger().d(dTAG,"shared targetUrl url is:"+ targetUrl); - - UMImage img; - if(bit!=null) - img = new UMImage(this, bit); - else - if(!TextUtils.isEmpty(imageUrl)){ - img = new UMImage(this, imageUrl); - }else{ -// if( isMapActive) -// img = new UMImage(this, R.drawable.ic_launcher); -// else - img = new UMImage(this, getViewImage()); - } - - mController.setShareMedia(img); -// mController.setShareContent(content); - - - QQShareContent qqShareContent = new QQShareContent(); - //设置分享文字 - qqShareContent.setShareContent(content); - //设置分享title - qqShareContent.setTitle(title); - //设置分享图片 - qqShareContent.setShareImage(img); - //设置点击分享内容的跳转链接 - qqShareContent.setTargetUrl(targetUrl); - mController.setShareMedia(qqShareContent); - - QZoneShareContent qqzoneShareContent = new QZoneShareContent (); - qqzoneShareContent.setShareContent(content); - //设置qq title - qqzoneShareContent.setTitle(title); - qqzoneShareContent.setShareImage(img); - qqzoneShareContent.setTargetUrl(targetUrl); - mController.setShareMedia(qqzoneShareContent); - - - WeiXinShareContent weixinContent = new WeiXinShareContent(); - //设置分享文字 - weixinContent.setShareContent(content); - //设置title - weixinContent.setTitle(title); - //设置分享内容跳转URL - weixinContent.setTargetUrl(targetUrl); - weixinContent.setShareImage(img); - mController.setShareMedia(weixinContent); - - - //CircleShareContent是和分享到微信好友不同的地方 - CircleShareContent circleMedia = new CircleShareContent(); - circleMedia.setShareContent(content); - //设置朋友圈title - circleMedia.setTitle(title+"\n"+content); - circleMedia.setShareImage(img); - circleMedia.setTargetUrl(targetUrl); - mController.setShareMedia(circleMedia); - - /* //分享到QQ空间 - QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(ctx, "1104563148", "bB5QKjxU4MpHoCq0"); - qZoneSsoHandler.addToSocialSDK(); - - mController.getConfig().setSsoHandler(new SinaSsoHandler()); - - mController.getConfig().setSsoHandler(new TencentWBSsoHandler()); - - String appID = "wxd929b04a9846a889"; - String appSecret = "8730a983fb9f0962b2f6610ddd2bf0b6"; - // 添加微信平台 - UMWXHandler wxHandler = new UMWXHandler(ctx,appID,appSecret); - wxHandler.addToSocialSDK(); - - // 支持微信朋友圈 - UMWXHandler wxCircleHandler = new UMWXHandler(ctx,appID,appSecret); - wxCircleHandler.setToCircle(true); - wxCircleHandler.addToSocialSDK();*/ - - mController.openShare(this, false); - - return mController; - } - private Bitmap getViewImage(){ - View view =findViewById(R.id.realtabcontent); -// view = getWindow().getDecorView(); //截屏 -// return Utils.getBitmapFromView(view,QiYouConstant.SUBNAIL_PIC_SIZE,QiYouConstant.SUBNAIL_PIC_SIZE); -// return Utils.getBitmapFromView(view,QiYouConstant.PV_INT_SCREEN_WIDTH,QiYouConstant.PV_INT_SCREEN_HEIGHT-400 ); - -// if(this.isMapActive) -// return Utils.convertViewToBitmap(view); - return Utils.getBitmapFromView(view); - -// return Utils.convertViewToBitmap(view ); - - - - } - - - void ToastMsg(String msg,int length){ - Toast.makeText(MainActivity.this, msg, length).show(); - } - public void startNaviService(final int trackId,final boolean isSimulation,final boolean isContinue){ - MobclickAgent.onEvent(this,"startNavi"); - final Intent serviceIntent = new Intent(this, QNaviSvc.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_START_NAVI, 0); - stopService(serviceIntent); - -// lastStartDialog=!isContinue; //start new navi should not show dialog - - handler = new Handler(){ - @Override - public void handleMessage(Message msg) { - if (msg.what==10) { - app.naviTrackId=trackId; //TODO:this need current navi stopped. - startService(serviceIntent); - if(isSimulation){ - startTrackPlayBack(trackId); - }else if(!isContinue){ - tabTrackClicked();//start new track - } - } - }}; - - new Thread(){ - - @Override - public void run() { - int totalWaiting=0; -// if(app.naviTrackId>0){ - while(app.naviTrackId>0 && totalWaiting<10000){ - try { - Thread.sleep(500); - totalWaiting+=500; - // QLog.getLogger().dLog(dTAG,TAG + " to exit navigation totalWaiting "+totalWaiting); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - handler.sendEmptyMessage(10); - - - }}.start(); - } - - - public void startNaviService(final int trackId,final boolean isSimulation){ - - startNaviService(trackId,isSimulation,false); - - - } - -public void stopNaviService(){ - app.naviTrackId =-1; - app.isNaving=false; - Intent serviceIntent = new Intent(this, QNaviSvc.class); - stopService(serviceIntent); - app.clearLastNavId(); - - } - - - - public void showGpxTrackDetail(int typeId,int id,boolean isWebQuery) { - - showFragment(GpxDetail_fragment.newInstance(typeId,id,isWebQuery),GpxDetail_fragment.getFTag()); - -} - public void showTrackDetail(int typeId,int id) { - - /* if(id>0 && app.getRecordingTrack().getTrackBean().getTrackId()==id){ - showRecordingTrack(false); - return; - }*/ - - showFragment(TrackDetail_fragment.newInstance(typeId,id),TrackDetail_fragment.getFTag()); - - } - - /* - * check and confirm with user to start new track or continue the tracking one - */ - protected void newNaviDialog(final boolean isContinue) { - AlertDialog.Builder builder = new Builder(this); - builder.setMessage("是否继续上次导航?"); - builder.setTitle("提示"); - builder.setCancelable(false); - builder.setPositiveButton("确认", new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - int navId=app.getExistNaviID(); - app.clearLastNavId(); - - if( -// navId!=app.getCurrentTrack().getTrackBean().getTrackId()&& - navId!=app.getRecordingTrack().getTrackBean().getTrackId() ) - { - startNaviService(navId, false,isContinue); - } - lastStartDialog=true; - new Thread(){ - @Override - public void run() { - if(isContinue) - while(!app.isNaving) - try { - Thread.sleep(500); - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - startNewTrack(isContinue); - - - }}.start(); - - } - }); - builder.setNegativeButton("取消", new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - app.clearLastNavId(); - startNewTrack(isContinue); - } - }); - builder.create().show(); - } - - public void startNewTrackMap() { - //TODO: is to check the preference for exist recording track? - // // QLog.getLogger().dLog(TAG," Here , Start a New Track.................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - - - app.setRecordingTrack(new Track()); - startNewTrack(false); - app.speech("开始新运动",100); - } - /* - * continue the current track for recording. - */ - public void continueTrack() { - if(app.currentTrack==null -// ||app.currentTrack.getTrackBean().getTrackId()==app.getRecordingTrack().getTrackBean().getTrackId() - )return; - startNewTrack(true); - - } - private boolean lastStartDialog=false; - void startNewTrack(final boolean isContinue){ - - // // QLog.getLogger().d(dTAG,TAG+" "+"Start a new track..."); - if(!lastStartDialog - &&app.isLastNaviExist() -// && app.getExistNaviID()!=app.getCurrentTrack().getTrackBean().getTrackId() - && app.getExistNaviID()!=app.getRecordingTrack().getTrackBean().getTrackId() - && app.naviTrackId<=0){ - newNaviDialog(isContinue) ; - }else{ - - if(isContinue) - app.setRecordingTrack(app.getCurrentTrack()); - - if(isContinue) - app.continueTrack(app.currentTrack.getTrackBean().getType()); - else - app.initialNewTrack(TrackType.BIKE); - - - app.playBack=false; - if(!lastStartDialog||isContinue) - showRecordingTrack(false); - - app.forceDbUpdate(false); - - lastStartDialog=false; - } -// startNaviService();//TODO:remove - } - - - public void showRecordingTrack( boolean isContinue){ - - app.playBack=false; - - - - Track_fragment fragment; - String tag =Track_fragment.getFTag(); - if(isContinue){ - fragment = Track_fragment.newInstance(app.getCurrentTrack().getTrackBean().getTrackId()); - }else{ - fragment = (Track_fragment) getSupportFragmentManager().findFragmentByTag(tag); - if(fragment==null || fragment.trackId!=app.getRecordingTrack().getTrackBean().getTrackId()){ - fragment = Track_fragment.newInstance(app.getRecordingTrack().getTrackBean().getTrackId());; -// fragment = new Track_fragment(); -// Bundle args = new Bundle(); -// args.putInt(QiYouConstant.EXTRA_KEY_ID, app.getRecordingTrack().getTrackBean().getTrackId()); -// fragment.setArguments(args); - } - } - - showFragment(fragment,tag); - - updateTabTitle(); - } - - - /* - * play back - */ - public void startTrackPlayBack(Integer trackId) { - - MobclickAgent.onEvent(this,"playback"); -// LocationChangedCnt=0; - // // QLog.getLogger().d(dTAG,TAG+" "+" Start playback track "+ trackId ); - app.initialPlayBack(trackId); - // // QLog.getLogger().d(dTAG,TAG+" "+ "startTrackPlayBack, isPlayback: " + app.playBack ); -// if(app.isCanRecord()||app.playBack) - if(QiYouConstant.PLAYBACK_CAN_RECORD){ - - // // QLog.getLogger().d(dTAG,TAG+" "+"Start recording a playback..."); - if(app.recordingTrack!=null -// && app.recordingTrack.getTrackBean().getType() != QiYouConstant.TRACK_TYPE_COPY - && app.recordingTrack.getTrackBean().getType()!=TrackType.COPY - && app.recordingTrack.getTrackBean().getStatus()==TrackStatus.RECORDING - ){ - finishRecording(); -// newTrackDialog(); - } - - // // QLog.getLogger().d(dTAG,TAG+"start new track for playback recording."); - -// app.setRecordingTrack(new Track()); -// app.getRecordingTrack().startNewTrack(); -// app.initialNewTrack(QiYouConstant.TRACK_TYPE_COPY); - app.initialNewTrack(TrackType.COPY); - app.playBack=true; - app.getRecordingTrack().getTrackBean().setComment("拷贝自"+trackId); - // // QLog.getLogger().d(dTAG,TAG+"new track distance:" + app.getRecordingTrack().getTrackBean().getDistance()); - // // QLog.getLogger().d(dTAG,TAG+"new track start time:" + Utils.getFormatedTime(app.getRecordingTrack().getTrackBean().getStartTime())); - - } - if(app.currentActiveFragment!=Playback_fragment.getFTag()) - showFragment(Playback_fragment.newInstance(trackId),Playback_fragment.getFTag()); - app.forceDbUpdate(false); - // // QLog.getLogger().d(dTAG,TAG+" "+ "startTrackPlayBack, isPlayback: " + app.playBack ); - - - } - - - public void showTrackChart(ArrayList trs) { - - DistanceChart dc = new DistanceChart(); - dc.setTrs(trs); - Intent achartIntent =dc.execute(this); - startActivity(achartIntent); - } - - - public void showTrackStatics() { - -// showFragment(new testFragment(),testFragment.getFTag()); - // // QLog.getLogger().d(dTAG," TrackStatics starting show trackstatics... " ); -// if(app.currentActiveFragment ==TrackStatics_fragment.getFTag())return; - - TrackStatics_fragment fragment = (TrackStatics_fragment) getSupportFragmentManager().findFragmentByTag(TrackStatics_fragment.getFTag()); - if(fragment==null) fragment =new TrackStatics_fragment(); - - showFragment(fragment,TrackStatics_fragment.getFTag()); - // // QLog.getLogger().d(dTAG," TrackStatics starting show trackstatics... end" ); - - } - /* - * let user download offline maps - */ - public void showOffline() { - - showFragment(new OfflineMaps_fragment(),OfflineMaps_fragment.getFTag()); - - } - - public void showScanner() { -// if(app.currentActiveFragment==WebList_fragment.getFTag()) return; - - Scan_fragment fragment = (Scan_fragment) getSupportFragmentManager().findFragmentByTag(Scan_fragment.getFTag()); - if(fragment==null) fragment =new Scan_fragment(); - showFragment(fragment,Scan_fragment.getFTag()); - - } - - public void showQcode(String json) { -// if(app.currentActiveFragment==WebList_fragment.getFTag()) return; - - QCode_fragment fragment = (QCode_fragment) getSupportFragmentManager().findFragmentByTag(QCode_fragment.getFTag()); - if(fragment==null) fragment = QCode_fragment.newInstance(json); - showFragment(fragment,QCode_fragment.getFTag()); - - } - - - public void showWebList() { -// if(app.currentActiveFragment==WebList_fragment.getFTag()) return; - - WebList_fragment webList_fragment = (WebList_fragment) getSupportFragmentManager().findFragmentByTag(WebList_fragment.getFTag()); - if(webList_fragment==null) webList_fragment =new WebList_fragment(); - showFragment(webList_fragment,WebList_fragment.getFTag()); - - } - - public void showNoteList(int cate,int subCate) { - - NoteList notelist = (NoteList) getSupportFragmentManager().findFragmentByTag(NoteList.getFTag()); - if(notelist==null) notelist = NoteList.newInstance(cate,subCate); - showFragment(notelist,NoteList.getFTag()); - - } - - - public void showNewNote(Note note) { - - NoteNew noteNew = (NoteNew) getSupportFragmentManager().findFragmentByTag(NoteNew.getFTag()); - if(noteNew==null) { - noteNew = NoteNew.newInstance(note); - }else{ - // update the currentNote - noteNew.setCurrentNote(note); - } - showFragment(noteNew,NoteNew.getFTag()); - - } - - - - public void showEditNote(Note note,NoteMessage noteMsg) { - - NoteNew noteNew = (NoteNew) getSupportFragmentManager().findFragmentByTag(NoteNew.getFTag()); - if(noteNew==null) { - noteNew = NoteNew.newInstance(note,noteMsg); - }else{ - // update the currentNote,msg - noteNew.setCurrentNote(note); - noteNew.setCurrentMsg(noteMsg); - } - showFragment(noteNew,NoteNew.getFTag()); - - } - - - -public void showNoteDetail(Note note,NoteMessage noteMsg) { - - NoteDetail noteDetail = (NoteDetail) getSupportFragmentManager().findFragmentByTag(NoteDetail.getFTag()); - - if(noteDetail==null) { - noteDetail = NoteDetail.newInstance(note,noteMsg); - }else{ - // update the currentNote,msg - noteDetail.setCurrentNote(note); - noteDetail.setCurrentMsg(noteMsg); - } - - showFragment(noteDetail,NoteDetail.getFTag()); - - } - - public void showLocalTrackList() { -// if(app.currentActiveFragment==WebList_fragment.getFTag()) return; - - TrackList_fragment trackList_fragment = (TrackList_fragment) getSupportFragmentManager() - .findFragmentByTag(TrackList_fragment.getFTag()); - if(trackList_fragment==null) trackList_fragment =new TrackList_fragment(); - showFragment(trackList_fragment,TrackList_fragment.getFTag()); - - } - - /* - * show footmark's image in a pager photoviewer. - */ - public void showImagePagerFragment(int position,String[] urls){ - - if(app.currentActiveFragment!=ImagePager_fragment.getFTag()){ - - showFragment(ImagePager_fragment.newInstance(position,urls),ImagePager_fragment.getFTag()); - - } - } - - public void showLogin(){ - if(app.currentActiveFragment!=LoginFragment.getFTag()){ -// LoginFragment loginFragment = (LoginFragment) getSupportFragmentManager().findFragmentByTag(LoginFragment.getFTag()); -// if(loginFragment==null) loginFragment =LoginFragment.newInstance(); - LoginFragment loginFragment =LoginFragment.newInstance(); - showFragment(loginFragment,LoginFragment.getFTag()); -// showFragment(LoginFragment.newInstance(),LoginFragment.getFTag()); - - } - } - - public void showRegist(){ - if(app.currentActiveFragment!=RegistFragment.getFTag()){ - -// RegistFragment registFragment = (RegistFragment) getSupportFragmentManager().findFragmentByTag(RegistFragment.getFTag()); -// if(registFragment==null) registFragment =RegistFragment.newInstance(); - RegistFragment registFragment =RegistFragment.newInstance(); - showFragment(registFragment,LoginFragment.getFTag()); - -// showFragment(RegistFragment.newInstance(),RegistFragment.getFTag()); - - } - } - public void showActvityHome( Activity_bean activity){ - if(app.currentActiveFragment!=ActivityHome.getFTag()){ - - /* ActivityDetail actFragment = (ActivityDetail) getSupportFragmentManager().findFragmentByTag(ActivityDetail.getFTag()); - if(actFragment==null) actFragment =ActivityDetail.newInstance(); - actFragment.setCurrentAct(activity); - */ - - ActivityHome actFragment =ActivityHome.newInstance(activity); - - showFragment(actFragment,ActivityHome.getFTag()); - } - } - - public void showActvity( Activity_bean activity){ - if(app.currentActiveFragment!=ActivityDetail.getFTag()){ - - /* ActivityDetail actFragment = (ActivityDetail) getSupportFragmentManager().findFragmentByTag(ActivityDetail.getFTag()); - if(actFragment==null) actFragment =ActivityDetail.newInstance(); - actFragment.setCurrentAct(activity); - */ - - ActivityDetail actFragment =ActivityDetail.newInstance(activity); - - showFragment(actFragment,ActivityDetail.getFTag()); - } - } - - public void showGroup(Group_bean group){ - if(app.currentActiveFragment!=GroupDetail.getFTag()){ - - /* GroupDetail fragment = (GroupDetail) getSupportFragmentManager() - .findFragmentByTag(GroupDetail.getFTag()); - if(fragment==null) fragment =GroupDetail.newInstance(); - fragment.setCurrentGroup(group);*/ - - GroupDetail fragment =GroupDetail.newInstance(group); - showFragment(fragment,GroupDetail.getFTag()); - - - } - } - public void showGroupHome(Group_bean group){ - if(app.currentActiveFragment!=GroupHome.getFTag()){ - - - - GroupHome fragment =GroupHome.newInstance(group); - showFragment(fragment,GroupHome.getFTag()); - - - } - } - public void showLocationFinder() { - - LocationPickerFragment lpfFragment = (LocationPickerFragment) getSupportFragmentManager().findFragmentByTag(LocationPickerFragment.getFTag()); - if(lpfFragment==null) lpfFragment =new LocationPickerFragment(); - showFragment(lpfFragment,LocationPickerFragment.getFTag()); - - } - - public void showUserDetails(User_bean user/*,int userId*/) { -// if(app.currentActiveFragment==WebList_fragment.getFTag()) return; - - /*UserDetails fragment = (UserDetails) getSupportFragmentManager().findFragmentByTag(UserDetails.getFTag()); - if(fragment==null) fragment = UserDetails.newInstance(); - fragment.setCurrentUser(user);*/ - - //TODO to use above reuse fragment mechnism - - UserDetails fragment = UserDetails.newInstance(user); - showFragment(fragment,UserDetails.getFTag()); - - } - - public void showUserHome(User_bean user/*,int userId*/) { - - UserHome fragment = (UserHome) getSupportFragmentManager().findFragmentByTag(UserHome.getFTag()); - if(fragment==null) fragment = UserHome.newInstance(); - fragment.setCurrentUser(user); - - //TODO to use above reuse fragment mechnism - -// UserHome fragment = UserHome.newInstance(user); - showFragment(fragment,UserHome.getFTag()); - - } - - - - public void showRoute(int trackId){ - - Route_fragment route_fragment = (Route_fragment) getSupportFragmentManager().findFragmentByTag(Route_fragment.getFTag()); - if(route_fragment==null) route_fragment = Route_fragment.newInstance(trackId); - route_fragment.trackId=trackId; - if(app.currentActiveFragment!=Route_fragment.getFTag()){ - - showFragment(route_fragment,Route_fragment.getFTag()); - - } - -// route_fragment = (Route_fragment) getSupportFragmentManager().findFragmentByTag(Route_fragment.getFTag()); -// route_fragment = (Route_fragment) getSupportFragmentManager().findFragmentByTag(Route_fragment.getFTag()); - } - - private void showFragment(Fragment fragment,String fragmentTag) - { - - FragmentManager fm = getSupportFragmentManager(); - FragmentTransaction ft = fm.beginTransaction(); - - if (findViewById(R.id.realtabcontent) != null) { //realtabcontent - - ft.replace(R.id.realtabcontent, fragment,fragmentTag); - // // QLog.getLogger().d(dTAG, " before commit,getSupportFragmentManager().findFragmentByTag: "+fragmentTag +", result is:"+getSupportFragmentManager().findFragmentByTag(fragmentTag)); - Fragment lastFragmeng = getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment); - if(! (lastFragmeng instanceof IlocationFragment //see last fragment is track_fragment - && fragmentTag.equalsIgnoreCase(TrackDetail_fragment.getFTag()) - )) { //1.前一个fragment为 track_fragment 2.当前新fragment为detail_fragment, 则不放入回退栈 -// if(!(fragment instanceof RegistFragment)) - ft.addToBackStack(null); //add to backstack. - } - - } - - else - { - try{ - ft.add(R.id.realtabcontent, fragment,fragmentTag); - }catch(Exception e){ - Utils.logStackTrace(e, dTAG); - } - } - // ft.show(bmapview_fragment); - app.currentActiveFragment =fragmentTag; -// ft.setTransition(2500);//TRANSIT_FRAGMENT_OPEN - ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); -// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); -// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); -// ft.setTransition(FragmentTransaction.TRANSIT_EXIT_MASK); -// ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK); -// ft.setTransition(FragmentTransaction.TRANSIT_UNSET); -// ft.setTransition(FragmentTransaction.TRANSIT_EXIT_MASK); -// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); -// ft.setTransition(FragmentTransaction.TRANSIT_NONE); - -// ft.commit(); - ft.commitAllowingStateLoss(); -// fm.executePendingTransactions(); - - - // // QLog.getLogger().d(dTAG, " after commit,getSupportFragmentManager().findFragmentByTag: "+fragmentTag +", result is:"+getSupportFragmentManager().findFragmentByTag(fragmentTag)); -// Fragment frgmnt = getSupportFragmentManager().findFragmentByTag(fragmentTag); -// int i=0; -// i++; -// i++; - - } - - - - - public void startPrefActivity() - { - Intent intent = new Intent(this,SettingsActivity.class); - this.startActivity(intent); - } - /*public void startSpeech() - { - Intent intent = new Intent(this,TtsDemo.class); - this.startActivity(intent); - } - */ - - - public void showAbout() - { - Intent intent = new Intent(this,About.class); - this.startActivity(intent); - } - - public void showWeb() - { - Intent intent = new Intent(this,Website.class); - this.startActivity(intent); - } - - long lastNetworkLocationRequest=0; - class LocationSendBackReceiver extends BroadcastReceiver { - - @Override - public void onReceive(Context context, Intent intent) { - - try{ - - if (System.currentTimeMillis() - firstTime < 800) { //back key hit - return; - } - -// if(app.canStopNetworkRequest() ||app.getRecordingTrack().getTrackBean().getStatus()!= TrackStatus.RECORDING &&!app.playBack &&!app.isRouting &&!app.isLocationFinding) - if(app.getRecordingTrack().getTrackBean().getStatus()!= TrackStatus.RECORDING &&!app.playBack &&!app.isRouting &&!app.isLocationFinding) { - Log.d(dTAG,TAG+" track id:"+app.getRecordingTrack().getTrackBean().getTrackId() +",status: "+app.getRecordingTrack().getTrackBean().getStatus() - +",start time: "+ app.getRecordingTrack().getTrackBean().getStartTime()); - Log.d(dTAG,TAG+" No active tracking activity,stoping the gps request..."); -// if(Utils.isLocOfGPS(loc)) - app.stopAndroidGPSRequest(); - return; - } - - final Location navLoc =intent.hasExtra( QiYouConstant.NEW_NAVIFO_MSG)? (Location)intent.getExtras().get(QiYouConstant.NEW_NAVIFO_MSG):null; - - /*if(navLoc!=null){ - // QLog.getLogger().d(dTAG,TAG+" get navi msg of" + navLoc.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG)); - }*/ - - final Location location; - location= intent.hasExtra( QiYouConstant.NEW_LOCATION)? (Location)intent.getExtras().get(QiYouConstant.NEW_LOCATION) :null; - - - - /* if(location ==null){ - // QLog.getLogger().d(dTAG, String.format("%s, app.isNetworkLocationRequestStarted :%s,location == null? %s", TAG, app.isNetworkLocationRequestStarted,location == null)); - - }*/ - if(!app.isNetworkLocationRequestStarted && Utils.isLocOfMonitor(location) - &&System.currentTimeMillis() -lastNetworkLocationRequest> QiYouConstant.MAX_GPS_SPAN*4 - ){ -// if(location == null){ - // QLog.getLogger().d(dTAG, String.format("%s, app.startNetworkLocationRequest()", TAG )); - app.startNetworkLocationRequest(false); - lastNetworkLocationRequest =System.currentTimeMillis(); - }else - if(app.isNetworkLocationRequestStarted - && Utils.isLocOfGPS(location) -// && !intent.hasExtra(QiYouConstant.ACTION_NEW_COARSE_LOCATION) -// && location!=null - - ) - { - app.stopNetworkLocationRequest(); - - } - final boolean isPause = location==null?false:(Utils.isLocOfGPS(location)?location.getSpeed()==0:false); - - // final boolean isNoSigNal =intent.getBooleanExtra(QiYouConstant.EXTRA_KEY_NO_LOCCATION_SIGNAL, false); - // if(isNoSigNal)Log.d(dTAG,TAG+" Lost the gps signal..."); - // // QLog.getLogger().d(dTAG,TAG+" CurrentActiveFragment... "+app.currentActiveFragment); - - - if(!TextUtils.isEmpty(app.currentActiveFragment)) - { - final Fragment frgmnt = getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment); - if(frgmnt instanceof IlocationFragment && !app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag())){ -// // QLog.getLogger().d(dTAG, String.format(" app.currentActiveFragment: %s", app.currentActiveFragment )); - handler.post(new Runnable(){ - @Override - public void run() { -// ((IlocationFragment)frgmnt).updateUI(location, Pausingtime>0); - ((IlocationFragment)frgmnt).updateUI(location,isPause); - if(navLoc!=null) - ((IlocationFragment)frgmnt).navInfo(navLoc); - } - }); - } - } - - // Log.d(TAG,"get Pausing time from location service:"+ Pausingtime.toString()); - }catch (Exception e) - { - Log.d(dTAG, TAG + " " +e.getMessage()); - Log.d(dTAG,TAG +" Error while handling location changes information."); - } - } - - } - - - long firstTime =0; - @Override - public boolean onKeyUp(int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_BACK) { - -// tabHost.getTabWidget().setVisibility(View.VISIBLE); - - if(!app.currentActiveFragment.equalsIgnoreCase(ImageDetailFragment.getFTag()) - && !app.currentActiveFragment.equalsIgnoreCase(LoginFragment.getFTag()) - && !app.currentActiveFragment.equalsIgnoreCase(RegistFragment.getFTag()) - && !app.currentActiveFragment.equalsIgnoreCase(OfflineMaps_fragment.getFTag()) - && !app.currentActiveFragment.equalsIgnoreCase(UserDetails.getFTag()) - && !app.currentActiveFragment.equalsIgnoreCase(UserHome.getFTag()) - && !app.currentActiveFragment.equalsIgnoreCase(tabList) - && !app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag()) - && !app.currentActiveFragment.equalsIgnoreCase(QCode_fragment.getFTag())) - - { - - updateTabVisibility(true); - - } - - - -// getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment).onHiddenChanged(true); - - /* Fragment frgmnt = getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment); - if(frgmnt instanceof IlocationFragment ) { - this.showFragment(new Nav_fragment(), Nav_fragment.getFTag());return true; - }*/ - int cnt=0; -// Utils.hideSoftKeyboard(this); -// if( ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE)).isActive()) -// if(isShowingInput) -// return true; - - - if(app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag())){ -// showWebList(); - showLocalTrackList(); - return true; - } - - - /* - if(app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag()) -// ||app.currentActiveFragment.equalsIgnoreCase(GpxDetail_fragment.getFTag()) // why - ) - while(true){ - { - cnt++; - if(cnt>3)showWebList() ; - // // QLog.getLogger().d(dTAG, TAG +" back count is:" + cnt); - - // // QLog.getLogger().d(dTAG, TAG +" app.currentActiveFragment is:" + app.currentActiveFragment); - - if( app.currentActiveFragment==WebList_fragment.getFTag() - || app.currentActiveFragment==TrackStatics_fragment.getFTag() - - ) - return true; - - -// if( app.currentActiveFragment == Nav_fragment.getFTag()) -// break; -// if( app.currentActiveFragment == TrackDetail_fragment.getFTag()) -// break; - Fragment frgmnt = getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment); - if(frgmnt ==null )break; - - FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); - fragmentTransaction.remove(frgmnt).commit(); - super.onKeyUp(keyCode, event); -// frgmnt.onDestroy(); - } - - } */ - - - -// if(!app.currentActiveFragment.equalsIgnoreCase(Nav_fragment.getFTag())) -// if(tabHost.getTabWidget().getVisibility()==View.GONE) -// if(!app.currentActiveFragment.equalsIgnoreCase(tabHome)) - - if(app.currentActiveFragment.equalsIgnoreCase(RegistFragment.getFTag())){ - this.isTabHome(); - return true; - } - if(app.currentActiveFragment.equalsIgnoreCase(LoginFragment.getFTag())){ - this.isTabHome(); - return true; - } - - if(app.currentActiveFragment.equalsIgnoreCase(tabList)){ - this.isTabHome(); - return true; -// firstTime = System.currentTimeMillis(); - -// return super.onKeyUp(keyCode, event); - } - -// if(app.currentActiveFragment.equalsIgnoreCase(TrackList_fragment.getFTag())){ -// this.isTabHome(); -// return true; -// } - if( app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag())){ - long secondTime = System.currentTimeMillis(); - if (secondTime - firstTime > 800) {//如果两次按键时间间隔大于800毫秒,则不退出 - String msg= "再按一次将退出路书编辑" ; - Toast.makeText(MainActivity.this, msg, - Toast.LENGTH_SHORT).show(); - firstTime = secondTime;//更新firstTime - -// if( app.currentActiveFragment.equalsIgnoreCase(tabTrack)) -// tabHost.getTabWidget().setVisibility(View.GONE); - - return true; - } - } - - if(!app.currentActiveFragment.equalsIgnoreCase(tabHome) - && !app.currentActiveFragment.equalsIgnoreCase(tabTrack) - ) - return super.onKeyUp(keyCode, event); - - long secondTime = System.currentTimeMillis(); - if (secondTime - firstTime > 800) {//如果两次按键时间间隔大于800毫秒,则不退出 - String msg=app.canExit()?"再按一次将退出":"再按一次将在后台继续记录"; - Toast.makeText(MainActivity.this, msg, - Toast.LENGTH_SHORT).show(); - firstTime = secondTime;//更新firstTime - -// if( app.currentActiveFragment.equalsIgnoreCase(tabTrack)) -// tabHost.getTabWidget().setVisibility(View.GONE); - - return true; - } else { - //if(app.isCanRecord() && app.recordingTrack!=null && app.recordingTrack.getTrackBean().getStatus()==QiYouConstant.TRACK_STATUS_TRACKING ) -// if(app.isCanRecord() && !QiYouConstant.DEVELOPER_MODE) - return exit(); - } - } - try{ - return super.onKeyUp(keyCode, event); - } - catch(Exception e){ - Utils.logStackTrace(e, TAG); - return true; - } - } - - void saveExit(){ - if(!app.canExit()) - Toast.makeText(this, "系统将结束当前运动并退出", Toast.LENGTH_LONG ).show(); - cancelRecording(); - finishRecording(); - app.ExitApp(); - - } - - boolean exit(){ - - if(app.canExit()){ -// Toast toast= Toast.makeText(this, "谢谢使用,再见!", Toast.LENGTH_LONG ); -// toast.show(); - this.finish(); - QLog.getLogger().d(dTAG,TAG+" activity finished." ); - app.ExitApp(); - return false; - } - else{ - Toast toast= Toast.makeText(this, "结束运动之前,系统将在后台继续为您记录", Toast.LENGTH_LONG ); - toast.show(); -// toast= Toast.makeText(this, " ", Toast.LENGTH_LONG ); -// toast.show(); - Intent intent = new Intent(Intent.ACTION_MAIN); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.addCategory(Intent.CATEGORY_HOME); - startActivity(intent); -// return super.onKeyUp(keyCode, event); - return true; - } - } - public void cancelRecording(){ - Log.i(dTAG,TAG + " cancelRecording "); - if(app.recordingTrack!=null && app.recordingTrack.getTrackBean().getTrackId()<=0){ - app.recordingTrack =null; -// app.setLastRecordingIdStartTime(); - app.clearLastRecordingIdStartTime(); - // // QLog.getLogger().d(dTAG,TAG+" setLastRecordingIdStartTime 2" ); -// Log.i(dTAG,TAG + " to stop gps request "); -// app.forceDbUpdate(true); - app.stopAndroidGPSRequest(); - app.stopNetworkLocationRequest(); - app.unregTimeTick(); - stopNaviService(); - } -// showFragment(new Nav_fragment(),Nav_fragment.getFTag()); - - - } - - public void pausingTrack(boolean is2Pause){ - - if(is2Pause){ - app.updateTrackStatus(QiYouConstant.TRACK_STATUS_PAUSED); - app.stopAndroidGPSRequest(); - app.updatePauseParameters(); - } - else{ - app.updateTrackStatus(QiYouConstant.TRACK_STATUS_TRACKING); - app.getPausedTime(true);//update manual paused time - } - - - - - - } - - public void clearRecordingCache(){ - Intent serviceIntent = new Intent(this, LocationService.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_FINISH_RECORDING, 1); - startService(serviceIntent); - // // QLog.getLogger().d(dTAG,TAG+" cleaning requested." ); - } - - - public void finishRecording(){ - app.forceDbUpdate(true); - -// long st=System.currentTimeMillis(); - app.clearLastRecordingIdStartTime(); - // // QLog.getLogger().dLog(TAG, "activity.finishRecording() cost time:" +(System.currentTimeMillis()-st)); - - if(null != app.currentTrack && app.currentTrack.getTrackBean().getTrackId()>0){ - app.getTrackCache().put( app.currentTrack.getTrackBean().getTrackId(), app.currentTrack); - } -// app.clearLastRecordingIdStartTime(); - - - if( app.recordingTrack!=null && TrackStatus.FINISHED != app.recordingTrack.getTrackBean().getStatus()){ - - try{ - - - if( app.recordingTrack.getTrackBean().getLastWp().getWb().getSumDist() - app.recordingTrack.getTrackBean().getSportTime()){ - app.recordingTrack.getTrackBean().setSportTime(app.recordingTrack.getTrackBean().getLastWp().getWb().getSportTime()); - } - - app.recordingTrack.getTrackBean().setDistance(app.recordingTrack.getTrackBean().getLastWp().getWb().getSumDist()); - app.recordingTrack.getTrackBean().setSportTime(app.recordingTrack.getTrackBean().getLastWp().getWb().getSportTime()); - -// st=System.currentTimeMillis(); - app.updateStatistics(); - // app.writeStatiscs(); - // // QLog.getLogger().dLog(TAG, " app.updateStatistics() cost time:" +(System.currentTimeMillis()-st)); - app.recordingTrack.finishRecording(); - - app.recordingTrack.getTrackBean().setStatus(TrackStatus.FINISHED); - }catch(NullPointerException e){ - app.clearLastRecordingIdStartTime(); - Utils.logStackTrace(e, TAG); - } -// app.setLastRecordingIdStartTime(); -// app.clearLastRecordingIdStartTime(); - - /* if(app.mStatistics!=null){ - app.mStatistics.mergeTrack( app.recordingTrack); - app.writeStatiscs(); - }*/ - -// st=System.currentTimeMillis(); - app.setCurrentTrack( app.getRecordingTrack()); - app.recordingTrack=null; - app.updateTrackStatus(app.getCurrentTrack().getTrackBean().getTrackId(),QiYouConstant.TRACK_STATUS_FINISHED); - // // QLog.getLogger().dLog(TAG, " updateTrackStatus cost time:" +(System.currentTimeMillis()-st)); - - } - app.clearLastRecordingIdStartTime(); - app.initialTrackParameters(); - app.stopNetworkLocationRequest(); - - stopNaviService(); - // QLog.getLogger().dLog(TAG, " navi stopped"); -// st=System.currentTimeMillis(); - - app.syncStatistics(); - - // // QLog.getLogger().dLog(TAG, " app.syncStatistics() cost time:" +(System.currentTimeMillis()-st)); - -// updateTabTitle(); - } - - boolean blDialog; - /* - * check and confirm with user to start new track or continue the tracking one - */ - protected void newTrackDialog(final boolean isContinue) { - AlertDialog.Builder builder = new Builder(this); - builder.setMessage("是否终止当前记录,并开始新的记录?"); - builder.setTitle("提示"); - builder.setCancelable(false); - builder.setPositiveButton("确认", new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - finishRecording(); - - // app.forceDbUpdate(true); - // app.setPreferences(false,false); - // app.playbackPaused=false; - if(app.playBack) - startTrackPlayBack(app.currentTrackId); - else{ - if(isContinue) - // continueTrack(); - showRecordingTrack(isContinue); - else - startNewTrackMap(); - } - //notice the UI - - - dialog.dismiss(); - } - }); - - builder.setNegativeButton("取消", new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - }); - builder.create().show(); - } - - - -// public StatisticsTrack statisticsTrack; - - - private ShareActionProvider mShareActionProvider; - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - getMenuInflater().inflate(R.menu.main, menu); - /* - MenuItem item = menu.findItem(R.id.menu_item_share); - // Fetch and store ShareActionProvider - mShareActionProvider = (ShareActionProvider) item.getActionProvider();*/ - - return true; - } - // Call to update the share intent - private void setShareIntent(Intent shareIntent) { - if (mShareActionProvider != null) { - mShareActionProvider.setShareIntent(shareIntent); - } - } - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: -// KeyEvent kv = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK); -// this.onKeyUp(KeyEvent.KEYCODE_BACK, kv); -// ActionBar ab =getActionBar(); -// if(ab!=null){ - if( tabHost.getTabWidget().getVisibility() ==View.GONE) - new Thread(){ - @Override - public void run() { - try{ - Instrumentation inst = new Instrumentation(); - inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); - } - catch (Exception e) { - Log.e("Exception when onBack", e.toString()); - } - } - }.start(); -// } - return true; - /* case R.id.action_settings: - startPrefActivity(); - return true; - case R.id.action_offline: - showOffline(); - return true;*/ - case R.id.action_about: - showAbout(); - return true; - case R.id.action_exit: - saveExit(); -// exit(); - return true; - case R.id.action_route: - showRoute(0); - return true; - /*case R.id.action_login: - showLogin(); - return true;*/ - - case R.id.menu_item_share: - doShare(); - return true; - case R.id.action_main: - isTabHome(); - return true; - /* case R.id.action_history: - this.showLocalTrackList(); - return true; */ - - /*case R.id.action_regist: - showRegist(); - return true; */ - - - -// case R.id.action_navi: -// startNaviService(); -// return true; - -// case R.id.action_speech: -// startSpeech(); -// return true; - - - /* case R.id.action_listview: - Intent intent = new Intent(this,CursorDSLV.class); - - this.startActivity(intent); - return true;*/ - - - default: - - Fragment frgmnt = getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment); - if(frgmnt instanceof TrackTabs_fragment ){ - ((TrackTabs_fragment)frgmnt).onContextItemSelected(item); - } - } - return false; - } - - @SuppressLint("NewApi") - @Override - public boolean onPrepareOptionsMenu(Menu menu){ -// final int notShow=0; -// final int alwaysShow =2; - super.onPrepareOptionsMenu(menu); -// MenuItem mainItem=menu.findItem( R.id.action_main); -// mainItem.setShowAsAction(app.currentActiveFragment.equalsIgnoreCase(tabHome)?notShow:alwaysShow); - - /*MenuItem loginItem=menu.findItem( R.id.action_login); - String loginTitle ="登录";//loginItem.getTitle().toString(); - String loginUser =*//* app.user.getUserbean().getAccount();*//*app.user.getUserbean().getUserName(); - if(TextUtils.isEmpty(loginUser))return true; - loginUser=loginUser.length()>20?loginUser.substring(0, 20):loginUser; - loginTitle += ( app.user.getUserbean().getId()<=0?"":" ( " + loginUser +" )"); - loginItem.setTitle(loginTitle);*/ - - return true; - - } - - - public void doShare(){ - /* Intent shareIntent=getShareIntent(); - mShareActionProvider.setShareIntent(shareIntent);*/ - - if(isMapActive){ - ToastMsg("对不起,暂不支持分享地图",Toast.LENGTH_SHORT); - }else - defaultShare(); - - } - - public void doShare(Intent shareIntent){ - - mShareActionProvider.setShareIntent(shareIntent); - } - - /*public Intent getShareIntent() { - Intent intent = new Intent(Intent.ACTION_SEND); - intent.putExtra(Intent.EXTRA_TEXT, "这里是要分享的文字"); - intent.setType("text/plain"); -// intent.setType("image/*"); - Intent.createChooser(intent, "Share"); - - if(app.getCurrentTrack().getTrackBean().getTrackId()>0){ - Intent shareIntent = new Intent(Intent.ACTION_SEND); - // Uri uri = Uri.parse("file:///sdcard/image.jpg"); - FileCache fc= new FileCache(app); - Uri uri =fc.getCachedUri(app.getCurrentTrack().getStaticMap()); - shareIntent.setType("* / * "); - shareIntent.putExtra(Intent.EXTRA_TEXT, "Body text of the new status"); - shareIntent.putExtra(Intent.EXTRA_STREAM, uri); - shareIntent.putExtra(Intent.EXTRA_SUBJECT, " EXTRA_SUBJECT text of the new status"); - shareIntent.putExtra(Intent.EXTRA_TITLE, " TITLE text of the new status"); - return shareIntent; - } - - - return intent; - } - */ - - - /* - * bottom tabs - */ - - TabHost tabHost; - TabWidget tabWidget; - LinearLayout bottom_layout; - int CURRENT_TAB = -1; //设置常量 - - final int TRACK_STATISTICS=0; - final int TRACK_TAB=1; - final int TRACK_WEB=2; -// final int TRACK_HISTORY =1; -// final int TRACK_TAB=2; -// final int TRACK_NOTE=3; -// final int TRACK_WEB=4; - - Track_fragment track_fragment; - WebList_fragment webList_fragment; - TrackStatics_fragment trackStatics_fragment; -// Me_Fragment meFragment; -// android.support.v4.app.FragmentTransaction ft; - - final String tabHome =TrackStatics_fragment.getFTag() ; - final String tabList=TrackList_fragment.getFTag(); - final String tabWeb=WebList_fragment.getFTag(); - final String tabTrack=Track_fragment.getFTag(); - final String tabNote=NoteList.getFTag(); - - final String tabLongway="tabLongway"; - final String tabSetup="setup"; - ColorStateList colorSelected ; - ColorStateList colorUnselected ; - - RelativeLayout tabIndicator_home,tabIndicator_history,tabIndicator_track,tabIndicator_web,tabIndicator_note;//,tabIndicator4,tabIndicator5; - - void initialTabs(){ - // // QLog.getLogger().d(dTAG, TAG+" app.currentActiveFragment:"+app.currentActiveFragment +",initialTabs() called."); - findTabView(); - tabHost.setup(); - colorUnselected = getResources().getColorStateList(R.color.white/*darkgrey*/); - colorSelected = getResources().getColorStateList(R.color.white); - - /** 监听*/ - TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener(){ - @Override - public void onTabChanged(String tabId) { - - - - // // QLog.getLogger().d(dTAG, TAG+" onTabChanged: app.currentActiveFragment,tabId is:"+ tabId +",CURRENT_TAB is: " +CURRENT_TAB); - - ((TextView)tabIndicator_track.getChildAt(1)).setTextColor(colorSelected); - /** 如果当前选项卡是home */ - if(tabId.equalsIgnoreCase(tabHome) /*&&CURRENT_TAB!=TRACK_STATISTICS*/){ - // // QLog.getLogger().d(dTAG," TrackStatics starting tab clicked to show trackstatics... " ); - isTabHome(); - - /** 如果当前选项卡是Me */ - } - else if(tabId.equalsIgnoreCase(tabList) /* &&CURRENT_TAB!=TRACK_HISTORY*/){ -// CURRENT_TAB = 2; - - showLocalTrackList(); - /** 如果当前选项卡是history list */ - } - else if(tabId.equalsIgnoreCase(tabTrack) /* &&CURRENT_TAB!=TRACK_TAB*/){ - tabTrackClicked(); - - - /** 如果当前选项卡是track */ - } else if(tabId.equalsIgnoreCase(tabNote) /*&&CURRENT_TAB!=3*/){ -// showNoteList(); - - /** 如果当前选项卡是list */ - } else if(tabId.equalsIgnoreCase(tabWeb) /*&&CURRENT_TAB!=TRACK_HISTORY*/){ - isTabList(); - - } - - setSelectedTabhostStyle(tabHost); - } - - }; - //设置初始选项卡 -// tabHost.setCurrentTab(0); - tabHost.setOnTabChangedListener(tabChangeListener); - initTab(); - /** 设置初始化界面 */ -// tabHost.setCurrentTab(TRACK_STATISTICS); - - if(app.isLastTrackExist()){ - tabHost.setCurrentTab(TRACK_TAB); -// tabTrackClicked(); - } - - setSelectedTabhostStyle(tabHost); - } - -/* public void setSelectedTabhostStyle(){ - TabWidget tabWidget = tabHost.getTabWidget(); - for (int i =0; i < tabWidget.getChildCount(); i++) { - - TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title); - // tv.setTextSize(15); - if(i!=tabHost.getCurrentTab()){ -// tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray); - tv.setTextColor( getResources().getColorStateList(R.color.lightslategrey)); -// tv.setTextSize(unSelectedSize); - }else{ -// tabWidget.getChildAt(tabhost.getCurrentTab()).setBackgroundResource(R.color.ivory); - tv.setTextColor( getResources().getColorStateList(R.color.darkslategrey)); -// tv.setTextSize(selectedSize); - } - - } -// tabhost.getTabWidget().setStripEnabled(true); - } - */ - - - - //判断当前 - public void isTabHome(){ //show recording track_fragment - - showTrackStatics(); -// - // // QLog.getLogger().d(dTAG,TAG+" app.currentActiveFragment: "+ app.currentActiveFragment +", isTabHome called"); - - } - - - public void isTabList(){ //show tracklist - // // QLog.getLogger().d(dTAG,TAG+" app.currentActiveFragment: "+ app.currentActiveFragment +", isTabList called"); -// - showWebList(); -// showLocalTrackList(); - } - - public void tabTrackClicked(){ - // // QLog.getLogger().d(dTAG,TAG+" app.currentActiveFragment: "+ app.currentActiveFragment +", isTabTrack called"); -// - if(app.isLastTrackExist()) - showRecordingTrack(false); - else - startNewTrackMap(); - - updateTabTitle(); -// tabHost.setCurrentTab(3); - } - - public void selectTabTrack(){ - CURRENT_TAB =TRACK_TAB; - tabHost.setCurrentTab(CURRENT_TAB); - CURRENT_TAB=-1; - - } - - - public void setSelectedTabhostStyle(TabHost tabhost){ - TabWidget tabWidget = tabhost.getTabWidget(); - for (int i =0; i < tabWidget.getChildCount(); i++) { - - TextView tv = (TextView) ((RelativeLayout)tabWidget.getChildAt(i)).getChildAt(1)/*.findViewById(android.R.id.title)*/; -// TextView tv = (TextView) ((RelativeLayout)tabWidget.getChildAt(i)).findViewById(android.R.id.title); - - ImageView iv = (ImageView) ((RelativeLayout)tabWidget.getChildAt(i)).getChildAt(0); - - - if( tv==null){ - continue; - } - // tv.setTextSize(15); - if(i!=tabhost.getCurrentTab()){ -// tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray); - tv.setTextColor( colorUnselected); -// tv.setPadding(0, 2, 0, -2); - tv.setTypeface(null, Typeface.NORMAL); - tv.getPaint().setFlags(0); - - if (i== TRACK_TAB){ - iv.setImageResource(R.drawable.icon_go_in); - }else if (i ==TRACK_STATISTICS ){ - iv.setImageResource(R.drawable.icon_award_in); - }else if (i == TRACK_WEB){ - iv.setImageResource(R.drawable.icon_web_32_in); - } - -// tv.setTextSize(unSelectedSize); - }else{ -// tabWidget.getChildAt(tabhost.getCurrentTab()).setBackgroundResource(R.color.ivory); - tv.setTextColor( colorSelected); -// tv.setTextSize(selectedSize); - tv.setTypeface(null, Typeface.BOLD); -// tv.setPadding(0, 2, 0, -2); - tv.getPaint().setFlags(0);//Paint.UNDERLINE_TEXT_FLAG); - - if (i== TRACK_TAB){ - iv.setImageResource(R.drawable.icon_go); - }else if (i ==TRACK_STATISTICS ){ - iv.setImageResource(R.drawable.icon_award); - }else if (i == TRACK_WEB){ - iv.setImageResource(R.drawable.icon_web_32); - } - - } - - - if(i==TRACK_TAB){ - updateTabTitle(); - - continue; - } - - - - } -// tabhost.getTabWidget().setStripEnabled(true); - } - - - - /** - * 找到Tabhost布局 - */ - public void findTabView(){ - - tabHost = (TabHost) findViewById(android.R.id.tabhost); - tabWidget = (TabWidget) findViewById(android.R.id.tabs); - LinearLayout layout = (LinearLayout)tabHost.getChildAt(0); - TabWidget tw = (TabWidget)layout.getChildAt(1); - - - - tabIndicator_home = (RelativeLayout) LayoutInflater.from(this) - .inflate(R.layout.tab_indicator, tw, false); - TextView tvTab1 = (TextView)tabIndicator_home.getChildAt(1); - ImageView ivTab1 = (ImageView)tabIndicator_home.getChildAt(0); - ivTab1.setBackgroundResource(R.drawable.icon_award); - tvTab1.setText(R.string.bottom_me); - - - /* - tabIndicator_history = (RelativeLayout) LayoutInflater.from(this) - .inflate(R.layout.tab_indicator, tw, false); - TextView tvTab2 = (TextView)tabIndicator_history.getChildAt(1); -// ImageView ivTab2= (ImageView)tabIndicator_home.getChildAt(0); -// ivTab2.setBackgroundResource(R.drawable.main_history); - tvTab2.setText(R.string.bottom_list); - */ - - - - int trackingTitle= R.string.bottom_new_track ; - - tabIndicator_track = (RelativeLayout) LayoutInflater.from(this) - .inflate(R.layout.tab_indicator/*_camera*/, tw, false); - TextView tvTab3 = (TextView)tabIndicator_track.getChildAt(1); - ImageView ivTab3 = (ImageView)tabIndicator_track.getChildAt(0); - ivTab3.setBackgroundResource(R.drawable.icon_go); - - tvTab3.setTypeface(null, Typeface.NORMAL); - tvTab3.setTextColor(getResources().getColorStateList(R.color.white)); - if(app.isLastTrackExist()){ - trackingTitle =R.string.bottom_tracking ; - tvTab3.setTypeface(null, Typeface.BOLD); - tvTab3.setTextColor(getResources().getColorStateList(R.color.wheat)); - } - tvTab3.setText(trackingTitle); - - - tabIndicator_web = (RelativeLayout) LayoutInflater.from(this) - .inflate(R.layout.tab_indicator, tw, false); - TextView tvTab4 = (TextView)tabIndicator_web.getChildAt(1); - ImageView ivTab4 = (ImageView)tabIndicator_web.getChildAt(0); - ivTab4.setBackgroundResource(R.drawable.icon_web_32); - tvTab4.setText(R.string.bottom_web); - - /* - tabIndicator_note = (RelativeLayout) LayoutInflater.from(this) - .inflate(R.layout.tab_indicator, tw, false); - TextView tvTab5 = (TextView)tabIndicator_note.getChildAt(1); -// ImageView ivTab5 = (ImageView)tabIndicator_web.getChildAt(0); -// ivTab5.setBackgroundResource(R.drawable.mian_note); - tvTab5.setText(R.string.bottom_note); - */ - - } - - /** - * 初始化选项卡 - * - * */ - public void initTab(){ - - TabHost.TabSpec tSpecHome = tabHost.newTabSpec(tabHome); - tSpecHome.setIndicator(tabIndicator_home); - tSpecHome.setContent(new DummyTabContent(getBaseContext())); - tabHost.addTab(tSpecHome); - - -// TabHost.TabSpec tSpecHistory = tabHost.newTabSpec(tabList); -// tSpecHistory.setIndicator(tabIndicator_history); -// tSpecHistory.setContent(new DummyTabContent(getBaseContext())); -// tabHost.addTab(tSpecHistory); - - - TabHost.TabSpec tSpecTrack = tabHost.newTabSpec(tabTrack); - tSpecTrack.setIndicator(tabIndicator_track); - tSpecTrack.setContent(new DummyTabContent(getBaseContext())); - tabHost.addTab(tSpecTrack); - - tabIndicator_track.setOnClickListener(new android.view.View.OnClickListener() { - @Override - public void onClick(View v) { - tabTrackClicked(); - } - - - }); - - -// TabHost.TabSpec sSpecNotes = tabHost.newTabSpec(tabNote); -// sSpecNotes.setIndicator(tabIndicator_note); -// sSpecNotes.setContent(new DummyTabContent(getBaseContext())); -// tabHost.addTab(sSpecNotes); - - - TabHost.TabSpec tSpecList = tabHost.newTabSpec(tabWeb); - tSpecList.setIndicator(tabIndicator_web); - tSpecList.setContent(new DummyTabContent(getBaseContext())); - tabHost.addTab(tSpecList); - - /*TabHost.TabSpec tSpecLongway = tabHost.newTabSpec(tabLongway); - tSpecLongway.setIndicator(tabIndicator_longway); - tSpecLongway.setContent(new DummyTabContent(getBaseContext())); - tabHost.addTab(tSpecLongway);*/ - } - - public void updateTabTitle(){ - if(tabHost==null)return; - - boolean isSporting =app.isNaving||app.isLastTrackExist(); -// String title=isVisible?tabData:app.isLastTrackExist()?"数据加载中。。。":tabData; - int title=app.isNaving?(app.isLastTrackExist()?R.string.bottom_navi:R.string.bottom_new_track ): (app.isLastTrackExist()?R.string.bottom_tracking:R.string.bottom_new_track ); - - TextView textview = (TextView)tabIndicator_track.getChildAt(1);//(TextView)tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title); - - if(textview==null){ - return; - } - - textview.setTypeface(null, Typeface.NORMAL); - textview.setTextColor(getResources().getColorStateList(R.color.white)); - if(isSporting){ - - textview.setTypeface(null, Typeface.BOLD); - textview.setTextColor(getResources().getColorStateList(R.color.gold)); - } - - textview.setText(title); - - - } - - public void updateTabVisibility(boolean visible ){ - -// int visibility =visible?View.VISIBLE:View.GONE; - updateActionBar(!visible); -// if( tabHost.getTabWidget().getVisibility() ==visibility)return; - - - if(visible){ -// tabHost.setCurrentTab(0); -// isTabHome(); - - // // QLog.getLogger().d(dTAG,TAG+" updateTabVisibility, app.currentActiveFragment: "+app.currentActiveFragment); - - if(app.currentActiveFragment.equalsIgnoreCase(tabHome)){ - tabHost.setCurrentTab(TRACK_STATISTICS); -// } - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(0) " ); -// isTabHome(); - }else if(app.currentActiveFragment.equalsIgnoreCase(tabList)){ -// tabHost.setCurrentTab(TRACK_HISTORY); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(TRACK_HISTORY) " ); -// isTabList(); -// isTabHome() ; - } - - else if(app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag()) ){ -// updateTabVisibility(false); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(track detail) " ); - } - else if(app.currentActiveFragment.equalsIgnoreCase(GpxDetail_fragment.getFTag()) ){ -// updateTabVisibility(false); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(gpx detail) " ); - } - else if(app.currentActiveFragment.equalsIgnoreCase(WebList_fragment.getFTag()) ){ - tabHost.setCurrentTab(TRACK_WEB); -// updateTabVisibility(false); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(gpx detail) " ); - } - else if(app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag()) ){ - - } else if(app.currentActiveFragment.equalsIgnoreCase(ActivityDetail.getFTag()) ){ -// updateTabVisibility(false); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(Route detail) " ); - - - } else if(app.currentActiveFragment.equalsIgnoreCase(ActivityHome.getFTag()) ){ -// updateTabVisibility(false); - QLog.getLogger().d(dTAG,TAG+" setCurrentTab(ActivityHome detail) " ); - } - else if(app.currentActiveFragment.equalsIgnoreCase(GroupHome.getFTag()) ){ -// updateTabVisibility(false); - QLog.getLogger().d(dTAG,TAG+" setCurrentTab(GroupHome detail) " ); - } - else if(app.currentActiveFragment.equalsIgnoreCase(UserDetails.getFTag()) ){ - - } else if(app.currentActiveFragment.equalsIgnoreCase(UserHome.getFTag()) ){ - - }else if(app.currentActiveFragment.equalsIgnoreCase(GroupDetail.getFTag()) ){ - - } else if(app.currentActiveFragment.equalsIgnoreCase(NoteList.getFTag()) ){ - - } else if(app.currentActiveFragment.equalsIgnoreCase(NoteDetail.getFTag()) ){ - - } else if(app.currentActiveFragment.equalsIgnoreCase(NoteNew.getFTag()) ){ - - } - - - else if(app.currentActiveFragment.equalsIgnoreCase(Playback_fragment.getFTag()) ){ - updateTabVisibility(false); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(playback) " ); - } - else if(app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag()) ){ - - } - - else if(app.isLastTrackExist() && app.currentActiveFragment.equalsIgnoreCase(Track_fragment.getFTag()) ){ //cancel recording goes here now - tabHost.setCurrentTab(TRACK_TAB); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(TRACK_TAB) " ); - } - else{ - - if(tabHost.getCurrentTab() ==TRACK_STATISTICS) - isTabHome() ; - else - tabHost.setCurrentTab(TRACK_STATISTICS); - // // QLog.getLogger().d(dTAG,TAG+" setCurrentTab(TRACK_STATISTICS) " ); - } - - } - - - updateTabTitle(); - tabHost.getTabWidget().setVisibility(visible?View.VISIBLE:View.GONE); - } - - - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public void updateActionBar(boolean enable ){ - - if(Utils.getAndroidSDKVersion()Build.VERSION_CODES.JELLY_BEAN_MR2){ -// ab.setHomeAsUpIndicator(R.drawable.icon_back); -// } -// ab.setSubtitle(enable?" can be back ":"can not back"); - if(!enable) - ab.setTitle(R.string.title_activity_main); - } - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public void updateActionBarTitle(int title ){ - if(Utils.getAndroidSDKVersion()outSize.y?outSize.x:outSize.y; - int screenWidth =getWindowManager().getDefaultDisplay().getWidth(); - int screenHeight =getWindowManager().getDefaultDisplay().getHeight(); - screenWidth=screenWidth>screenHeight?screenWidth:screenHeight; - int rate = (int)(5*(float) screenWidth/320); - return rate<14?14:rate; - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) - private void getScreenSize( ) { -// Point outSize = new Point(); -// getWindowManager().getDefaultDisplay().getSize(outSize); -// -// int screenWidth=outSize.x>outSize.y?outSize.x:outSize.y; - if(QiYouConstant.PV_INT_SCREEN_WIDTH>0)return; - Point outSize= new Point(); - outSize.set(480, 800); - try{ - if(Utils.getAndroidSDKVersion()>=Build.VERSION_CODES.JELLY_BEAN_MR1) - getWindowManager().getDefaultDisplay().getRealSize(outSize); - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - } - app.setScreenInfo(outSize); - } - - - - - - - @Override - public void onPause() { - super.onPause(); - unregisterReceiver(receiver); - app.isUIactive=false; - MobclickAgent.onPause(this); - - } - - @Override - public void onResume() { - - super.onResume(); - registerReceiver(receiver, filter); -// Toast toast= Toast.makeText(this, TAG+" current recording track status:" +app.getRecordingTrack().getTrackBean().getStatus(), Toast.LENGTH_LONG ); -// toast.show(); - if(app.canRecord() )//|| app.getRecordingTrack().getTrackBean().getStatus()==QiYouConstant.TRACK_STATUS_TRACKING) - { - //app.stopAndroidGPSRequest(); - if(app.isLostGps()) - app.startAndroidGPSRequest(); //if duplicated called lm.requestLocationUpdates, will request more or no impact? -// toast= Toast.makeText(this, TAG+" start GPS requeest once more.", Toast.LENGTH_LONG ); -// toast.show(); - } - app.isUIactive=true; - app.updateStatistics(); - app.getPreferences(); - MobclickAgent.onResume(this); - - } - - @Override - public void onDestroy() { -// Log.d(TAG,TAG+" The MainActivity is going to be destroied."); -// Toast toast= Toast.makeText(this, TAG+" The MainActivity is going to be destroied.", Toast.LENGTH_LONG ); -// toast.show(); -// app.stopAndroidGPSRequest(); - app.setPreferences(false,false); -// mTts.stopSpeaking(mTtsListener); -// // 閫?嚭鏃堕噴鏀捐繛鎺? -// mTts.destory(); - super.onDestroy(); - } - - - public final MediaScannerConnection msc = new MediaScannerConnection((QiYouApplication) getApplication(), new MediaScannerConnectionClient() { - @Override - public void onMediaScannerConnected() { -// msc.scanFile("/sdcard/image.jpg", "image/jpeg"); - } - @Override - public void onScanCompleted(String path, Uri uri) { - -// msc.disconnect(); - } - }); - - void startWelcome(){ - Intent it = new Intent(MainActivity.this,Welcome.class); - startActivity(it); -// overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right); -// Welcome.this.finish(); - - } - - void setVolume(){ - /**/ - setVolumeControlStream(AudioManager.STREAM_MUSIC); - /* MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.gogo); - mediaPlayer.setVolume(1.0f, 1.0f); - mediaPlayer.start();*/ - } - - - String SCOPE = "get_simple_userinfo,add_topic";//所有权限用“all” - public void doQQLogin() { - IUiListener listener = new BaseUiListener() { - @Override - protected void doComplete(/*JSONObject*/Object values) { - onAuth20LoginComplete(values); - } - }; - mTencent.login(this, SCOPE, listener); - } - - private void onAuth20LoginComplete(Object values){ - JSONObject json =(JSONObject)values; - - try { - QiYouConstant.PV_OPEN_ID =json.getString("openid"); - QiYouConstant.PV_ACCESS_TOKEN =json.getString("access_token"); - QiYouConstant.PV_EXPIRES_IN =System.currentTimeMillis()+Long.parseLong(json.getString("expires_in"))*1000; - app.saveAuth20Token(); - - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - - - - - - } - - private class BaseUiListener implements IUiListener { - @Override - public void onComplete(Object response) { - //V2.0版本,参数类型由JSONObject 改成了Object,具体类型参考api文档 -// mBaseMessageText.setText("onComplete:"); - // QLog.getLogger().d(dTAG, "Tencent Auth2.0 on Complete."); - doComplete(response); - } - protected void doComplete(/*JSONObject*/Object values) { - - } - @Override - public void onError(UiError e) { - // QLog.getLogger().e("onError:", "code:" + e.errorCode + ", msg:"0 + e.errorMessage + ", detail:" + e.errorDetail); - } - @Override - public void onCancel() { -// showResult("onCancel", ""); - } - - } - -} - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/SettingsActivity.java b/qy/src/main/java/com/qiyou/mb/android/ui/SettingsActivity.java deleted file mode 100644 index 1b9a192..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/SettingsActivity.java +++ /dev/null @@ -1,359 +0,0 @@ -package com.qiyou.mb.android.ui; - -import android.annotation.TargetApi; -import android.app.ActionBar; -import android.content.Context; -import android.content.res.Configuration; -import android.media.Ringtone; -import android.media.RingtoneManager; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.preference.ListPreference; -import android.preference.Preference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceCategory; -import android.preference.PreferenceFragment; -import android.preference.PreferenceManager; -import android.preference.RingtonePreference; -import android.text.TextUtils; -import android.view.MenuItem; -import android.support.v4.app.NavUtils; - -import java.util.List; - -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; - -/** - * A {@link PreferenceActivity} that presents a set of application settings. On - * handset devices, settings are presented as a single list. On tablets, - * settings are split by category, with category headers shown to the left of - * the list of settings. - *

- * See - * Android Design: Settings for design guidelines and the Settings - * API Guide for more information on developing a Settings UI. - */ -public class SettingsActivity extends PreferenceActivity { - /** - * Determines whether to always show the simplified settings UI, where - * settings are presented in a single list. When false, settings are shown - * as a master/detail two-pane view on tablets. When true, a single pane is - * shown on tablets. - */ - private static final boolean ALWAYS_SIMPLE_PREFS = false; - public QiYouApplication app ; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setupActionBar(); - app = (QiYouApplication) getApplication(); - setContentView(R.layout.setting_background); - - } - - /** - * Set up the {@link android.app.ActionBar}, if the API is available. - */ - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - private void setupActionBar() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - // Show the Up button in the action bar. - ActionBar ab =getActionBar(); - if(ab!=null) - ab.setDisplayHomeAsUpEnabled(true); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - // This ID represents the Home or Up button. In the case of this - // activity, the Up button is shown. Use NavUtils to allow users - // to navigate up one level in the application structure. For - // more details, see the Navigation pattern on Android Design: - // - // http://developer.android.com/design/patterns/navigation.html#up-vs-back - // - // TODO: If Settings has multiple levels, Up should navigate up - // that hierarchy. - NavUtils.navigateUpFromSameTask(this); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - - setupSimplePreferencesScreen(); - } - @Override - public void onDestroy() { - super.onDestroy(); - app.getPreferences(); - } - /** - * Shows the simplified settings UI if the device configuration if the - * device configuration dictates that a simplified, single-pane UI should be - * shown. - */ - @SuppressWarnings("deprecation") - private void setupSimplePreferencesScreen() { - if (!isSimplePreferences(this)) { - return; - } - - // In the simplified UI, fragments are not used at all and we instead - // use the older PreferenceActivity APIs. - - // Add 'general' preferences. - addPreferencesFromResource(R.xml.pref_general); - - // Add 'notifications' preferences, and a corresponding header. - PreferenceCategory fakeHeader = new PreferenceCategory(this); -// fakeHeader.setTitle(R.string.pref_header_notifications); - getPreferenceScreen().addPreference(fakeHeader); - - -// addPreferencesFromResource(R.xml.pref_notification); -// -// // Add 'data and sync' preferences, and a corresponding header. -// fakeHeader = new PreferenceCategory(this); -// fakeHeader.setTitle(R.string.pref_header_data_sync); -// getPreferenceScreen().addPreference(fakeHeader); -// addPreferencesFromResource(R.xml.pref_data_sync); - - // Bind the summaries of EditText/List/Dialog/Ringtone preferences to - // their values. When their values change, their summaries are updated - // to reflect the new value, per the Android Design guidelines. -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_STR_USER_NAME/*.PK_STR_USER_ACCOUNT*/)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_FLOAT_USER_WEIGHT)); - - - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_GPS_SPAN)); -// bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_SPEAK_KM)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_SPORTS_SPEAK_MODEL)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_NAVI_SPEAK_MODEL)); - - bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_PLAYBACK_RECORD_SCREEN_OFF)); - bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_SAVE_POWER)); - bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_NAVI_VIBRATOR_ON)); -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_WPS_CNT_BEAR)); -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_ANGLE_BEAR)); -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_WPS_KEEP_PERCENT)); -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_PLAYBACK_TIME_INTERVAL)); -// bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")); -// bindPreferenceSummaryToValue(findPreference("sync_frequency")); -// bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_SHARE_LOCATION)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_LIVE_SPAN)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_LIVE_TERM)); - - } - - /** {@inheritDoc} */ - @Override - public boolean onIsMultiPane() { - return isXLargeTablet(this) && !isSimplePreferences(this); - } - - /** - * Helper method to determine if the device has an extra-large screen. For - * example, 10" tablets are extra-large. - */ - private static boolean isXLargeTablet(Context context) { - return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; - } - - /** - * Determines whether the simplified settings UI should be shown. This is - * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device - * doesn't have newer APIs like {@link PreferenceFragment}, or the device - * doesn't have an extra-large screen. In these cases, a single-pane - * "simplified" settings UI should be shown. - */ - private static boolean isSimplePreferences(Context context) { - return ALWAYS_SIMPLE_PREFS - || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB - || !isXLargeTablet(context); - } - - /** {@inheritDoc} */ - @Override - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public void onBuildHeaders(List

target) { - if (!isSimplePreferences(this)) { - loadHeadersFromResource(R.xml.pref_headers, target); - } - } - - /** - * A preference value change listener that updates the preference's summary - * to reflect its new value. - */ - private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object value) { - String stringValue = value.toString(); - - if (preference instanceof ListPreference) { - // For list preferences, look up the correct display value in - // the preference's 'entries' list. - ListPreference listPreference = (ListPreference) preference; - int index = listPreference.findIndexOfValue(stringValue); - - // Set the summary to reflect the new value. - preference - .setSummary(index >= 0 ? listPreference.getEntries()[index] - : null); - - } else if (preference instanceof RingtonePreference) { - // For ringtone preferences, look up the correct display value - // using RingtoneManager. - if (TextUtils.isEmpty(stringValue)) { - // Empty values correspond to 'silent' (no ringtone). - preference.setSummary(R.string.pref_ringtone_silent); - - } else { - Ringtone ringtone = RingtoneManager.getRingtone( - preference.getContext(), Uri.parse(stringValue)); - - if (ringtone == null) { - // Clear the summary if there was a lookup error. - preference.setSummary(null); - } else { - // Set the summary to reflect the new ringtone display - // name. - String name = ringtone - .getTitle(preference.getContext()); - preference.setSummary(name); - } - } - - } else { - // For all other preferences, set the summary to the value's - // simple string representation. - preference.setSummary(stringValue); - } - return true; - } - }; - - /** - * Binds a preference's summary to its value. More specifically, when the - * preference's value is changed, its summary (line of text below the - * preference title) is updated to reflect the value. The summary is also - * immediately updated upon calling this method. The exact display format is - * dependent on the type of preference. - * - * @see #sBindPreferenceSummaryToValueListener - */ - private static void bindPreferenceSummaryToValue(Preference preference) { - // Set the listener to watch for value changes. - preference - .setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); - - // Trigger the listener immediately with the preference's - // current value. - sBindPreferenceSummaryToValueListener.onPreferenceChange( - preference, - PreferenceManager.getDefaultSharedPreferences( - preference.getContext()).getString(preference.getKey(), - "")); - } - - private static void bindBooleanPreferenceSummaryToValue(Preference preference) { - // Set the listener to watch for value changes. - preference - .setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); - - // Trigger the listener immediately with the preference's - // current value. - sBindPreferenceSummaryToValueListener.onPreferenceChange( - preference, - PreferenceManager.getDefaultSharedPreferences( - preference.getContext()).getBoolean(preference.getKey(), - true)); - } - - /** - * This fragment shows general preferences only. It is used when the - * activity is showing a two-pane settings UI. - */ - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public static class GeneralPreferenceFragment extends PreferenceFragment { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - addPreferencesFromResource(R.xml.pref_general); - - // Bind the summaries of EditText/List/Dialog/Ringtone preferences - // to their values. When their values change, their summaries are - // updated to reflect the new value, per the Android Design - // guidelines. -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_STR_USER_NAME/*.PK_STR_USER_ACCOUNT*/)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_FLOAT_USER_WEIGHT)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_GPS_SPAN)); -// bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_SPEAK_KM)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_SPORTS_SPEAK_MODEL)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_NAVI_SPEAK_MODEL)); - bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_PLAYBACK_RECORD_SCREEN_OFF)); - bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_SAVE_POWER)); - bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_NAVI_VIBRATOR_ON)); - - -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_WPS_CNT_BEAR)); -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_ANGLE_BEAR)); -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_PLAYBACK_TIME_INTERVAL)); -// bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_WPS_KEEP_PERCENT)); -// bindBooleanPreferenceSummaryToValue(findPreference(QiYouConstant.PK_BL_SHARE_LOCATION)); - - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_LIVE_SPAN)); - bindPreferenceSummaryToValue(findPreference(QiYouConstant.PK_INT_LIVE_TERM)); - } - } - - /** - * This fragment shows notification preferences only. It is used when the - * activity is showing a two-pane settings UI. - */ - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public static class NotificationPreferenceFragment extends - PreferenceFragment { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); -// addPreferencesFromResource(R.xml.pref_notification); - - // Bind the summaries of EditText/List/Dialog/Ringtone preferences - // to their values. When their values change, their summaries are - // updated to reflect the new value, per the Android Design - // guidelines. -// bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")); - } - } - - /** - * This fragment shows data and sync preferences only. It is used when the - * activity is showing a two-pane settings UI. - */ - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public static class DataSyncPreferenceFragment extends PreferenceFragment { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); -// addPreferencesFromResource(R.xml.pref_data_sync); - - // Bind the summaries of EditText/List/Dialog/Ringtone preferences - // to their values. When their values change, their summaries are - // updated to reflect the new value, per the Android Design - // guidelines. -// bindPreferenceSummaryToValue(findPreference("sync_frequency")); - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/Website.java b/qy/src/main/java/com/qiyou/mb/android/ui/Website.java deleted file mode 100644 index 6bbbc2a..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/Website.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.qiyou.mb.android.ui; - -import android.annotation.SuppressLint; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.RemoteException; -import android.util.Log; -import android.view.View; -import android.view.View.OnClickListener; -import android.webkit.WebChromeClient; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.webkit.WebViewClient; -import android.widget.Button; -import android.widget.ProgressBar; -import android.widget.TextView; -import android.widget.Toast; - -//import com.iflytek.speech.ErrorCode; -//import com.iflytek.speech.ISpeechModule; -//import com.iflytek.speech.InitListener; -//import com.iflytek.speech.SpeechConstant; -//import com.iflytek.speech.SpeechSynthesizer; -//import com.iflytek.speech.SpeechUtility; -//import com.iflytek.speech.SynthesizerListener; -import com.qiyou.mb.android.Activity_qiyouBase; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.upgrade.UpdateManager; -import com.qiyou.mb.android.utils.log.QLog; - -public class Website extends Activity_qiyouBase { - public static final String TAG ="com.qiyou.Website"; - public static final String dTAG ="com.qiyou"; - - private WebView webView; -// TextView textView; - ProgressBar progressBar; - @Override - protected void onCreate(Bundle savedInstanceState) { -// updateActionBar(false); - super.onCreate(savedInstanceState); - app = (QiYouApplication) getApplication(); - setContentView(R.layout.web_site); - initialWebview(); - - } - - @SuppressLint("SetJavaScriptEnabled") - void initialWebview(){ - webView = (WebView) findViewById(R.id.webview); - progressBar = (ProgressBar) findViewById(R.id.webprogress); - webView.loadUrl( QiYouConstant.BASE_URL+"list"); -// webView.loadUrl( "WWW.BAIDU.COM"); - WebSettings setting = webView.getSettings(); - setting.setJavaScriptEnabled(true);//支持js - setting.setDefaultTextEncodingName("GBK");//设置字符编码 - webView.setScrollBarStyle(0);//滚动条风格,为0指滚动条不占用空间,直接覆盖在网页上 - - -/* webView.setWebChromeClient(new WebChromeClient(){ - - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - - view.loadUrl(url); //在当前的webview中跳转到新的url - - return true; - } - }); */ - - webView.setWebViewClient(new WebViewClient(){ - - @Override - public void onPageFinished(WebView view, String url) { - // TODO Auto-generated method stub - super.onPageFinished(view, url); - //页面下载完毕,却不代表页面渲染完毕显示出来 - //WebChromeClient中progress==100时也是一样 - if (webView.getContentHeight() != 0) { - //这个时候网页才显示 - } - } - - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - -// view.loadUrl(url); //在当前的webview中跳转到新的url - if(Uri.parse(url).getHost().equals("www.i7lv.com")) - { - // This is my web site, so do not override; let my WebView load - // the page - return false; - } - // Otherwise, the link is not for a page on my site, so launch - // another Activity that handles URLs - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - startActivity(intent); - return true; - - - } - }); - - webView.setWebChromeClient(new WebChromeClient(){ - @Override - public void onProgressChanged(WebView view, int newProgress) { - // TODO Auto-generated method stub - super.onProgressChanged(view, newProgress); - //这里将textView换成你的progress来设置进度 - if (newProgress == 0) { - // textView.setVisibility(View.VISIBLE); - progressBar.setVisibility(View.VISIBLE); - } -// textView.setText(newProgress+""); -// textView.postInvalidate(); - progressBar.setProgress(newProgress); - progressBar.postInvalidate(); - if (newProgress == 100) { - // textView.setVisibility(View.GONE); - progressBar.setVisibility(View.GONE); - } - } - }); - } - - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/Welcome.java b/qy/src/main/java/com/qiyou/mb/android/ui/Welcome.java deleted file mode 100644 index b980f9b..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/Welcome.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.qiyou.mb.android.ui; - -import android.annotation.TargetApi; -import android.app.ActionBar; -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; -import android.view.KeyEvent; -import android.view.View; -import android.view.animation.Animation; -import android.view.animation.Animation.AnimationListener; -import android.view.animation.AnimationUtils; -import android.widget.ImageView; -import android.widget.TextView; - -import com.qiyou.mb.android.Activity_qiyouBase; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -public class Welcome extends Activity_qiyouBase { - public static final String TAG ="com.qiyou.Welcome"; - public static final String dTAG ="com.qiyou"; - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - updateActionBar(); - app.isUIactive = true; - Intent intent =this.getIntent(); - - setContentView(R.layout.welcomelogo); - -// app.restoreLastTracking(); -// app.getStaticsTracks();//异步获取track statistics - - if(intent.hasExtra("noani")){ - startMainActivity(); - } - - - - //寰楀埌ImageView鎺т欢 - ImageView logo = (ImageView) findViewById(R.id.logo2); - Animation logo_animation = AnimationUtils.loadAnimation(Welcome.this, - R.anim.push_left_in); - logo.setAnimation(logo_animation); - -// app.syncStatistics(); -// app.startNetworkLocationRequest(true); -// workingInBackground(); - app.restoreLastTracking(); -// QLog.getLogger().dLog(TAG, " restoreLastTracking cost time:" +(System.currentTimeMillis()-st)); -// st=System.currentTimeMillis(); -// app.getStaticsTracks();//异步获取track statistics - - logo_animation.setAnimationListener(new AnimationListener() { - - @Override - public void onAnimationStart(Animation animation) { - // TODO Auto-generated method stub -// workingInBackground(); - - } - - @Override - public void onAnimationRepeat(Animation animation) { - // TODO Auto-generated method stub - - } - - @Override - public void onAnimationEnd(Animation animation) { -// if(Utils.getAndroidSDKVersion()>=Build.VERSION_CODES.HONEYCOMB) -// ((ImageView) findViewById(R.id.logo2)).setAlpha(50f); -// ((TextView)findViewById(R.id.i7lv)).setVisibility(View.VISIBLE); - // TODO Auto-generated method stub - workingInBackground(); - - startMainActivity(); - } - }); - - - } - - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - public void updateActionBar(){ - - if(Utils.getAndroidSDKVersion() trs = new ArrayList(); - protected double minY; - protected double minX; - protected double maxY =0; - protected String[] titles ; - protected List xValues ; - protected List yValues ; - protected TypeStatistics mTypeStatistics; - protected int CYRAN =Color.parseColor("#00FFFF"); - protected int LIGHTCYRAN =Color.parseColor("#E0FFFF");//#E0FFFF - protected int WHITE =Color.parseColor("#FFFFFF");//#E0FFFF - protected int DARKCYRAN =Color.parseColor("#008B8B"); -// protected int renderCnt; - /* - * - */ - - public XYMultipleSeriesRenderer getRender(int cnt,String title, String xTitle, String yTitle, boolean isBarRender ) { - - -// int[] allColors = new int[] {Color.MAGENTA,Color.BLUE ,Color.DKGRAY , Color.CYAN,Color.GREEN, Color.GRAY ,Color.RED, Color.YELLOW,Color.DKGRAY}; - int[] allColors = { Color.parseColor("#FF8497"), DARKCYRAN, - Color.parseColor("#948D8B"),Color.parseColor("#F59331"), - Color.parseColor("#00BFC0"), CYRAN,Color.parseColor("#95AC5F"), - Color.parseColor("#56ADDB"), - Color.parseColor("#73C83C"), - Color.parseColor("#E54273"), - Color.parseColor("#FFD34E"), Color.parseColor("#2A86D6"), - }; - - - PointStyle[] allStyles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND, - PointStyle.TRIANGLE, PointStyle.SQUARE ,PointStyle.POINT,PointStyle.POINT,PointStyle.POINT,PointStyle.POINT}; - - int num =trs.size()>0?trs.size():1; - - int[] colors = new int[num*cnt] ; - PointStyle[] styles = new PointStyle[num*cnt] ; - - - for(int i=0;igetMaxTime()?maxXvalue:getMaxTime(); - maxXvalue =maxXvalue*1.01; - - - setChartSettings(renderer, title, xTitle, yTitle, minX, maxXvalue, minY*1.1, getMaxY()*1.1, - Color.LTGRAY, Color.LTGRAY); - - renderer.setInScroll(true); //http://zhirong.iteye.com/blog/1629781 - -// renderer.setXLabels((int) getMaxTime()); -// renderer.setYLabels((int) getMaxDist()); - renderer.setXLabels(20); - renderer.setYLabels(10); - renderer.setShowGrid(true); - renderer.setXLabelsAlign(Align.RIGHT); - renderer.setYLabelsAlign(Align.RIGHT); - renderer.setZoomButtonsVisible(true); - renderer.setZoomEnabled(true, false); -// renderer.setBackgroundColor(Color.LTGRAY); -// renderer.setApplyBackgroundColor(true); - -// renderer.setMarginsColor(Color.argb(0, 220, 228, 234)); - renderer.setMarginsColor(WHITE);//周边背景色 - renderer.setGridColor(Color.LTGRAY); //栅格颜色 - renderer.setLabelsColor(Color.DKGRAY); //周边标签字体颜色 - renderer.setAxesColor(Color.DKGRAY);//轴颜色 - renderer.setLabelFormat(NumberFormat.getNumberInstance());// NumberFormat.getIntegerInstance()); - renderer.setXLabelsColor(Color.BLACK); - renderer.setYLabelsColor(0, Color.BLACK); - renderer.setMargins(new int[] { 1, 50,20, 0 });//top,left,bottom,right - - renderer.setAxisTitleTextSize(tFontSize); -// renderer.setBackgroundColor(color.lightgray); - renderer.setAxisTitleTextSize(tFontSize); - renderer.setChartTitleTextSize(tFontSize); - renderer.setLabelsTextSize(tFontSize); - renderer.setLegendTextSize(tFontSize);//距离--,速度-- - renderer.setPointSize(2f); -// renderer.setShowAxes(true); - renderer.setShowLegend(true); -// renderer.setShowAxes(false); -// renderer.setShowLegend(false); -// renderer.setShowLabels(false); -// renderer.setPanLimits(new double[] { 0, getMaxTime()*2, 0, getMaxDist()*2 }); -// renderer.setZoomLimits(new double[] { 0, getMaxTime()/2, 0, getMaxDist()/2 }); - renderer.setPanLimits(new double[] { minX, maxXvalue, 0, getMaxY() }); - renderer.setZoomLimits(new double[] { minX, maxXvalue, 0, getMaxY()}); - return renderer; - } - - public XYMultipleSeriesRenderer getRender(int cnt,String title, String xTitle, String yTitle ) - { -// int[] allColors = new int[] { Color.BLUE, Color.GREEN, Color.CYAN, Color.YELLOW }; - return getRender( cnt, title, xTitle, yTitle, false ); - } - /* - * return max time of minutes - */ - public double getMaxTime() - { - double maxSportTime =0.0; - for(Track tr:trs){ - if(tr ==null)continue; -// maxSportTime = tr.getTrackBean().getSportTime()>maxSportTime? tr.getTrackBean().getSportTime():maxSportTime; -// long sptime =tr.getTrackBean().getEndTime() - tr.getTrackBean().getStartTime(); - long sptime =tr.getTrackBean().getSportTime(); - maxSportTime = sptime>maxSportTime? sptime:maxSportTime; - } - maxSportTime = maxSportTime/1000/60.0; - - return maxSportTime ; - } - - public double getMaxDist() - { - double max =0.0; - for(Track tr:trs){ - if(tr ==null)continue; -// maxSportTime = tr.getTrackBean().getSportTime()>maxSportTime? tr.getTrackBean().getSportTime():maxS - max = tr.getTrackBean().getDistance()>max? tr.getTrackBean().getDistance():max; - } - max = max/1000.0; - - return max ; - } - - public double getMaxSpTime() - { - double maxSportTime =0.0; - for(Track tr:trs){ - if(tr ==null)continue; - maxSportTime = tr.getTrackBean().getSportTime()>maxSportTime? tr.getTrackBean().getSportTime():maxSportTime; - } - maxSportTime = maxSportTime/1000/60.0; - return maxSportTime ; - } - - public abstract double getMaxY(); - - - /** - * Builds an XY multiple dataset using the provided values. - * - * @param titles the series titles - * @param xValues the values for the X axis - * @param yValues the values for the Y axis - * @return the XY multiple dataset - */ - protected XYMultipleSeriesDataset buildDataset(String[] titles, List xValues, - List yValues) { - XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); - addXYSeries(dataset, titles, xValues, yValues, 0); - return dataset; - } - - public void addXYSeries(XYMultipleSeriesDataset dataset, String[] titles, List xValues, - List yValues, int scale) { - int length = titles.length; - for (int i = 0; i < length; i++) { - XYSeries series = new XYSeries(titles[i], scale); - double[] xV = xValues.get(i); - double[] yV = yValues.get(i); - -// QLog.getLogger().d(dTAG,TAG +" xV: "+ xV.toString()); -// QLog.getLogger().d(dTAG,TAG +" yV: "+ yV.toString()); - - int seriesLength = xV.length; -// int seriesLength = yV.length; - for (int k = 0; k < seriesLength; k++) { - series.add(xV[k], yV[k]); - } - dataset.addSeries(series); - } - } - - /** - * Builds an XY multiple series renderer. - * - * @param colors the series rendering colors - * @param styles the series point styles - * @return the XY multiple series renderers - */ - protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) { - XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(); - setRenderer(renderer, colors, styles); - return renderer; - } - - protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) { - renderer.setAxisTitleTextSize(16); - renderer.setChartTitleTextSize(20); - renderer.setLabelsTextSize(15); - renderer.setLegendTextSize(15); - renderer.setPointSize(3f); - renderer.setMargins(new int[] { 40, 40, 35, 20 }); - int length = colors.length; - for (int i = 0; i < length; i++) { - XYSeriesRenderer r = new XYSeriesRenderer(); - r.setColor(colors[i]); - r.setPointStyle(styles[i]); - renderer.addSeriesRenderer(r); - } - } - - /** - * Sets a few of the series renderer settings. - * - * @param renderer the renderer to set the properties to - * @param title the chart title - * @param xTitle the title for the X axis - * @param yTitle the title for the Y axis - * @param xMin the minimum value on the X axis - * @param xMax the maximum value on the X axis - * @param yMin the minimum value on the Y axis - * @param yMax the maximum value on the Y axis - * @param axesColor the axes color - * @param labelsColor the labels color - */ - protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle, - String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor, - int labelsColor) { - renderer.setChartTitle(title); - renderer.setXTitle(xTitle); - renderer.setYTitle(yTitle); - renderer.setXAxisMin(xMin); - renderer.setXAxisMax(xMax); - renderer.setYAxisMin(yMin); - renderer.setYAxisMax(yMax); - renderer.setAxesColor(axesColor); - renderer.setLabelsColor(labelsColor); - } - - /** - * Builds an XY multiple time dataset using the provided values. - * - * @param titles the series titles - * @param xValues the values for the X axis - * @param yValues the values for the Y axis - * @return the XY multiple time dataset - */ - protected XYMultipleSeriesDataset buildDateDataset(String[] titles, List xValues, - List yValues) { - XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); - int length = titles.length; - for (int i = 0; i < length; i++) { - TimeSeries series = new TimeSeries(titles[i]); - Date[] xV = xValues.get(i); - double[] yV = yValues.get(i); - int seriesLength = xV.length; - for (int k = 0; k < seriesLength; k++) { - series.add(xV[k], yV[k]); - } - dataset.addSeries(series); - } - return dataset; - } - - /** - * Builds a category series using the provided values. - * - * @param titles the series titles - * @param values the values - * @return the category series - */ - protected CategorySeries buildCategoryDataset(String title, HashMap values) { - CategorySeries series = new CategorySeries(title); - - for (String key:values.keySet()) { - - - series.add(key, values.get(key)); - } - - return series; - } - - - protected CategorySeries buildCategoryDataset(String title, List Citems) { - CategorySeries series = new CategorySeries(title); - - for (CItem citem:Citems) { - - series.add(citem.getValue(), citem.getCnt() ); - } - - return series; - } - - /** - * Builds a multiple category series using the provided values. - * - * @param titles the series titles - * @param values the values - * @return the category series - */ - protected MultipleCategorySeries buildMultipleCategoryDataset(String title, - List titles, List values) { - MultipleCategorySeries series = new MultipleCategorySeries(title); - int k = 0; - for (double[] value : values) { - series.add(2007 + k + "", titles.get(k), value); - k++; - } - return series; - } - - /** - * Builds a category renderer to use the provided colors. - * - * @param colors the colors - * @return the category renderer - */ - protected DefaultRenderer buildCategoryRenderer(int[] colors) { - DefaultRenderer renderer = new DefaultRenderer(); - renderer.setLabelsTextSize(25); - renderer.setLegendTextSize(18); - renderer.setMargins(new int[] { 20, 30, 15, 0 }); - for (int color : colors) { - SimpleSeriesRenderer r = new SimpleSeriesRenderer(); - r.setColor(color); - renderer.addSeriesRenderer(r); - } - return renderer; - } - - /** - * Builds a bar multiple series dataset using the provided values. - * - * @param titles the series titles - * @param values the values - * @return the XY multiple bar dataset - */ - protected XYMultipleSeriesDataset buildBarDataset(String[] titles, List values) { - XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); - int length = titles.length; - for (int i = 0; i < length; i++) { - CategorySeries series = new CategorySeries(titles[i]); - double[] v = values.get(i); - int seriesLength = v.length; - for (int k = 0; k < seriesLength; k++) { - series.add(v[k]); - } - dataset.addSeries(series.toXYSeries()); - } - return dataset; - } - - /** - * Builds a bar multiple series renderer to use the provided colors. - * - * @param colors the series renderers colors - * @return the bar multiple series renderer - */ - protected XYMultipleSeriesRenderer buildBarRenderer(int[] colors) { - XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(); - renderer.setAxisTitleTextSize(16); - renderer.setChartTitleTextSize(20); - renderer.setLabelsTextSize(15); - renderer.setLegendTextSize(15); - int length = colors.length; - for (int i = 0; i < length; i++) { - SimpleSeriesRenderer r = new SimpleSeriesRenderer(); - r.setColor(colors[i]); -// r.setDisplayChartValues(true); - renderer.addSeriesRenderer(r); - } - return renderer; - } - - protected void buildBarRenderer(XYMultipleSeriesRenderer renderer,int[] colors) { - int length = colors.length; - for (int i = 0; i < length; i++) { - SimpleSeriesRenderer r = new SimpleSeriesRenderer(); - r.setColor(colors[i]); - renderer.addSeriesRenderer(r); - } -// renderer.setBarSpacing(0.5); - renderer.setBarSpacing(1); - - } - - public abstract View getChartView(Context context); - public abstract void buildChartData(); - public void setTrs(ArrayList trs) { - - if(trs.size()>4) - { - this.trs.clear(); - for(int i =0;i<=3;i++){ - this.trs.add(trs.get(i)); - } - }else - this.trs = trs; - } - -protected double[] getDv( ArrayList D ){ - return getDv(D,false); - } - - protected double[] getDv( ArrayList D,boolean checkMax){ - int i =0; - double[] Dv = new double[D.size()]; - for (Double d :D){ - Dv[i] =d.doubleValue(); - if(checkMax){ - maxXvalue =maxXvalue< Dv[i]? Dv[i]:maxXvalue; - } - i++; - } - return Dv; - -} - -public TypeStatistics getStrack() { - return mTypeStatistics; -} - -public void setStrack(TypeStatistics mTypeStatistics) { - this.mTypeStatistics = mTypeStatistics; -} -protected float mFontSize=24; -protected float sFontSize=10; -protected float tFontSize=8; -protected float ttFontSize=6; -public void setFontSize(Context context){ - mFontSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mFontSize, context.getResources().getDisplayMetrics()); - sFontSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sFontSize, context.getResources().getDisplayMetrics()); - tFontSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tFontSize, context.getResources().getDisplayMetrics()); - tFontSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, ttFontSize, context.getResources().getDisplayMetrics()); - -} - -} - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/CopyOfDistEleChart.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/CopyOfDistEleChart.java deleted file mode 100644 index 067e59d..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/CopyOfDistEleChart.java +++ /dev/null @@ -1,263 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import org.achartengine.ChartFactory; - -import android.content.Context; -import android.content.Intent; -import android.view.View; - -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -/** - *X: distance - *Y: ele, sum ele - */ -public class CopyOfDistEleChart extends AbstractChart { - public static final String TAG ="com.qiyou.DistEleChart"; - public static final String dTAG ="com.qiyou"; - - - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, - "高度变化"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - @Override - public View getChartView(Context context) - { - View v = null; - try{ - setFontSize(context); - buildChartData(); - v= ChartFactory.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - } - @Override - public void buildChartData(){ - getTitles(); - getMinY(); - getXYvalues(); - - dataset = buildDataset(titles, xValues, yValues); - renderer = getRender(3," ", "距离(公里)", "高度(米)"); - } - - - - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*3]; - int i=0; - String name=""; - for(Track tr:trs){ - if(tr ==null)continue; -// name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); - titles[i] =name + "高度"; - i++; - titles[i] =name + "累积升高"; - i++; - titles[i] =name + "累积下降"; - i++; - - } - - - } - - /* - * return max time of minutes - */ - - -@Override -public double getMaxY(){ - double tmp =0; - for(Track tr:trs){ - if(tr ==null)continue; - - tmp = tr.getTrackBean().geteUpDist()>tmp? tr.getTrackBean().geteUpDist():tmp; - - } - maxY =maxYtmp?tmp:minY; - - minY= minY*1.1; - - if( Math.abs(minY)<500){ - - minY=minY*2; //扩大图形范围,使不精确的小的海拔变化波动在图上不明显 - - } -} - - - void getXYvalues (){ - - xValues = new ArrayList(); - XstepValue = getMaxDist()/Xcnt*2; - ArrayList xD ; - ArrayList xE ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yD; // y e down - ArrayList yU; // y e up - ArrayList yE; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b &&!(b.getEled()==0 &&b.getElevation()==0)) - al.add(b); - } - - yD =new ArrayList(); -// yD.add(0, 0D); - yU =new ArrayList(); -// yU.add(0, 0D); - yE =new ArrayList(); - xD = new ArrayList(); -// xD.add(0, 0D); - xE =new ArrayList(); - double ttmS =0 ; //step value for Speed - long tm=0; - Waypoint_bean wb; - int j=0; - double k=0; - double asp =0.0; //step average Speed - long trStartTime; - double lwb; - double xvalue=0; - double eu=0; - double ed=0; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 &&al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - - wb = al.get(i); - j++; -// if(j==1){ -// minX=wb.getSumDist()/1000; -// } - - trStartTime =tr.getTrackBean().getStartTime(); -// lwb = i>0?al.get(i-1).getDistance():0; - lwb = al.get(i).getDistance(); - xvalue = wb.getSumDist()/1000.0; - ttmS+=wb.getDistance()/1000; - - asp +=wb.getElevation(); - // asp +=wb.getEled(); - k++; - // QLog.getLogger().d(dTAG,"i: "+ i +", ttm is: "+ ttmS +",XstepValue is: "+XstepValue +", j: " ); - - if(wb.getEled()>0) - eu+=wb.getEled(); - if(wb.getEled() < 0) - ed+=wb.getEled(); - - if(ttmS >=XstepValue ||i==al.size()-1 ){ - if(i==al.size()-1) - { - QLog.getLogger().d(dTAG," it is here "); - } - - xE.add(xvalue); - yE.add( asp/(k+0.00) ); - // yE.add((double) wb.getEled()); - maxY =maxY< asp/(k) ?asp/(k):maxY; - minY =minY< asp/(k) ?minY:asp/(k); - asp=0.0; - k=0; - ttmS =0; - - xD.add(xvalue); - yD.add(ed); - yU.add(eu); -// xE.add(xvalue); -// yE.add((double) wb.getElevation()); - // j++; - } - } - - -// if(maxY-minY<1000){ -// maxY=maxY*2; //扩大图形范围,使不精确的小的海拔变化波动在图上不明显 -// minY=minY*2; -// } - yValues.add(getDv(yE)); //e y - yValues.add( getDv(yU) );//e up y - yValues.add( getDv(yD) );//e down y - xValues.add(getDv(xE,true)); //e x - xValues.add(getDv(xD,true)); //e up x - xValues.add(getDv(xD)); //e down x - - - } - - - } - } - - - - \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistEleChart.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistEleChart.java deleted file mode 100644 index dd37e81..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistEleChart.java +++ /dev/null @@ -1,269 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import org.achartengine.ChartFactory; - -import android.content.Context; -import android.content.Intent; -import android.view.View; - -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -/** - *X: distance - *Y: ele, sum ele - */ -public class DistEleChart extends AbstractChart { - public static final String TAG ="com.qiyou.DistEleChart"; - public static final String dTAG ="com.qiyou"; - - - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, - "高度变化"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - @Override - public View getChartView(Context context) - { - View v = null; - try{ - setFontSize(context); - buildChartData(); - v= ChartFactory.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - } - @Override - public void buildChartData(){ - getTitles(); - getMinY(); - getXYvalues(); - - dataset = buildDataset(titles, xValues, yValues); - renderer = getRender(3," ", "距离(公里)", "高度(米)"); - - renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right - renderer.isApplyBackgroundColor(); - renderer.setXLabels(20); //数字的个数 - renderer.setYLabels(10); - - } - - - - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*3]; - int i=0; - String name=""; - for(Track tr:trs){ - if(tr ==null)continue; -// name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); - titles[i] =name + "高度"; - i++; - titles[i] =name + "累积升高"; - i++; - titles[i] =name + "累积下降"; - i++; - - } - - - } - - /* - * return max time of minutes - */ - - -@Override -public double getMaxY(){ - double tmp =0; - for(Track tr:trs){ - if(tr ==null)continue; - - tmp = tr.getTrackBean().geteUpDist()>tmp? tr.getTrackBean().geteUpDist():tmp; - - } - maxY =maxYtmp?tmp:minY; - - minY= minY*1.1; - - if( Math.abs(minY)<500){ - - minY=minY*2; //扩大图形范围,使不精确的小的海拔变化波动在图上不明显 - - } -} - - - void getXYvalues (){ - - xValues = new ArrayList(); - XstepValue = getMaxDist()/Xcnt; - ArrayList xD ; - ArrayList xE ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yD; // y e down - ArrayList yU; // y e up - ArrayList yE; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b &&!(b.getEled()==0 &&b.getElevation()==0)) - al.add(b); - } - - yD =new ArrayList(); -// yD.add(0, 0D); - yU =new ArrayList(); -// yU.add(0, 0D); - yE =new ArrayList(); - xD = new ArrayList(); -// xD.add(0, 0D); - xE =new ArrayList(); - double ttmS =0 ; //step value for Speed - long tm=0; - Waypoint_bean wb; - int j=0; - double k=0; - double asp =0.0; //step average Speed - long trStartTime; - double lwb; - double xvalue=0; - double eu=0; - double ed=0; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 &&al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - - wb = al.get(i); - j++; -// if(j==1){ -// minX=wb.getSumDist()/1000; -// } - - trStartTime =tr.getTrackBean().getStartTime(); -// lwb = i>0?al.get(i-1).getDistance():0; - lwb = al.get(i).getDistance(); - xvalue = wb.getSumDist()/1000.0; - ttmS+=wb.getDistance()/1000; - - asp +=wb.getElevation(); - // asp +=wb.getEled(); - k++; - // QLog.getLogger().d(dTAG,"i: "+ i +", ttm is: "+ ttmS +",XstepValue is: "+XstepValue +", j: " ); - - if(wb.getEled()>0) - eu+=wb.getEled(); - if(wb.getEled() < 0) - ed+=wb.getEled(); - - if(ttmS >=XstepValue ||i==al.size()-1 ){ - if(i==al.size()-1) - { - QLog.getLogger().d(dTAG," it is here "); - } - - xE.add(xvalue); - yE.add( asp/(k+0.00) ); - // yE.add((double) wb.getEled()); - maxY =maxY< asp/(k) ?asp/(k):maxY; - minY =minY< asp/(k) ?minY:asp/(k); - asp=0.0; - k=0; - ttmS =0; - - xD.add(xvalue); - yD.add(ed); - yU.add(eu); -// xE.add(xvalue); -// yE.add((double) wb.getElevation()); - // j++; - } - } - - -// if(maxY-minY<1000){ -// maxY=maxY*2; //扩大图形范围,使不精确的小的海拔变化波动在图上不明显 -// minY=minY*2; -// } - yValues.add(getDv(yE)); //e y - yValues.add( getDv(yU) );//e up y - yValues.add( getDv(yD) );//e down y - xValues.add(getDv(xE,true)); //e x - xValues.add(getDv(xD,true)); //e up x - xValues.add(getDv(xD)); //e down x - - - } - - - } - } - - - - \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistEleChartNoDown.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistEleChartNoDown.java deleted file mode 100644 index 35870ec..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistEleChartNoDown.java +++ /dev/null @@ -1,283 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import org.achartengine.ChartFactory; - -import android.content.Context; -import android.content.Intent; -import android.view.View; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -/** - *X: distance - *Y: ele, sum ele - */ -public class DistEleChartNoDown extends AbstractChart { - public static final String TAG ="com.qiyou.DistEleChart"; - public static final String dTAG ="com.qiyou"; - - - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, - "高度变化"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - @Override - public View getChartView(Context context) - { - View v = null; - try{ - setFontSize(context); - buildChartData(); - v= ChartFactory.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - } - @Override - public void buildChartData(){ - getTitles(); -// getMinY(); - getXYvalues(); - - dataset = buildDataset(titles, xValues, yValues); - renderer = getRender(2," ", "距离(公里)", "高度(米)"); - int left= (int) (QiYouConstant.PV_INT_SCREEN_WIDTH/480f *40); - int bottom =(int) (QiYouConstant.PV_INT_SCREEN_WIDTH/480f *30); -// renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right - renderer.setMargins(new int[] { 1, left,bottom, 0 });//top,left,bottom,right - -// renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right - renderer.isApplyBackgroundColor(); - renderer.setXLabels(20); //数字的个数 - renderer.setYLabels(10); - - } - - - - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*2]; - int i=0; - String name=""; - for(Track tr:trs){ - if(tr ==null)continue; -// name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); - titles[i] =name + "高度"; - i++; - titles[i] =name + "累积升高"; - i++; -// titles[i] =name + "累积下降"; -// i++; - - } - - - } - - /* - * return max time of minutes - */ - - -@Override -public double getMaxY(){ - double tmp =0; - for(Track tr:trs){ - if(tr ==null)continue; - - tmp = tr.getTrackBean().geteUpDist()>tmp? tr.getTrackBean().geteUpDist():tmp; - - } - maxY =maxYtmp?tmp:minY; - - minY= minY*1.1; - - if( Math.abs(minY)<500){ - - minY=minY*2; //扩大图形范围,使不精确的小的海拔变化波动在图上不明显 - - } -} - - - void getXYvalues (){ - - xValues = new ArrayList(); - XstepValue = getMaxDist()/Xcnt; - XstepValue=XstepValue>0.5?0.5:XstepValue; - ArrayList xD ; - ArrayList xE ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yD; // y e down - ArrayList yU; // y e up - ArrayList yE; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b &&!(b.getEled()==0 &&b.getElevation()==0)) - al.add(b); - } - - yD =new ArrayList(); -// yD.add(0, 0D); - yU =new ArrayList(); -// yU.add(0, 0D); - yE =new ArrayList(); - xD = new ArrayList(); -// xD.add(0, 0D); - xE =new ArrayList(); - double ttmS =0 ; //step value for Speed - long tm=0; - Waypoint_bean wb; - int j=0; - double k=0; - double asp =0.0; //step average Speed - long trStartTime; - double lwb; - double xvalue=0; - double eu=0; - double ed=0; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 &&al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - - wb = al.get(i); - j++; -// if(j==1){ -// minX=wb.getSumDist()/1000; -// } - - trStartTime =tr.getTrackBean().getStartTime(); -// lwb = i>0?al.get(i-1).getDistance():0; - lwb = al.get(i).getDistance(); - xvalue = wb.getSumDist()/1000.0; - ttmS+=wb.getDistance()/1000; - - asp +=wb.getElevation(); - // asp +=wb.getEled(); - k++; - // QLog.getLogger().d(dTAG,"i: "+ i +", ttm is: "+ ttmS +",XstepValue is: "+XstepValue +", j: " ); - - if(wb.getEled()>0) - eu+=wb.getEled(); - if(wb.getEled() < 0) - ed+=wb.getEled(); - - if(ttmS >=XstepValue ||i==al.size()-1 ){ - if(i==al.size()-1) - { - QLog.getLogger().d(dTAG," it is here "); - } - - xE.add(xvalue); - yE.add( asp/(k+0.00) ); - // yE.add((double) wb.getEled()); - - maxY =maxY< asp/(k) ?asp/(k):maxY; - minY =minY< asp/(k) ?minY:asp/(k); - asp=0.0; - k=0; - ttmS =0; - - xD.add(xvalue); - yD.add(ed); - yU.add(eu); -// xE.add(xvalue); -// yE.add((double) wb.getElevation()); - // j++; - } - } - - -// if(maxY-minY<1000){ -// maxY=maxY*2; //扩大图形范围,使不精确的小的海拔变化波动在图上不明显 -// minY=minY*2; -// } - - /* xD.add(xvalue+1);// - yU.add(0d); - xE.add(xvalue+1); - yE.add(0d ); */ - - maxY+=50; - yValues.add(getDv(yE)); //e y - yValues.add( getDv(yU) );//e up y -// yValues.add( getDv(yD) );//e down y - xValues.add(getDv(xE,true)); //e x - xValues.add(getDv(xD,true)); //e up x -// xValues.add(getDv(xD)); //e down x - - - } - - - } - } - - - - \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistKmSpeedChart.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistKmSpeedChart.java deleted file mode 100644 index c44808c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistKmSpeedChart.java +++ /dev/null @@ -1,317 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import org.achartengine.ChartFactory; -import org.achartengine.chart.BarChart; -import org.achartengine.chart.LineChart; -import org.achartengine.renderer.SimpleSeriesRenderer; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Paint.Align; -import android.view.View; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - - -/** - *X: distance - *Y:time, speed - */ - -public class DistKmSpeedChart extends AbstractChart { - public static final String TAG ="com.qiyou.DistSpeedChart"; - public static final String dTAG ="com.qiyou"; - - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, "速度-距离"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - /* - * (non-Javadoc) - * @see com.qiyou.mb.android.ui.charts.AbstractChart#getChartView(android.content.Context) - */ - @Override - public View getChartView(Context context) - { - View v = null; - try{ - setFontSize(context); - buildChartData(); - String[] types; types= new String[] { BarChart.TYPE,BarChart.TYPE }; - v= ChartFactory.getCombinedXYChartView(context, dataset, renderer,types); -// v= ChartFactory.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - - - } - - @Override - public void buildChartData(){ - getTitles(); - getXYvalues(); - dataset = buildDataset(titles, xValues, yValues); - renderer = getRender(2, "", "距离(公里)", yTitle,true); - int left= (int) (QiYouConstant.PV_INT_SCREEN_WIDTH/480f *40); - int bottom =(int) (QiYouConstant.PV_INT_SCREEN_WIDTH/480f *30); - - -// renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right - renderer.setMargins(new int[] { 2, left,bottom, 0 });//top,left,bottom,right - -// renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right - renderer.setYLabels(20); - int length = renderer.getSeriesRendererCount(); - for (int i = 0; i < length; i++) { - SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i); - seriesRenderer.setDisplayChartValues(true); - seriesRenderer.setChartValuesTextSize(tFontSize); -// seriesRenderer.setChartValuesTextAlign(Align.CENTER); -// seriesRenderer.setDisplayChartValuesDistance(18); -// seriesRenderer.setChartValuesSpacing(5f); - } - } - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*2]; - int i=0; - String name="ID"; - for(Track tr:trs){ - if(tr ==null)continue; - name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); - - titles[i]="每公里总用时" ;// - i++; - - titles[i]="每公里运动用时";// - i++; - } - - - } - - String yTitle="配速(分钟)";//="时速--时间(分)"; -// String yTitle="";//="时速--时间(分)"; - double yTscale=1; - double ySscale=1; -/* @Override -public double getMaxY(){ - double maxYs =1; - double maxYt =1; - for(Track tr:trs){ - if(tr ==null)continue; -// maxSportTime = getMaxTime(); - -// maxY = tr.getTrackBean().getDistance()/1000.0>maxY? tr.getTrackBean().getDistance()/1000.0:maxY; - maxYs = tr.getTrackBean().getTopSpeed()>maxYs? tr.getTrackBean().getTopSpeed():maxYs; -// maxYt = getMaxTime()>maxYt? getMaxTime():maxYt; - } - if(maxYs>maxYt*2){ -// ySscale= Math.round(maxYs/maxYt); - ySscale= maxYs/maxYt ; - maxY = maxYs/ySscale ; - yTitle ="时速(x"+ Utils.round(ySscale,1) + "公里。小时)--时间(分)"; - } - else if(maxYt>maxYs*2){ -// yTscale = Math.round(maxYt/maxYs); - yTscale = maxYt/maxYs ; - maxY = maxYt/yTscale; - yTitle ="时速--时间(x"+ Utils.round(yTscale,1 )+"分)"; - }else - maxY = maxYs>maxYt?maxYs:maxYt; - QLog.getLogger().d(dTAG,TAG+" maxYs "+ maxYs +" maxYt: " +maxYt +" maxY: " +maxY ); - QLog.getLogger().d(dTAG,TAG+" YsScale "+ ySscale +" yTscale: " +yTscale ); - return maxY; - -// return maxYs; - return maxY; - }*/ - double maxY; - - public ArrayList getTrs() { - return trs; - } - - void getXYvalues (){ - minY=100; - getMaxY(); - xValues = new ArrayList(); - - XstepValue = 1000;//、、 getMaxDist()/Xcnt; -// XstepValue = getMaxDist()/100; -// double[] xD ; - ArrayList xD ; - ArrayList xS ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yT; //total time - ArrayList yS; //sport time - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - - yT =new ArrayList(); - yT.add(0, 0D); - yS =new ArrayList(); - yS.add(0, 0D); - xD = new ArrayList();//[Xcnt+1]; - xD.add(0, 0D);; - xS =new ArrayList(); - xS.add(0, 0D); - double ttmS =0 ; //step value for Speed -// double ttmt =0 ; //step value for time bar - - Waypoint_bean wb; -// int j=0; -// double k=0; -// double asp =0.0; //step average Speed -// long trStartTime; -// double lwb; - double xvalue=0; - double yt; - double ys; -// long lastSpTime=0; - long lastSpTime= 0; - long lastTotalTime=tr.getTrackBean().getStartTime(); - double xStepvalue= 1000; - minY=-201.11; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 &&al.get(i).getTime()< al.get(i-1).getTime()){ -// QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } -// wb = al.get(i); -// trStartTime =tr.getTrackBean().getStartTime(); -// lwb = i>0?al.get(i-1).getDistance():0; -// lwb = wb.getDistance(); -// xvalue = (int)(wb.getSumDist()/1000); - xvalue =Math.round(wb.getSumDist()/1000); - ttmS+=wb.getDistance(); -// ttmt+=wb.getDistance(); -// yt=(wb.getTime()-trStartTime)/1000.0/60.0/yTscale; -// yt=(wb.getSportTime())/1000.0/60.0/yTscale; -// yt=(wb.getSportTime()-lastSpTime)/1000.0/60.0/yTscale; -// lastSpTime = wb.getSportTime(); -// asp +=wb.getSpeed()/ySscale; -// QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale ); -// k++; - -// if(ttmS>=xStepvalue || i==al.size()-1 ){ // filter x distance data to not show all. //bar, minutes/km - if(xvalue>0 && wb.getKmflag()>0 ||ttmS>=xStepvalue|| i==al.size()-1 ){ -// yt=(wb.getSportTime()-lastSpTime)/1000.0/60.0; - yt=(wb.getTime()-lastTotalTime)/1000.0/60.0; - ys=(wb.getSportTime()-lastSpTime)/1000.0/60.0; -// QLog.getLogger().d(dTAG,TAG+" lastSpTime "+ lastSpTime + ",wb.getSportTime() "+wb.getSportTime() ); - - lastSpTime = wb.getSportTime(); - lastTotalTime = wb.getTime(); - QLog.getLogger().d(dTAG,"--------------------------------------- wb.getSumDist(): " +wb.getSumDist() ); - QLog.getLogger().d(dTAG,"i: "+ i +" xvalue: " +xvalue ); - QLog.getLogger().d(dTAG,"wb.getKmflag() " +wb.getKmflag() ); - QLog.getLogger().d(dTAG,"yt " +yt ); -// QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale ); - -// xvalue=wb.getKmflag()>0?wb.getKmflag():xvalue; - - xD.add(xvalue);// - yT.add(Utils.round(yt,1)); - - xS.add(xvalue); - yS.add(Utils.round(ys,1) ); - -// j=0; - if(minY==-201.11)minY= yt; - maxY=maxY>ys?maxY:ys; - minY =minY > yt ?yt:minY; - ttmS =0; - // xS.add(xvalue); - // yS.add( asp/(k+0.00) ); - // maxY=maxY> asp/(k+0.00)?maxY: asp/(k+0.00); - // asp=0.0; - // k=0; - // - } - - - - } - - xD.add(xvalue+0.1);// - yT.add(0d); - xS.add(xvalue+0.1); - yS.add(0d ); - -// minY=minY>3?minY:3; -// maxY=maxY<5*minY?maxY:5*minY; - float avkm=tr.getTrackBean().getSportTime()/60/1000/(tr.getTrackBean().getDistance()/1000); - - QLog.getLogger().d(dTAG,"total minutes: "+ tr.getTrackBean().getSportTime()/60/1000 ); - QLog.getLogger().d(dTAG,"distance km: "+ tr.getTrackBean().getDistance()/1000 ); - QLog.getLogger().d(dTAG,"avkm: "+Math.round(avkm) ); - QLog.getLogger().d(dTAG,"maxY: "+ maxY ); - - maxY=maxYmaxY? tr.getTrackBean().getDistance()/1000.0:maxY; - maxYs = tr.getTrackBean().getTopSpeed()>maxYs? tr.getTrackBean().getTopSpeed():maxYs; -// maxYt = getMaxTime()>maxYt? getMaxTime():maxYt; - } - /* if(maxYs>maxYt*2){ -// ySscale= Math.round(maxYs/maxYt); - ySscale= maxYs/maxYt ; - maxY = maxYs/ySscale ; - yTitle ="时速(x"+ Utils.round(ySscale,1) + "公里。小时)--时间(分)"; - } - else if(maxYt>maxYs*2){ -// yTscale = Math.round(maxYt/maxYs); - yTscale = maxYt/maxYs ; - maxY = maxYt/yTscale; - yTitle ="时速--时间(x"+ Utils.round(yTscale,1 )+"分)"; - }else - maxY = maxYs>maxYt?maxYs:maxYt; - QLog.getLogger().d(dTAG,TAG+" maxYs "+ maxYs +" maxYt: " +maxYt +" maxY: " +maxY ); - QLog.getLogger().d(dTAG,TAG+" YsScale "+ ySscale +" yTscale: " +yTscale ); - return maxY; - */ -// return maxYs; - return maxY; - } - double maxY; - - public ArrayList getTrs() { - return trs; - } - - void getXYvalues (){ - getMaxY(); - xValues = new ArrayList(); - - XstepValue = getMaxDist()/Xcnt; -// XstepValue = getMaxDist()/100; -// double[] xD ; - ArrayList xD ; - ArrayList xS ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yT; - ArrayList yS; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - - yT =new ArrayList(); - yT.add(0, 0D); - yS =new ArrayList(); - yS.add(0, 0D); - xD = new ArrayList();//[Xcnt+1]; - xD.add(0, 0D);; - xS =new ArrayList(); - xS.add(0, 0D); - double ttmS =0 ; //step value for Speed - double ttmt =0 ; //step value for time bar - - Waypoint_bean wb; - int j=0; - double k=0; - double asp =0.0; //step average Speed - long trStartTime; - double lwb; - double xvalue=0; - double yt; - long lastSpTime=0; - double xStepvalue= tr.getTrackBean().getDistance()/1000/10 ; - xStepvalue=xStepvalue>2?2:xStepvalue; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 &&al.get(i).getTime()< al.get(i-1).getTime()){ -// QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - wb = al.get(i); - trStartTime =tr.getTrackBean().getStartTime(); -// lwb = i>0?al.get(i-1).getDistance():0; - lwb = al.get(i).getDistance(); - xvalue = wb.getSumDist()/1000.0; - ttmS+=wb.getDistance()/1000; - ttmt+=wb.getDistance()/1000; -// yt=(wb.getTime()-trStartTime)/1000.0/60.0/yTscale; -// yt=(wb.getSportTime())/1000.0/60.0/yTscale; -// yt=(wb.getSportTime()-lastSpTime)/1000.0/60.0/yTscale; -// lastSpTime = wb.getSportTime(); - asp +=wb.getSpeed()/ySscale; -// QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale ); - k++; - - if(tr.getTrackBean().getTopSpeed() == wb.getSpeed()|| 0 == wb.getSpeed()){ -// QLog.getLogger().d(dTAG,TAG+" getTopSpeed(): "+tr.getTrackBean().getTopSpeed() ); -// QLog.getLogger().d(dTAG,TAG+" wb.getSpeed(): "+wb.getSpeed() ); -// QLog.getLogger().d(dTAG,TAG+" wb.getSpeed()/ySscale: "+ wb.getSpeed()/ySscale ); - - xS.add(xvalue); - yS.add( wb.getSpeed()/ySscale); - maxY=maxY> wb.getSpeed()?maxY:wb.getSpeed(); - - // xD.add(xvalue);// - // yT.add(yt); - } - else if(ttmt >=xStepvalue/5 ||i==al.size()-1 ){ //speed, km/h - j++; - xS.add(xvalue); - // yS.add( asp/(k ) ); - yS.add( (double) wb.getSpeed() ); - // maxY=maxY> asp/(k )?maxY: asp/(k ); - maxY=maxY>wb.getSpeed()?maxY: wb.getSpeed(); - asp=0.0; - k=0; - ttmt=0; - } - - /* if(ttmS>=xStepvalue || i==al.size()-1 ){ // filter x distance data to not show all. //bar, minutes/km - yt=(wb.getSportTime()-lastSpTime)/1000.0/60.0/yTscale/(xStepvalue); -// QLog.getLogger().d(dTAG,TAG+" lastSpTime "+ lastSpTime + ",wb.getSportTime() "+wb.getSportTime() ); - - lastSpTime = wb.getSportTime(); - // QLog.getLogger().d(dTAG,"i: "+ i +" xvalue: " +xvalue ); -// QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale ); - - xD.add(xvalue);// - yT.add(yt); - j=0; - - maxY=maxY>yt?maxY:yt; - ttmS =0; - // xS.add(xvalue); - // yS.add( asp/(k+0.00) ); - // maxY=maxY> asp/(k+0.00)?maxY: asp/(k+0.00); - // asp=0.0; - // k=0; - // - } */ - - - - } -// yValues.add( getDv(yT) ); -// xValues.add(getDv(xD,true)); //distance - - yValues.add(getDv(yS )); - xValues.add(getDv(xS,true)); //speed - - - - - } - } -} - - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistSpeedChartOld.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistSpeedChartOld.java deleted file mode 100644 index 9e7d1cd..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistSpeedChartOld.java +++ /dev/null @@ -1,243 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import org.achartengine.ChartFactory; - -import android.content.Context; -import android.content.Intent; -import android.view.View; - -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - - -/** - *X: distance - *Y:time, speed - */ - -public class DistSpeedChartOld extends AbstractChart { - public static final String TAG ="com.qiyou.DistSpeedChart"; - public static final String dTAG ="com.qiyou"; - - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, - "速度-距离"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - /* - * (non-Javadoc) - * @see com.qiyou.mb.android.ui.charts.AbstractChart#getChartView(android.content.Context) - */ - @Override - public View getChartView(Context context) - { - View v = null; - try{ - buildChartData(); - v= ChartFactory.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - - - } - - @Override - public void buildChartData(){ - getTitles(); - getXYvalues(); - dataset = buildDataset(titles, xValues, yValues); - renderer = getRender(2, "速度-时间 -距离", "距离(公里)", yTitle); - } - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*2]; - int i=0; - String name="ID"; - for(Track tr:trs){ - if(tr ==null)continue; - name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); - titles[i] =name + "时间"; - i++; - titles[i] =name + "速度"; - i++; - } - - - } - - String yTitle ="时速--时间(分)"; - double yTscale=1; - double ySscale=1; - @Override -public double getMaxY(){ - double maxYs =1; - double maxYt =1; - for(Track tr:trs){ - if(tr ==null)continue; -// maxSportTime = getMaxTime(); - -// maxY = tr.getTrackBean().getDistance()/1000.0>maxY? tr.getTrackBean().getDistance()/1000.0:maxY; - maxYs = tr.getTrackBean().getTopSpeed()>maxYs? tr.getTrackBean().getTopSpeed():maxYs; - maxYt = getMaxTime()>maxYt? getMaxTime():maxYt; - } - if(maxYs>maxYt*2){ -// ySscale= Math.round(maxYs/maxYt); - ySscale= maxYs/maxYt ; - maxY = maxYs/ySscale ; - yTitle ="时速(x"+ Utils.round(ySscale,1) + "公里。小时)--时间(分)"; - } - else if(maxYt>maxYs*2){ -// yTscale = Math.round(maxYt/maxYs); - yTscale = maxYt/maxYs ; - maxY = maxYt/yTscale; - yTitle ="时速--时间(x"+ Utils.round(yTscale,1 )+"分)"; - }else - maxY = maxYs>maxYt?maxYs:maxYt; - QLog.getLogger().d(dTAG,TAG+" maxYs "+ maxYs +" maxYt: " +maxYt +" maxY: " +maxY ); - QLog.getLogger().d(dTAG,TAG+" YsScale "+ ySscale +" yTscale: " +yTscale ); - return maxY; - } - - - public ArrayList getTrs() { - return trs; - } - - void getXYvalues (){ - getMaxY(); - xValues = new ArrayList(); - - XstepValue = getMaxDist()/Xcnt; -// double[] xD ; - ArrayList xD ; - ArrayList xS ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yT; - ArrayList yS; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - - yT =new ArrayList(); - yT.add(0, 0D); - yS =new ArrayList(); - yS.add(0, 0D); - xD = new ArrayList();//[Xcnt+1]; - xD.add(0, 0D);; - xS =new ArrayList(); - xS.add(0, 0D); - double ttmS =0 ; //step value for Speed -// double ttmD =0 ; //step value for distance - - Waypoint_bean wb; - int j=1; - int k=0; - double asp =0.0; //step average Speed - long trStartTime; - double lwb; - double xvalue=0; - double yt; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 &&al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - wb = al.get(i); - trStartTime =tr.getTrackBean().getStartTime(); -// lwb = i>0?al.get(i-1).getDistance():0; - lwb = al.get(i).getDistance(); - xvalue = wb.getSumDist()/1000.0; - ttmS+=wb.getDistance()/1000; - yt=(wb.getTime()-trStartTime)/1000.0/60.0/yTscale; - asp +=wb.getSpeed()/ySscale; -// QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale ); - k++; - if(tr.getTrackBean().getTopSpeed() == wb.getSpeed()|| 0 == wb.getSpeed()){ - xS.add(xvalue); - yS.add( wb.getSpeed()/ySscale); - } - else if(ttmS >=XstepValue ||i==al.size()-1 ){ - j++; - - if(i==al.size()-1){ - - QLog.getLogger().d(dTAG,TAG+"al.size() "+al.size() +",current wb "+ i); - QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale ); - - - } - -// if(i%9==1 || i==j-1) - if(j==10 || i==al.size()-1 ){ // filter x distance data to not show all. - -// QLog.getLogger().d(dTAG,"i: "+ i +" xvalue: " +xvalue ); - xD.add(xvalue);// - yT.add(yt); - j=0; - } - xS.add(xvalue); - yS.add( asp/(k+0.00) ); - - asp=0.0; - k=0; - ttmS =0; - -// j++; - } - - - } - - yValues.add( getDv(yT) ); - yValues.add(getDv(yS)); - xValues.add(getDv(xD,true)); //distance - xValues.add(getDv(xS,true)); //speed - - - } - } -} - - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistanceChart.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistanceChart.java deleted file mode 100644 index c1d7b9f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistanceChart.java +++ /dev/null @@ -1,246 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import org.achartengine.ChartFactory; - -import android.content.Context; -import android.content.Intent; -import android.text.TextUtils; -import android.view.View; - -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -/** - * Average temperature demo chart. - */ -public class DistanceChart extends AbstractChart { - public static final String TAG ="com.qiyou.DistanceChart"; - public static final String dTAG ="com.qiyou"; - - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, - "距离-时间"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - /* - * (non-Javadoc) - * @see com.qiyou.mb.android.ui.charts.AbstractChart#getChartView(android.content.Context) - */ - @Override - public View getChartView(Context context) - { - View v = null; - try{ - buildChartData(); - v= ChartFactory.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - - - } - - @Override - public void buildChartData(){ - getTitles(); - getXYvalues(); - dataset = buildDataset(titles, xValues, yValues); - renderer = getRender(2, "距离-时速-时间 ", "时间(分钟)", ""); - } - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*2]; - int i=0; - String name="ID"; - for(Track tr:trs){ - if(tr ==null)continue; - name =name+tr.getTrackBean().getTrackId(); - name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); -// titles[i] =name + "距离"; -// i++; -// titles[i] =name + "时速"; - titles[i] = "距离(公里)"; - i++; - titles[i] = "时速(公里/小时)"; - i++; - } - - - } - - - - - @Override -public double getMaxY(){ - double maxY =0; - for(Track tr:trs){ - if(tr ==null)continue; -// maxSportTime = tr.getTrackBean().getSportTime()>maxSportTime? tr.getTrackBean().getSportTime():maxSportTime; - - maxY = tr.getTrackBean().getDistance()/1000.0>maxY? tr.getTrackBean().getDistance()/1000.0:maxY; - maxY = tr.getTrackBean().getTopSpeed()>maxY? tr.getTrackBean().getTopSpeed():maxY; - } - - return maxY; - } - - - public ArrayList getTrs() { - return trs; - } - - void getXYvalues (){ - - xValues = new ArrayList(); - - double maxSportTime = getMaxTime(); - XstepValue = maxSportTime/Xcnt; -// double[] xD ; - ArrayList xD ; - ArrayList xS ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yD; - ArrayList yS; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - - yD =new ArrayList(); - yD.add(0, 0D); - yS =new ArrayList(); - yS.add(0, 0D); - xD = new ArrayList();//[Xcnt+1]; - xD.add(0, 0D);; - xS =new ArrayList(); - xS.add(0, 0D); - double ttmS =0 ; //step value for Speed -// double ttmD =0 ; //step value for distance - long tm=0; - Waypoint_bean wb; - int j=1; - int k=0; - double asp =0.0; //step average Speed - long trStartTime; - long lwb; - double xvalue=0; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 &&al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - wb = al.get(i); - trStartTime =tr.getTrackBean().getStartTime(); - lwb = i>0?al.get(i-1).getTime():trStartTime; - xvalue = (wb.getTime() -trStartTime)/1000.0/60.0; - tm = wb.getTime() -lwb;//how much time till the wp - ttmS+=tm/1000.0/60.0; - asp +=wb.getSpeed(); - k++; - if(!xS.contains(xvalue) && (tr.getTrackBean().getTopSpeed() == wb.getSpeed()|| 0 == wb.getSpeed())){ - xS.add(xvalue); - yS.add( (double) wb.getSpeed()); - } - if(ttmS >=XstepValue ||i==al.size()-1 ){ - j++; -// ttmD+=ttmS; - if(xS.size()>0 && wb.getOfftime() + wb.getPauseTime()>0) - { - xS.add( xS.get(xS.size()-1)); - yS.add(0D); - if(wb.getOfftime() + wb.getPauseTime()>ttmS ){ -// xD.add(xvalue);// - xD.add( xS.get(xS.size()-1)); - yD.add(wb.getSumDist()/1000.0); -// QLog.getLogger().d(dTAG,"j: "+ j +" xvalue: " +xvalue +", yvalue" +(wb.getSumDist()/1000.0)); - } -// j++; - - xS.add(xvalue); - yS.add( 0D); - - if(wb.getOfftime() + wb.getPauseTime()>ttmS && xvalue > xS.get(xS.size()-1)){ - xD.add(xvalue);// - yD.add(wb.getSumDist()/1000.0); -// QLog.getLogger().d(dTAG,"j: "+ j +" xvalue: " +xvalue +", yvalue" +(wb.getSumDist()/1000.0)); - } -// j++; - } - -// if(i%9==1 || i==j-1) - if(!xD.contains(xvalue) && (j==20 ||i==al.size()-1)){ // filter x distance data to not show all. - -// QLog.getLogger().d(dTAG,"i: "+ i +" xvalue: " +xvalue ); - - xD.add(xvalue);// - yD.add(wb.getSumDist()/1000.0); - j=0; - } - if(!xS.contains(xvalue)){ - xS.add(xvalue); - yS.add( asp/(k+0.00) ); - } - asp=0.0; - k=0; - ttmS =0; - -// j++; - } - - } - /*xD.add(xvalue+1);// - yD.add(0d); - xS.add(xvalue+1); - yS.add(0d ); */ - - yValues.add( getDv(yD) ); - yValues.add(getDv(yS)); - xValues.add(getDv(xD,true)); //distance - xValues.add(getDv(xS,true)); //speed - - - } - } -} - - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistanceSpeedBarChart.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistanceSpeedBarChart.java deleted file mode 100644 index a636d30..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/DistanceSpeedBarChart.java +++ /dev/null @@ -1,465 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import java.util.List; - -import org.achartengine.ChartFactory; -import org.achartengine.chart.BarChart; -import org.achartengine.chart.LineChart; -import org.achartengine.chart.PointStyle; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYSeriesRenderer; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Color; -import android.graphics.Paint.Align; -import android.view.View; - -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -/** - * Average temperature demo chart. - */ -public class DistanceSpeedBarChart extends AbstractChart { - public static final String TAG ="com.qiyou.DistanceChart"; - public static final String dTAG ="com.qiyou"; - String[] Dtitles ; - int[] colors ; - String[] Stitles ; - List xDvalues ; - List yDvalues ; - List xSvalues ; - List ySvalues ; -// XYMultipleSeriesDataset Ddataset; -// XYMultipleSeriesRenderer renderer; -// XYMultipleSeriesDataset Sdataset; - - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, - "距离-时间"); - ChartFactory.getLineChartView(context, dataset, renderer); - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - @Override - public View getChartView(Context context) - { - buildChartData(); - return ChartFactory.getLineChartView(context, dataset, renderer); - } - - - public View getChartBarView(Context context) - { - buildBarChartData(); - - String[] types; - - if(Dtitles.length>1) - types= new String[] { LineChart.TYPE, LineChart.TYPE, BarChart.TYPE , BarChart.TYPE }; - else - types= new String[] { LineChart.TYPE, BarChart.TYPE }; - - return ChartFactory.getCombinedXYChartView(context, dataset, renderer,types); -// return null; - } - @Override -public void buildChartData(){ - getTitles(); - getXYvalues(); - dataset = buildDataset(Dtitles, xDvalues, yDvalues); - renderer = getRender(2,"距离-速度-时间 ", "时间(分钟)", "距离(公里)/速度(公里/小时)"); - } - - - void buildBarChartData(){ - buildChartData(); -// Sdataset = buildDataset(Stitles, xSvalues, ySvalues); - updateRender(); - addXYSeries( dataset, Stitles, xSvalues, ySvalues, 0); -// Drenderer.addSeriesRenderer(renderer) - - - - -} - - - - void updateRender() - { - buildBarRenderer(renderer,colors); - } - - - private int Xcnt =30; - private double XstepValue; -// private ArrayList trs = new ArrayList(); - -// - XYMultipleSeriesRenderer getRender() - { - - int[] allColors = new int[] { Color.BLUE, Color.GREEN, Color.CYAN, Color.YELLOW }; - PointStyle[] allStyles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND, - PointStyle.TRIANGLE, PointStyle.SQUARE }; - - - colors = new int[trs.size()] ; - PointStyle[] styles = new PointStyle[trs.size()] ; - - - for(int i=0;i trs.size()) -// { -// String[] tmp =new String[trs.size()] ; -// int i=0; -// for(Track tr:trs){ -// i++; -// if(tr ==null)continue; -// tmp[i]=titles[i]; -// } -// titles =tmp; - - -// } - -// titles = new String[] { "Crete","Corfu"};//, "Corfu", "Thassos"}; -// return titles; - - } - - - - @Override -public double getMaxY(){ - double maxY =0; - for(Track tr:trs){ - if(tr ==null)continue; -// maxSportTime = tr.getTrackBean().getSportTime()>maxSportTime? tr.getTrackBean().getSportTime():maxSportTime; - - maxY = tr.getTrackBean().getDistance()/1000.0>maxY? tr.getTrackBean().getDistance()/1000.0:maxY; - maxY = tr.getTrackBean().getTopSpeed()>maxY? tr.getTrackBean().getTopSpeed():maxY; - } - - return maxY; - } - - - public ArrayList getTrs() { - return trs; - } - - -void getXYvalues(){ - - - - xDvalues = new ArrayList(); - xSvalues = new ArrayList(); - - double maxSportTime = getMaxTime(); - XstepValue = maxSportTime/Xcnt; - double[] xD ; - double[] xS ; - - yDvalues = new ArrayList(); - ySvalues = new ArrayList(); - double[] yD; - double[] yS; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - -// Yvalues = new double[(int) (al.size()/Xcnt)]; - yD = new double[Xcnt]; - yD[0] =0; - yS = new double[Xcnt]; - yS[0] =0; - xD = new double[Xcnt+1]; - xD[0] =0; - xS = new double[Xcnt+1]; - xS[0] =0; - float ttm =0 ; - long tm=0; - double xvalue=0; - Waypoint_bean wb; - int j=1; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 && al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - wb = al.get(i); - long lwb = i>0?al.get(i-1).getTime():tr.getTrackBean().getStartTime(); - xvalue = (wb.getTime() -tr.getTrackBean().getStartTime())/1000.0/60.0; - tm = wb.getTime() -lwb;//how much time till the wp - ttm+=tm; -// QLog.getLogger().d(dTAG,"i: "+ i +", ttm is: "+ ttm +",XstepValue is: "+XstepValue +", j: " +j); - - if(ttm >=XstepValue*1000*60 && j trs) { -// -// if(trs.size()>4) -// { -// this.trs.clear(); -// for(int i =0;i<=3;i++){ -// this.trs.add(trs.get(i)); -// } -// }else -// this.trs = trs; -// -// } -// -// -// List getX(){ -// -// List x = new ArrayList(); -// -// double maxSportTime = getMaxTime(); -// XstepValue = maxSportTime/Xcnt; -//// XstepValue = maxSportTime/Xcnt; -// double[] Xvalues = new double[Xcnt]; -// -//// for (int i = 0; i (); -//// for (int i = 0; i < trs.size(); i++) { -//// x.add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); -//// } -// return x; -// } - - - - /* - * build y data - * distance - - List getY(){ - - - -// [135.8497314453125, 35.55116271972656, 31.631629943847656, 31.566986083984375, 39.92951965332031, 17.68587875366211, 3.73708176612854, 22.835655212402344, 17.93094825744629, -// 9.902849197387695, 23.028324127197266, 134.236328125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] - List y = new ArrayList(); - - double[] Yvalues; - - for(Track tr:trs){ - ArrayList al = new ArrayList(); - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - -// Yvalues = new double[(int) (al.size()/Xcnt)]; - Yvalues = new double[Xcnt]; - Yvalues[0] =0; - float ttm =0 ; - long tm=0; - Waypoint_bean wb; - int j=1; -// for(Waypoint_bean wb:al){ - for(int i=0;i0?al.get(i-1).getTime():tr.getTrackBean().getStartTime(); - - tm = wb.getTime() -lwb;//how much time till the wp - ttm+=tm; - if(ttm >=XstepValue*1000*60 && j(); -// y.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2, -// 13.9 }); -// y.add(new double[] { 10, 10, 12, 15, 20, 24, 26, 26, 23, 18, 14, 11 }); -// y.add(new double[] { 5, 5.3, 8, 12, 17, 22, 24.2, 24, 19, 15, 9, 6 }); -// y.add(new double[] { 9, 10, 11, 15, 19, 23, 26, 25, 22, 18, 13, 10 }); - - return y; - } - - */ - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/charts/EleChart.java b/qy/src/main/java/com/qiyou/mb/android/ui/charts/EleChart.java deleted file mode 100644 index f1d8565..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/charts/EleChart.java +++ /dev/null @@ -1,274 +0,0 @@ - -package com.qiyou.mb.android.ui.charts; - -import java.util.ArrayList; -import org.achartengine.ChartFactory; - -import android.content.Context; -import android.content.Intent; -import android.view.View; - -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - - -/** - *X: distance - *Y: ele, sum ele - */ -public class EleChart extends AbstractChart { - public static final String TAG ="com.qiyou.EleChart"; - public static final String dTAG ="com.qiyou"; - - - - /** - * - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { - - buildChartData(); - Intent intent = null; - try{ - intent = ChartFactory.getLineChartIntent(context, dataset, renderer, - "高度变化"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - } - - @Override - public View getChartView(Context context) - { - View v = null; - try{ - buildChartData(); - v= ChartFactory.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - } - @Override - public void buildChartData(){ - getTitles(); - getXYvalues(); - getMinY(); - dataset = buildDataset(titles, xValues, yValues); - renderer = getRender(3,"高度 ", "时间(分钟)", "高度(米)"); - } - -// private int Xcnt =100; -// private double XstepValue; -// private ArrayList trs = new ArrayList(); - - - - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*3]; - int i=0; - String name="ID"; - for(Track tr:trs){ - if(tr ==null)continue; - name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); - titles[i] =name + "累积升高"; - i++; - titles[i] =name + "累积下降"; - i++; - titles[i] =name + "高度"; - i++; - } - - - } - - /* - * return max time of minutes - */ - - -@Override -public double getMaxY(){ - double tmp =0; - for(Track tr:trs){ - if(tr ==null)continue; - - tmp = tr.getTrackBean().geteUpDist()>tmp? tr.getTrackBean().geteUpDist():tmp; - - } - maxY =maxYtmp?tmp:minY; - minY= minY*1.1; -} - - - void getXYvalues (){ - - xValues = new ArrayList(); - - double maxSportTime = getMaxTime(); - XstepValue = maxSportTime/Xcnt; -// double[] xD ; - ArrayList xD ; - ArrayList xE ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yD; // y e down - ArrayList yU; // y e up - ArrayList yE; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - - yD =new ArrayList(); - yD.add(0, 0D); - yU =new ArrayList(); - yU.add(0, 0D); - yE =new ArrayList(); - xD = new ArrayList(); - xD.add(0, 0D); - xE =new ArrayList(); - double ttmS =0 ; //step value for Speed - long tm=0; - Waypoint_bean wb; - int j=0; - int k=0; - double asp =0.0; //step average Speed - long trStartTime; - long lwb; - double xvalue=0; - double eu=0; - double ed=0; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 && al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - wb = al.get(i); - trStartTime =tr.getTrackBean().getStartTime(); - lwb = i>0?al.get(i-1).getTime():trStartTime; - xvalue = (wb.getTime() -trStartTime)/1000.0/60.0; - tm = wb.getTime() -lwb;//how much time till the wp - ttmS+=tm/1000.0/60.0; - asp +=wb.getElevation(); -// asp +=wb.getEled(); - k++; -// QLog.getLogger().d(dTAG,"i: "+ i +", ttm is: "+ ttmS +",XstepValue is: "+XstepValue +", j: " ); - - if(wb.getEled()>0) - eu+=wb.getEled(); - if(wb.getEled() < 0) - ed+=wb.getEled(); - - if(ttmS >=XstepValue || i==al.size()-1){ - j++; - if(xE.size()>0 && wb.getOfftime() + wb.getPauseTime()>0) - { - - xE.add(xvalue); - yE.add( yE.get(yE.size()-1)); -// - if(wb.getOfftime() + wb.getPauseTime()>ttmS ){ -// - xD.add(xvalue); - yD.add(yD.get(yD.size()-1)); - yU.add(yU.get(yU.size()-1)); - - xD.add(xvalue); - yD.add(ed); - yU.add(eu); - - } - } - - if(!xD.contains(xvalue) &&(j==10 || i==al.size()-1)){ // filter x distance data to not show all. - -// QLog.getLogger().d(dTAG,"i: "+ i +" xvalue: " +xvalue ); - xD.add(xvalue);// - yD.add(ed); - yU.add(eu); - j=0; - } - if(!xE.contains(xvalue)){ - xE.add(xvalue); - yE.add( asp/(k+0.00) ); - } -// yE.add((double) wb.getEled()); - maxY =maxY trs = new ArrayList(); - - - - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*2]; - int i=0; -// String name="ID"; - String name=""; - for(Track tr:trs){ - if(tr ==null)continue; -// name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); -// titles[i] =name + "累积升高"; -// i++; -// titles[i] =name + "累积下降"; -// i++; - titles[i] =name + "升高"; - i++; - titles[i] =name + "下降"; - i++; - } - - - } - - /* - * return max time of minutes - */ - - -@Override -public double getMaxY(){ -// double maxY =0; -// for(Track tr:trs){ -// if(tr ==null)continue; -// -// maxY = tr.getTrackBean().geteUpDist()>maxY? tr.getTrackBean().geteUpDist():maxY; -// -// } - -// return maxY*1.1; - return maxY; - } - - -void getMinY(){ -// for(Track tr:trs){ -// if(tr ==null)continue; -// -// minY = tr.getTrackBean().geteDownDist()(); - - double maxSportTime = getMaxTime(); - XstepValue = maxSportTime/Xcnt; -// double[] xD ; -// ArrayList xD ; - ArrayList xE ; - - yValues = new ArrayList(); -// double[] yD; -// ArrayList yD; // y e down -// ArrayList yU; // y e up - ArrayList yEu; - ArrayList yEd; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b &&!(b.getEled()==0 &&b.getElevation()==0)) - al.add(b); - } - -// yD =new ArrayList(); -// yD.add(0, 0D); -// yU =new ArrayList(); -// yU.add(0, 0D); - yEu =new ArrayList(); - yEd =new ArrayList(); -// xD = new ArrayList(); -// xD.add(0, 0D); - xE =new ArrayList(); - double ttmS =0 ; //step value for Speed - long tm=0; - Waypoint_bean wb; - int j=0; - int k=0; - double aeu =0.0; //step average ed up - double aed =0.0; //step average ed down - long trStartTime; - long lwb; - double xvalue=0; -// double eu=0; -// double ed=0; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 && al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - wb = al.get(i); - - - trStartTime =tr.getTrackBean().getStartTime(); - lwb = i>0?al.get(i-1).getTime():trStartTime; - xvalue = (wb.getTime() -trStartTime)/1000.0/60.0; - tm = wb.getTime() -lwb;//how much time till the wp - ttmS+=tm/1000.0/60.0; - -// maxY =maxY0) - aeu+=wb.getEled() ; - if(wb.getEled() < 0) - aed+=wb.getEled() ; - - if(ttmS >=XstepValue ||i==al.size()-1){ - j++; - if(xE.size()>0 && wb.getOfftime() + wb.getPauseTime()>0) - { - - xE.add(xvalue); - yEd.add( yEd.get(yEd.size()-1)); - yEu.add( yEu.get(yEu.size()-1)); -// if(wb.getOfftime() + wb.getPauseTime()>ttmS ){ -//// -// xD.add(xvalue); -// yD.add(yD.get(yD.size()-1)); -// yU.add(yU.get(yU.size()-1)); -// -// xD.add(xvalue); -// yD.add(ed); -// yU.add(eu); -// -// } - } - -// if(j==10 ){ // filter x distance data to not show all. -// -//// QLog.getLogger().d(dTAG,"i: "+ i +" xvalue: " +xvalue ); -// xD.add(xvalue);// -// yD.add(ed); -// yU.add(eu); -// j=0; -// } - xE.add(xvalue); - yEu.add( aeu/(k+0.00) ); - yEd.add( aed/(k+0.00) ); -// yE.add((double) wb.getEled()); - - maxY =maxY trs = new ArrayList(); - - - - - - void getTitles(){ - if(trs.size()==0)return; - titles = new String[trs.size()*2]; - int i=0; - String name="ID"; - for(Track tr:trs){ - if(tr ==null)continue; - name =name+tr.getTrackBean().getTrackId(); -// name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name)); -// titles[i] =name + "累积升高"; -// i++; -// titles[i] =name + "累积下降"; -// i++; - titles[i] =name + "升高"; - i++; - titles[i] =name + "下降"; - i++; - } - - - } - - /* - * return max time of minutes - */ - - -@Override -public double getMaxY(){ -// double maxY =0; -// for(Track tr:trs){ -// if(tr ==null)continue; -// -// maxY = tr.getTrackBean().geteUpDist()>maxY? tr.getTrackBean().geteUpDist():maxY; -// -// } - -// return maxY*1.1; - return maxY; - } - - -void getMinY(){ -// for(Track tr:trs){ -// if(tr ==null)continue; -// -// minY = tr.getTrackBean().geteDownDist()(); - - double maxSportTime = getMaxTime(); - XstepValue = maxSportTime/Xcnt; -// double[] xD ; -// ArrayList xD ; - ArrayList xE ; - - yValues = new ArrayList(); -// double[] yD; -// ArrayList yD; // y e down -// ArrayList yU; // y e up - ArrayList yEu; - ArrayList yEd; - - for(Track tr:trs){ - if(tr==null)continue; - ArrayList al = new ArrayList(); - - for(Waypoint_bean b:tr.getTrackBean().getTrkseg()) - { - if (null !=b) - al.add(b); - } - -// yD =new ArrayList(); -// yD.add(0, 0D); -// yU =new ArrayList(); -// yU.add(0, 0D); - yEu =new ArrayList(); - yEd =new ArrayList(); -// xD = new ArrayList(); -// xD.add(0, 0D); - xE =new ArrayList(); - double ttmS =0 ; //step value for Speed - long tm=0; - Waypoint_bean wb; - int j=0; - int k=0; - double aeu =0.0; //step average ed up - double aed =0.0; //step average ed down - long trStartTime; - long lwb; - double xvalue=0; -// double eu=0; -// double ed=0; -// for(Waypoint_bean wb:al){ - for(int i=0;i0 && al.get(i).getTime()< al.get(i-1).getTime()){ - QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped."); - continue; - } - wb = al.get(i); - trStartTime =tr.getTrackBean().getStartTime(); - lwb = i>0?al.get(i-1).getTime():trStartTime; - xvalue = (wb.getTime() -trStartTime)/1000.0/60.0; - tm = wb.getTime() -lwb;//how much time till the wp - ttmS+=tm/1000.0/60.0; - - // maxY =maxY0) - aeu+=wb.getEled() ; - if(wb.getEled() < 0) - aed+=wb.getEled() ; - - if(ttmS >=XstepValue ||i==al.size()-1){ - j++; -// if(xE.size()>0 && wb.getOfftime() + wb.getPauseTime()>0) -// { -// -//// xE.add(xvalue); -//// yEd.add( yEd.get(yEd.size()-1)); -//// yEu.add( yEu.get(yEu.size()-1)); -// -// -// } - xE.add(xvalue); - yEu.add( aeu/(k+0.00) ); - yEd.add( aed/(k+0.00) ); - // yE.add((double) wb.getEled()); - - maxY =maxY values=new HashMap(); - DefaultRenderer renderer ; -/* public TrackPieChart(SparseArray statisticsTracks){ - if(statisticsTracks==null)return; - StatisticsTrack st; - double value=0; - for(int i=0;i<=statisticsTracks.size();i++){ - st=statisticsTracks.get(i); - if(st==null)continue; - value =st.getStaticsTrackBeans().size(); - if(value>0){ - values.put(TrackType.valueOf(i).toCHString(),value); - } - } - buildChartData(); - - - } - - public TrackPieChart(HashMap trackStatMap){ - values.putAll(trackStatMap); - buildChartData(); - - - }*/ - List Citems; - - public TrackPieChart(List citems){ - /* if(citems==null)return; - for(CItem citem:citems){ - if(citem==null)continue; - - if(citem.getCnt()>0){ - values.put(TrackType.valueOf(Integer.valueOf(citem.GetID())).toCHString(),(double) citem.getCnt()); - } - } - values.clear(); - CItem citem; - for(int i=citems.size()-1;i>=0;i--){ - citem=citems.get(i); - if(citem==null)continue; - if(citem.getCnt()>0){ - values.put(TrackType.valueOf(Integer.valueOf(citem.GetID())).toCHString(),(double) citem.getCnt()); - } - } - if(values.size()>0)*/ - Citems =citems; - buildChartData(); - } - - - public String getName() { - return "Track Statistics"; - } - - /** - * Returns the chart description. - * - * @return the chart description - */ - public String getDesc() { - return "Track Statistics"; - } - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - @Override -public Intent execute(Context context) { -// double[] values = new double[] { 12, 14, 11, 10, 19 }; - - -// Intent intent = ChartFactory.getPieChartIntent(context, -// buildCategoryDataset("Track Statistics", values), renderer, "Budget"); -// return intent; - Intent intent = null; - try{ - intent = ChartFactory.getPieChartIntent(context, - buildCategoryDataset("Track Statistics", Citems), renderer, "Budget"); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - return intent; - - } - -@Override -public double getMaxY() { - // TODO Auto-generated method stub - return 0; -} - -@Override -public View getChartView(Context context) - { - View v = null; - try{ - setFontSize(context); - v= ChartFactory.getPieChartView(context, - buildCategoryDataset("Track Statistics", Citems), - renderer) ;//.getLineChartView(context, dataset, renderer); - - }catch(Exception er) - { - Utils.logStackTrace(er, TAG); - } - - return v; - - - } - -@Override -public void buildChartData() { - // TODO Auto-generated method stub - if(Citems.size()==0)return; -// int slateGrey = Integer.parseInt("708090",16); -// int[] allColors = new int[] {Color.GREEN,Color.CYAN, Color.RED, Color.GRAY, Color.DKGRAY,Color.MAGENTA, Color.YELLOW,Color.LTGRAY ,R.color.lightslategray}; - int[] allColors = { Color.parseColor("#56ADDB"),Color.parseColor("#FF8497"),Color.parseColor("#95AC5F"), CYRAN,Color.parseColor("#95AC5F"), - Color.parseColor("#F59331"), - Color.parseColor("#948D8B"), Color.parseColor("#73C83C"), - Color.parseColor("#FFD34E"), Color.parseColor("#E54273"), - Color.parseColor("#2A86D6"), Color.parseColor("#2A86D6"),Color.parseColor("#00BFC0") - }; - int[] colors = new int[Citems.size()] ; - - for(int i=0;i0?bottom:0; -// renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right - renderer.setMargins(new int[] { 1, left,bottom, 0 });//top,left,bottom,right - - -// renderer.setMargins(new int[] { 1, 55,48, 0 });//top,left,bottom,right - renderer.setXLabelsPadding(2); - - renderer.setPanEnabled(false); - renderer.setZoomEnabled(false); -// renderer.setShowLegend(false); -// renderer.setLabelsTextSize(8f); -// renderer.setLegendTextSize(8); - -// renderer.setMarginsColor(DARKCYRAN); - - } - - - void getTitles(){ - if(mTypeStatistics==null)return; - titles = new String[2]; - titles[0]="运动距离"; - titles[1]="运动均速"; -// titles[3]="最远距离"; - - - } - - - - - @Override -public double getMaxY(){ -// double maxY =0; -// -// if(mTypeStatistics ==null)return 0; -//// maxSportTime = tr.getTrackBean().getSportTime()>maxSportTime? tr.getTrackBean().getSportTime():maxSportTime; -// -// maxY = mTypeStatistics.getStatTrack().getMaxDist()/1000.0>maxY? mTypeStatistics.getStatTrack().getMaxDist()/1000.0:maxY; -// maxY = mTypeStatistics.getStatTrack().getMaxAvSpeed()>maxY? mTypeStatistics.getStatTrack().getMaxAvSpeed():maxY; -// - - return maxY; - } - - - public ArrayList getTrs() { - return trs; - } - - public double getTimePeriod() - { - double timePeriod =0.0; - if(mTypeStatistics!=null && mTypeStatistics.getSbs().size()>0){ -// long endTime =mTypeStatistics.getStaticsTrackBeans().get(mTypeStatistics.getStaticsTrackBeans().size()-1).getEndTime(); -// long start =mTypeStatistics.getStaticsTrackBeans().get(0).getStartTime(); -// timePeriod =endTime -start; - timePeriod =mTypeStatistics.getStart() -mTypeStatistics.getEnd(); - timePeriod = timePeriod/1000/60.0; - } - - return timePeriod ; - } - - - - void getXYvalues (){ - - xValues = new ArrayList(); - - double maxTime = getTimePeriod(); - XstepValue = maxTime/mTypeStatistics.getSbs().size(); -// long startTime = mTypeStatistics.getStaticsTrackBeans().get(0).getStartTime(); -// double[] xD ; - ArrayList xD ; - ArrayList xS ; - - yValues = new ArrayList(); -// double[] yD; - ArrayList yD; - ArrayList yS; - - - yD =new ArrayList(); -// yD.add(0, 0D); - yS =new ArrayList(); -// yS.add(0, 0D); - xD = new ArrayList();//[Xcnt+1]; -// xD.add(0, 0D);; - xS =new ArrayList(); -// xS.add(0, 0D); - - int i=0; - Statics_bean tr; - - for(Integer key :mTypeStatistics.getSbs().keySet()){ - tr=mTypeStatistics.getSbs().get(key); -// for(Statics_bean tr:mTypeStatistics.getSbs()){ - if(tr==null ||tr.getStartTime()==0)continue; - if(i==0)minX=tr.getTrackid(); - yD.add(tr.getDist()/1000d); -// xD.add((tr.getStartTime()-startTime)/1000/60.0); - xD.add(tr.getTrackid()/1.0); -// xD.add(tr.getTrackid()/1.0); - maxY=maxY>tr.getDist()/1000d?maxY:tr.getDist()/1000d; - - yS.add((double) tr.getAvs()); -// xS.add((tr.getStartTime()-startTime)/1000/60.0); - xS.add(tr.getTrackid()/1.0); -// xS.add(tr.getTrackid()/1.0); - maxY=maxY>tr.getAvs()?maxY:(double) tr.getAvs(); - - i++; - minX = minX>tr.getTrackid()?tr.getTrackid():minX; - - } - yValues.add( getDv(yD) ); - yValues.add(getDv(yS)); - xValues.add(getDv(xD,true)); //distance - xValues.add(getDv(xS,true)); //speed -// maxXvalue = maxXvalue>10? maxXvalue:10; - maxXvalue=i0 ? getResources().getString(R.string.frg_actdetail) +"|"+currentAct.getName() - : getResources().getString(R.string.frg_actnew); - - - currentLayout =R.layout.activity_detail; - vContainer = inflater.inflate(currentLayout, container, false); - - webTab="活动"; - initialViews( ); -// initialLLViews(); -// initialMapview(); - - return vContainer; - } - @Override - Activity_bean getCurrentAct(){ - return currentAct; - } - - @Override - void initialMapview(){ - super.initialMapview(); - /* endOverlay=getItemizedOverlay(R.drawable.icon_send); - startOverlay=getItemizedOverlay(R.drawable.icon_sstart); - actStartOverlay=getItemizedOverlay(R.drawable.icon_pass); - startOverlay=getItemizedOverlay(R.drawable.icon_sstart); - gpxOverlay =new GraphicsOverlay(mMapView); - mMapView.getOverlays().add(gpxOverlay);*/ - } - - - - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - IL = new ImageLoader(activity); -// int actid=-1; - -// showActivityDetail(svrNumber); - showWebObject(); - } - - void showWebObject(){ - showDetail(currentAct.getSvrNumber()); - } - @Override - void mapViewOnActivityCreated(){ - if(currentAct!=null && currentAct.getLat()>0){ - locateMapCenter(currentAct.getLat(),currentAct.getLon()); - - /*LatLng startGp =Utils.getLatLng(currentAct.getLat(),currentAct.getLon()); - setStartIcon(startGp); */ - -// setGeoIcon(startGp,actStartOverlay); - - }else{ - if(QiYouConstant.PV_LAST_LAT>0 ){ - locateMapCenter(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON); - } - } - } - - @Override - ArrayList getGpxTracks(){ - - return currentAct ==null? new ArrayList() - : currentAct.getRoadbooks(); -// return currentAct.getRoadbooks(); - } - - -// boolean isShareQuery=false; - protected String lastActShareQueryPara=""; - List> shareTrackData; - boolean isRemoveRoadbook; - boolean isRepeatAct; -// int svrNumber; - String title; -// protected ItemizedOverlay actStartOverlay =null; - Button btn_saveAct; - Button btn_submitAct; - Button btn_loadRoadbook; -// Button btn_removeRoadbook; - Button btn_refresh; - Button btn_actJoin; - Button btn_share; - Button btn_qcode; -// TextView td_track_sumary; - EditText act_roadbook; - EditText act_edit_title; -// LinearLayout ll_start_place; -// LinearLayout ll_end_place; - TextView txtStartGeoPicker;// act_txt_startGeo_picker - TextView txtEndGeoPicker; // act_txt_startGeo_picker - EditText edit_act_endGeo; - EditText edit_act_startGeo; - EditText act_edit_description; - RatingBar act_levlRatingBar; - TextView act_creator; - - TextView act_svrNo; - - EditText edit_act_startDate; - EditText edit_act_endDate; - - EditText edit_act_startTime; - EditText edit_act_endTime; - EditText edit_act_distance; - EditText edit_act_speed; - RadioGroup repeatRdGroup; - RadioGroup roadbookRdGroup; - RadioGroup actTypeRdGroup; - - TextView act_startplace_share; - TextView act_endplace_share; - QimageView imgTopBanner ; - - - - @Override - protected void initialViews(){ -// initialTabhost(); -// initialRoadBookViews(); -// liveList =(LinearLayout)vContainer.findViewById(R.id.ll_liveList) ; -// liveList.setVisibility(View.VISIBLE); - -// btn_refresh =(Button)vContainer.findViewById(R.id.act_btn_refresh); -// btn_refresh.setOnClickListener(ButtonOnClickListener); - imgTopBanner= (QimageView) vContainer.findViewById(R.id.imgTopBanner); - imgTopBanner.setOnClickListener(ButtonOnClickListener); - - btn_saveAct =(Button)vContainer.findViewById(R.id.btn_SaveAct); - btn_saveAct.setOnClickListener(ButtonOnClickListener); - btnShare =(Button)vContainer.findViewById(R.id.act_btn_share); - btnShare.setOnClickListener(ButtonOnClickListener); - - btn_submitAct =(Button)vContainer.findViewById(R.id.btn_submitAct); - btn_submitAct.setOnClickListener(ButtonOnClickListener); - - act_edit_description =(EditText)vContainer.findViewById(R.id.act_edit_desc); - act_levlRatingBar =(RatingBar)vContainer.findViewById(R.id.act_levlRatingBar); - -// td_track_sumary = (TextView) vContainer.findViewById(R.id.td_track_sumary); - - act_creator = (TextView) vContainer.findViewById(R.id.act_textview_creator); - act_svrNo = (TextView) vContainer.findViewById(R.id.act_textview_svrNo); - - -// act_roadbook = (EditText) vContainer.findViewById(R.id.act_edit_roadbook); - act_edit_title = (EditText) vContainer.findViewById(R.id.act_edit_title); ; - -// noRec = (TextView) vContainer.findViewById(R.id.trakList_tv_norec); - txtNote =(TextView)vContainer.findViewById(R.id.txt_web_note); - -// lvWeb.setOnItemClickListener(itemListener); -// lvWeb.setOnTouchListener(new OnTouchListener() { -// @Override -// public boolean onTouch(View v, MotionEvent event) { -// Utils.hideSoftKeyboard(activity); -// return false; -// } -// }); - - edit_act_startGeo =(EditText)vContainer.findViewById(R.id.act_edit_startGeo); - edit_act_distance= (EditText) vContainer.findViewById(R.id.act_edit_distance); - edit_act_speed= (EditText) vContainer.findViewById(R.id.act_edit_speed); - btn_actJoin =(Button)vContainer.findViewById(R.id.act_btn_join); - btn_actJoin.setOnClickListener(ButtonOnClickListener); - - btn_qcode =(Button)vContainer.findViewById(R.id.act_btn_qcode); - btn_qcode.setOnClickListener(ButtonOnClickListener); - btn_qcode.setVisibility(QiYouConstant.DEVELOPER_MODE?View.VISIBLE: View.GONE); - - txtStartGeoPicker = (TextView) vContainer.findViewById(R.id.act_txt_startGeo_picker); - txtStartGeoPicker.setOnClickListener(ButtonOnClickListener); - act_startplace_share = (TextView) vContainer.findViewById(R.id.act_txt_startGeo_share); - act_startplace_share.setOnClickListener(ButtonOnClickListener); - edit_act_startTime = (EditText) vContainer.findViewById(R.id.act_edit_starttime); - - popupText=(TextView) vContainer.findViewById(R.id.textcache); - - - /* btn_live_refresh =(Button)vContainer.findViewById(R.id.share_btn_refresh); - btn_live_list =(Button)vContainer.findViewById(R.id.share_btn_list); - btn_live_query =(Button)vContainer.findViewById(R.id.share_btn_query); - - btn_live_refresh.setOnClickListener(ButtonOnClickListener); - btn_live_list.setOnClickListener(ButtonOnClickListener); - btn_live_query.setOnClickListener(ButtonOnClickListener);*/ - -// btn_pageup=(ImageButton)vContainer.findViewById(R.id.btn_webpageup); -// btn_pageup.setOnClickListener(ButtonOnClickListener); -// btn_pagedown=(ImageButton)vContainer.findViewById(R.id.btn_webpagedown); -// btn_pagedown.setOnClickListener(ButtonOnClickListener); - - initialExtraViews(); -// initialMapview(); -// initialLoadingMore(); - -// textContainer =(android.widget.ScrollView)vContainer.findViewById(R.id.td_scrollView); -// if(textContainer!=null) -// textContainer.setOnTouchListener(new OnTouchListener() { -// @Override -// public boolean onTouch(View v, MotionEvent event) { -// Utils.hideSoftKeyboard(activity); -// return false; -// } -// }); - - - } - - - void initialExtraViews(){ - edit_act_endGeo =(EditText)vContainer.findViewById(R.id.act_edit_endGeo); - - -// timePickerListener tpl= new timePickerListener(); - dateTimePickerListener dtpl = new dateTimePickerListener(); - tl = new datePickerListener(); - edit_act_endTime = (EditText) vContainer.findViewById(R.id.act_edit_endtime); - - edit_act_startTime.setOnTouchListener(dtpl); - edit_act_endTime.setOnTouchListener(dtpl); - - repeatRdGroup = (RadioGroup)vContainer.findViewById(R.id.act_rdGroup_repeat); - if(repeatRdGroup!=null) - repeatRdGroup.setOnCheckedChangeListener(rdgChanged); - - - - - actTypeRdGroup = (RadioGroup)vContainer.findViewById(R.id.act_rdGroup_type); - if(actTypeRdGroup!=null) - actTypeRdGroup.setOnCheckedChangeListener(rdgChanged); - - - txtEndGeoPicker = (TextView) vContainer.findViewById(R.id.act_txt_endGeo_picker); - txtEndGeoPicker.setOnClickListener(ButtonOnClickListener); - - - act_endplace_share = (TextView) vContainer.findViewById(R.id.act_txt_endGeo_share); - act_endplace_share.setOnClickListener(ButtonOnClickListener); - - super.BBScate = BBSCate.ACT.toInt(); -// - } - - - - - OnCheckedChangeListener rdgChanged = new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(RadioGroup arg0, int arg1) { - // TODO Auto-generated method stub - //获取变更后的选中项的ID - int radioButtonId = arg0.getCheckedRadioButtonId(); - //根据ID获取RadioButton的实例 -// RadioButton rb = (RadioButton)activity.findViewById(radioButtonId); - - if(radioButtonId ==R.id.act_rd_addroadbook){ - isRemoveRoadbook =false; - }else if(radioButtonId ==R.id.act_rd_removeroadbook){ - isRemoveRoadbook=true; - } else if(radioButtonId ==R.id.act_rd_single){ - edit_act_startTime.setBackgroundColor(getResources().getColor(R.color.linen)); - edit_act_endTime.setBackgroundColor(getResources().getColor(R.color.linen)); -// edit_act_startTime.setTextAppearance(activity, R.style.activtity_edit_required); -// edit_act_endTime.setTextAppearance(activity, R.style.activtity_edit_required); - showRepeatDays(false); - - } else if(radioButtonId ==R.id.act_rd_multi){ - edit_act_startTime.setBackgroundColor(getResources().getColor(R.color.ivory)); - edit_act_endTime.setBackgroundColor(getResources().getColor(R.color.ivory)); -// edit_act_startTime.setTextAppearance(activity, R.style.activtity_edit); -// edit_act_endTime.setTextAppearance(activity, R.style.activtity_edit); - showRepeatDays(true); - } else if(radioButtonId ==R.id.act_rd_public){ - setActType(ActivityType.PUBLIC); - } else if(radioButtonId ==R.id.act_rd_cycle){ - setActType(ActivityType.CYCLE); - }else if(radioButtonId ==R.id.act_rd_private){ - setActType(ActivityType.PRIVATE); - } - - - } - }; - - - @Override - void pickGeoPlace(int textViewId){ -// activity.addressTextId=textViewId; -// activity.showLocationFinder(); - saveSvrObj(); - activity.addressTextId=textViewId; - setbackGeoInfo(textViewId); - activity.showLocationFinder(); - - - - - } - - void setbackGeoInfo(int textViewId){ - if(textViewId == R.id.act_txt_startGeo_picker){ - activity.latToshow =currentAct.getLat(); - activity.lngToshow =currentAct.getLon(); - - }else if(textViewId == R.id.act_txt_endGeo_picker){ - activity.latToshow =currentAct.getEndGeo().getLat(); - activity.lngToshow =currentAct.getEndGeo().getLon(); - } - - } - - void setActType(ActivityType type){ -// ActivityType actype = ActivityType.valueOf(type); - currentAct.setType( type/*ActivityType.valueOf(type)*//*actype*/); - - - } - - void showRepeatDays(boolean isShow){ - isRepeatAct =isShow; - vContainer.findViewById(R.id.act_ll_days).setVisibility(isShow?View.VISIBLE:View.GONE); - - - } - @Override - void onTimePicked(int viewId,long timePicked){ - if (viewId == R.id.act_edit_starttime) { - currentAct.setStartDate(timePicked); - }else if (viewId == R.id.act_edit_endtime){ - currentAct.setEndDate(timePicked); - } - - } - - -// final String shareTab ="分享"; -// String memberTab ="成员"; -// String webTab="活动"; - String roadbookTab ="路书"; - final String actLiveTab ="直播"; - final int tabResourceId = R.id.tab_webquery; - @Override - void creatTabs(){ - - memberTab ="成员"; - - tabBbs = tabhost.newTabSpec(bbsTab); - tabBbs.setIndicator(bbsTab/*, getResources().getDrawable(R.drawable.icon_user,null)*/); -// tabBbs.setContent(R.id.tab_bbs); - - tabBbs.setContent(tabResourceId); - - tabRoadbook = tabhost.newTabSpec(roadbookTab); - tabRoadbook.setIndicator(roadbookTab); -// tabRoadbook.setContent(R.id.tab_webquery); - tabRoadbook.setContent(tabResourceId); - - tabUser = tabhost.newTabSpec(memberTab); - tabUser.setIndicator(memberTab); -// tabUser.setContent(R.id.act_tab_members); - tabUser.setContent(tabResourceId); - - tabTrack = tabhost.newTabSpec(shareTab); - tabTrack.setIndicator(shareTab); -// tabTrack.setContent(R.id.act_tab_share); - tabTrack.setContent(tabResourceId); - - tabLive = tabhost.newTabSpec(actLiveTab); - tabLive.setIndicator(actLiveTab); -// tabLive.setContent(R.id.tab_map); - tabLive.setContent(tabResourceId); - - tabAct = tabhost.newTabSpec(actTab); - tabAct.setIndicator(actTab); -// tabLive.setContent(R.id.tab_map); - tabAct.setContent(tabResourceId); - - tabGrp = tabhost.newTabSpec(grpTab); - tabGrp.setIndicator(grpTab); -// tabLive.setContent(R.id.tab_map); - tabGrp.setContent(tabResourceId); - - - } - /* - @Override - void addTabs(){ - - tabhost.addTab(t1); - - if(currentAct.getSvrNumber()>0) { - ((LinearLayout)vContainer.findViewById(R.id.act_tab_members)).setVisibility( View.VISIBLE ); - ((LinearLayout)vContainer.findViewById(R.id.act_tab_share)).setVisibility( View.VISIBLE ); - ((LinearLayout)vContainer.findViewById(R.id.tab_map)).setVisibility( View.VISIBLE ); - - - tabhost.addTab(t2); - - - tabhost.addTab(t3); - - - tabhost.addTab(t4); - - }else{ - ((LinearLayout)vContainer.findViewById(R.id.act_tab_members)).setVisibility( View.GONE ); - ((LinearLayout)vContainer.findViewById(R.id.act_tab_share)).setVisibility( View.GONE ); - ((LinearLayout)vContainer.findViewById(R.id.tab_map)).setVisibility( View.GONE ); -// - } - } - */ - /* - int newTabId=-1; - @Override - void addPic(LinearLayout ll,int currentTab,int tabsCnt){ - if(currentTab>newTabId){ - super.addPic(ll, currentTab ,tabsCnt); - } - - ll.setPadding(10, 0, 0, 0); - } - */ - - - @Override - void loadRoadBook(){ -// activity.showLocationFinder(); - - - - - - - - if(isRemoveRoadbook){ - delActBook(); - return; - } - this.firstLoad=false; - lastWebQueryPara=""; - if(!TextUtils.isEmpty(act_roadbook.getText())){ -// this.requestTrackFromWeb( Integer.valueOf(act_roadbook.getText().toString())); - if(!currentAct.getRoadbooks().contains(Integer.valueOf(act_roadbook.getText().toString()))){ - currentAct.getRoadbooks().add(Integer.valueOf(act_roadbook.getText().toString())); - doWebTrackQuery();//query out the added roadbooks - updateRoadbooks(); - }else{ - //show msg that the roadbook was already added - Toast.makeText(activity, "已经添加了该路书", Toast.LENGTH_SHORT).show(); - } - } - } - - @Override - void delActBook(){ - firstLoad=false; - if(!TextUtils.isEmpty(act_roadbook.getText())){ - if(currentAct.getRoadbooks().contains(Integer.valueOf(act_roadbook.getText().toString()))){ - - - AlertDialog.Builder builder = new Builder(activity); - builder.setMessage("是否删除该路书?"); - builder.setTitle("提示"); - builder.setCancelable(false); - builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - currentAct.getRoadbooks().remove(Integer.valueOf(act_roadbook.getText().toString())); - Toast.makeText(activity, "移除路书成功", Toast.LENGTH_SHORT).show(); - if(currentAct.getRoadbooks().size()>0){ - doWebTrackQuery();//query out the added roadbooks - }else{ - trackData = new ArrayList>(); - showWebTrackListData(trackData); - - } - updateRoadbooks(); - - - } - }); - builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - }); - builder.create().show(); - - - }else{ - //show msg that the roadbook was already added - Toast.makeText(activity, "活动没有添加该路书", Toast.LENGTH_SHORT).show(); - } - } - - } - - //update web activity roadbook - void updateRoadbooks(){ - if(currentAct.getSvrNumber()>0){ - Activity_bean tmp = new Activity_bean(); - tmp.setSvrNumber(currentAct.getSvrNumber()); - tmp.setRoadbooks(currentAct.getRoadbooks()); - this.postJsonWS(Utils.getGsonString(tmp), RestMethods.ACT_P_UPDATE_ROODBOOK); - - } - } - - /*@Override - void showWebTrack(Track track){ - if(track==null)return; - staticMapImg= (QimageView) vContainer.findViewById(R.id.td_staticMap); - td_track_sumary.setText(track.getSummary()); - if(staticMapImg==null)return; - IL.DisplayImage(track.getStaticMap(),staticMapImg); - act_roadbook.setText(track.getTrackBean().getName()); - }*/ - - - - - private void showDetail(int actid){ - if(actid>0 && currentAct!=null && actid==currentAct.getSvrNumber()){ - - -// initialWebQuery(); - - - /* if(currentAct.getRoadbooks().size()>0){ - for(int i =0;i0){ - requestTrackFromWeb(currentAct.getRoadbooks().get(i));//only toget general data - break; - } - } - }*/ - - btn_submitAct.setText("更新"); - - }else{ //start new action - newActivity(); - - } - - getDetails(); - - - } - - - void newActivity(){ - loadLocalActivity(); - if(currentAct==null||currentAct.getSvrNumber()>0){ - currentAct = new Activity_bean(); - currentAct.setUserId(activity.app.user.getUserbean().getId()); - currentAct.setUserName(activity.app.user.getUserbean().getUserName()); - } -// setActivityDetails(); - - - - } - void getDetails(){ - - - - if(currentAct.getSvrNumber()>0 ){ -// act_creator.setText(currentAct.getUserName()); - setUserLinkSpanTxt(act_creator,currentAct.getUserId(),currentAct.getUserName()); - - this.BBScate = BBSCate.ACT.toInt(); // act - this.BBSSubcate = currentAct.getSvrNumber(); - this.BBSsubCateName = currentAct.getName(); - }else{ - act_creator.setText(activity.app.user.getUserbean().getUserName()); - } - if ( !TextUtils.isEmpty(currentAct.getAlbum()) ){ - if (currentAct.getSvrNumber() > 0){ - IL.DisplayImage(QiYouConstant.BASE_MD_URL + currentAct.getAlbum(), this.imgTopBanner); - }else{ - IL.DisplayImage(currentAct.getAlbum(), this.imgTopBanner); - } - }else { - this.imgTopBanner.setBackgroundResource(R.drawable.icon_actbanner); - } - act_edit_title.setText(currentAct.getName());// + (currentAct.getSvrNumber() > 0 ? "" : "<草稿>")); -// this.edit_act_endGeo.setText(currentAct.getEndAddress()); -// this.edit_act_startGeo.setText(currentAct.getStartAddress()); - this.edit_act_startGeo.setText(currentAct.getStartPlace()); - urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,currentAct.getStartAddressUrl()); - - - this.edit_act_endGeo.setText(currentAct.getEndPlace()); - urlFormat(R.id.act_txt_endGeo_map,R.id.act_txt_endGeo_share,currentAct.getEndAddressUrl()); - act_edit_description.setText(currentAct.getDescription()); -// if(currentAct.getSvrNumber()>0) - act_levlRatingBar.setRating(currentAct.getRateLevel()); - - edit_act_startTime.setText(Utils.getFormatedTime(currentAct.getStartDate())); - edit_act_endTime.setText(Utils.getFormatedTime(currentAct.getEndDate())); - - edit_act_distance.setText(String.format("%.0f",currentAct.getDistance())); - edit_act_speed.setText(String.format("%.0f",currentAct.getAvSpeed())); - if(currentAct.getSvrNumber()>0){ - act_svrNo.setText(currentAct.getSvrNumber()+""); - } - - isRepeatAct = currentAct.isRepeatable(); - showRepeatDays(isRepeatAct); - ((RadioButton)repeatRdGroup.getChildAt(1)).setChecked(isRepeatAct); - for(int i:currentAct.getDays()){ - switch (i){ - case 1: ((CheckBox) vContainer.findViewById(R.id.act_chk_day_1)).setChecked(true); break; - case 2: ((CheckBox) vContainer.findViewById(R.id.act_chk_day_2)).setChecked(true); break; - case 3: ((CheckBox) vContainer.findViewById(R.id.act_chk_day_3)).setChecked(true); break; - case 4: ((CheckBox) vContainer.findViewById(R.id.act_chk_day_4)).setChecked(true); break; - case 5: ((CheckBox) vContainer.findViewById(R.id.act_chk_day_5)).setChecked(true); break; - case 6: ((CheckBox) vContainer.findViewById(R.id.act_chk_day_6)).setChecked(true); break; - case 7: ((CheckBox) vContainer.findViewById(R.id.act_chk_day_7)).setChecked(true); break; - } - } - - ((RadioButton)actTypeRdGroup.getChildAt( currentAct.getType().toInt())).setChecked(true); - - } - void setDetails(){ - - - if(currentAct.getSvrNumber()==0 || currentAct.getUserId()<=0){ - currentAct.setUserId(activity.app.user.getUserbean().getId()); - currentAct.setUserName(activity.app.user.getUserbean().getUserName()); - act_creator.setText(currentAct.getUserName()); - } -// - currentAct.setName(act_edit_title.getText().toString()); - currentAct.setDescription(act_edit_description.getText().toString()); -// currentAct.setRateLevel(act_levlRatingBar.getNumStars()); - currentAct.setRateLevel(act_levlRatingBar.getRating()); - currentAct.setStartPlace(((EditText) vContainer.findViewById(R.id.act_edit_startGeo)).getText().toString()); - currentAct.setEndPlace(((EditText) vContainer.findViewById(R.id.act_edit_endGeo)).getText().toString()); - - if(!TextUtils.isEmpty(edit_act_distance.getText())){ - try{ - currentAct.setDistance(Float.valueOf(edit_act_distance.getText().toString().trim())); - }catch(NumberFormatException e){ - - } - } - - - if(!TextUtils.isEmpty(edit_act_distance.getText())){ - try{ - currentAct.setAvSpeed(Float.valueOf(edit_act_speed.getText().toString().trim())); - }catch(NumberFormatException e){ - - } - - } - - - currentAct.setRepeatable(isRepeatAct); - currentAct.getDays().clear(); - for(int i=1;i<8;i++){ - switch (i){ - case 1: if(((CheckBox) vContainer.findViewById(R.id.act_chk_day_1)).isChecked()) currentAct.getDays().add(i); break; - case 2: if(((CheckBox) vContainer.findViewById(R.id.act_chk_day_2)).isChecked()) currentAct.getDays().add(i); break; - case 3: if(((CheckBox) vContainer.findViewById(R.id.act_chk_day_3)).isChecked()) currentAct.getDays().add(i); break; - case 4: if(((CheckBox) vContainer.findViewById(R.id.act_chk_day_4)).isChecked()) currentAct.getDays().add(i); break; - case 5: if(((CheckBox) vContainer.findViewById(R.id.act_chk_day_5)).isChecked()) currentAct.getDays().add(i); break; - case 6: if(((CheckBox) vContainer.findViewById(R.id.act_chk_day_6)).isChecked()) currentAct.getDays().add(i); break; - case 7: if(((CheckBox) vContainer.findViewById(R.id.act_chk_day_7)).isChecked()) currentAct.getDays().add(i); break; - } - } - - } - - - - - - - void setFindResult(){ - - if(canEdit() && activity.geoAddress!=null &&activity.geoAddress.getLat()>0 && activity.addressTextId!=0){ - -// int txtid=activity.addressTextId == R.id.ll_start_place?R.id.act_edit_startGeo -// :activity.addressTextId == R.id.ll_end_place?R.id.act_edit_endGeo:-1; - - - int txtid=activity.addressTextId == R.id.act_txt_startGeo_picker?R.id.act_edit_startGeo - :activity.addressTextId == R.id.act_txt_endGeo_picker?R.id.act_edit_endGeo:-1; - - - if(txtid==-1)return; - - if(activity.geoAddress==null || TextUtils.isEmpty(activity.geoAddress.getCity()) ||TextUtils.isEmpty(activity.geoAddress.getCity().replace("null", "")))return; - - EditText text =((EditText)vContainer.findViewById(txtid)); - - if(text!=null){ - text.setText(activity.geoAddress.getName()); - - if(txtid ==R.id.act_edit_startGeo){ - currentAct.setStartGeo(new GEO_bean(activity.geoAddress )); - currentAct.getStartGeo().setSharedAddressUrl(activity.sharedAddressUrl ); - currentAct.setStartAddressUrl(activity.sharedAddressUrl); - currentAct.setStartAddress(activity.geoAddress.getAddress()); - currentAct.setStartPlace(activity.geoAddress.getName()); - currentAct.setLat(activity.geoAddress.getLat()); - currentAct.setLon(activity.geoAddress.getLon()); - urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,activity.sharedAddressUrl ); - }else - if(txtid ==R.id.act_edit_endGeo){ - currentAct.setEndGeo(new GEO_bean(activity.geoAddress )); - currentAct.getEndGeo().setSharedAddressUrl(activity.sharedAddressUrl ); - currentAct.setEndAddressUrl(activity.sharedAddressUrl); - currentAct.setEndAddress(activity.geoAddress.getAddress()); - currentAct.setEndPlace(activity.geoAddress.getName()); - urlFormat(R.id.act_txt_endGeo_map,R.id.act_txt_endGeo_share,currentAct.getEndAddressUrl()); - - } - - activity.geoAddress=null; - activity.addressTextId=0; - } - } - } - - boolean canEdit(){ - return currentAct.getSvrNumber()==0 - || currentAct==null - || currentAct.getSvrNumber()==0 - || currentAct.getUserId() ==activity.app.user.getUserbean().getId() - ||this.isAdmin(); - } - - //show input as editable or not - void validInputs(){ - - boolean canEdit = canEdit(); - - this.imgTopBanner.setEnabled(canEdit); - -// canEdit=false; - int visible=canEdit?View.VISIBLE:View.GONE; - checkSvrObjUser(currentAct.getSvrNumber(),activity.app.user.getUserbean().getId()); - - txtStartGeoPicker.setVisibility(visible); - txtEndGeoPicker.setVisibility(visible); - - -// btn_removeRoadbook.setEnabled(canEdit); -// btn_saveAct.setVisibility(visible); - btn_submitAct.setVisibility(visible); - btn_submitAct.setEnabled(canEdit); - btn_saveAct.setEnabled(currentAct.getSvrNumber()==0); - btn_saveAct.setVisibility(currentAct.getSvrNumber()==0?View.VISIBLE:View.GONE); - btn_submitAct.setText(currentAct.getSvrNumber()>0?R.string.act_update:R.string.act_submit); - - - act_edit_title.setEnabled(canEdit); - - -// txtStartGeoPicker.setClickable(canEdit); -// txtEndGeoPicker.setClickable(canEdit); - - edit_act_endGeo.setEnabled(canEdit); - edit_act_startGeo.setEnabled(canEdit); - - - - - act_edit_description.setEnabled(canEdit); - act_levlRatingBar.setEnabled(canEdit); - - - edit_act_startTime.setEnabled(canEdit); - edit_act_endTime.setEnabled(canEdit); - - edit_act_distance.setEnabled(canEdit); - edit_act_speed.setEnabled(canEdit); - - this.repeatRdGroup.setEnabled(canEdit); - - for (int i = 0; i < repeatRdGroup.getChildCount(); i++) { - repeatRdGroup.getChildAt(i).setEnabled(canEdit); - } - - for (int i = 0; i < actTypeRdGroup.getChildCount(); i++) { - actTypeRdGroup.getChildAt(i).setEnabled(canEdit); - } -// btn_actJoin.setEnabled(currentAct.getSvrNumber()>0); -// btn_actJoin.setText(currentAct.getSvrNumber()>0?R.string.act_join:R.string.act_left); - - boolean canJoin = currentAct.getSvrNumber()>0 ;// && currentAct.getUserId() !=activity.app.user.getUserbean().getId(); - visible=canJoin ?View.VISIBLE:View.GONE; - - btn_actJoin.setVisibility(visible); - btnShare.setVisibility(visible); - -// btn_refresh.setEnabled(currentAct.getSvrNumber()>0); -// btn_refresh.setVisibility(currentAct.getSvrNumber()>0?View.VISIBLE:View.GONE); - - } - - - void urlFormat(int viewId ,int shareId,String url){ -// act_txt_endGeo_map - TextView txtmap =(TextView) vContainer.findViewById(viewId); - - TextView txtshare =(TextView) vContainer.findViewById(shareId); - - txtshare.setVisibility(View.GONE); - - if(TextUtils.isEmpty(url) || url.equalsIgnoreCase("null")) return; -// String html = editText.getText().toString() ; - String aformat= "\n地图"; - String html =String.format(aformat, url);//这里即使不加协议好HTTP;也能自动被系统识别出来。 - CharSequence charSequence = Html.fromHtml(html); - txtmap.setText(charSequence); -// txtview.setAutoLinkMask(Linkify.MAP_ADDRESSES); - txtmap.setMovementMethod(LinkMovementMethod.getInstance()); - txtshare.setVisibility(View.VISIBLE); - - } - - boolean validDate(){ - long startDate=currentAct.getStartDate(); - long endDate =currentAct.getEndDate(); - - - if(currentAct.isRepeatable() ){ - if(startDate==0){ - currentAct.setStartDate(System.currentTimeMillis()); - } - } - - boolean isPass =currentAct.isRepeatable() && currentAct.getDays().size()>0 || - (currentAct.getSvrNumber()>0 ||startDate>System.currentTimeMillis()) && startDate0){ - ((EditText) vContainer.findViewById(R.id.act_edit_starttime)).setText(""); - ((EditText) vContainer.findViewById(R.id.act_edit_starttime)).setHint(Utils.getFormatedTime(startDate)); - ((EditText) vContainer.findViewById(R.id.act_edit_starttime)).setHintTextColor(Color.RED); - } - -// ((EditText) vContainer.findViewById(R.id.act_edit_starttime)).setTextColor(Color.RED); - showNotes("请输入正确的活动开始时间"); - - }else if( startDate >= endDate){ - ((EditText) vContainer.findViewById(R.id.act_edit_endtime)).setText(""); - ((EditText) vContainer.findViewById(R.id.act_edit_endtime)).setHint(Utils.getFormatedTime(endDate)); - ((EditText) vContainer.findViewById(R.id.act_edit_endtime)).setHintTextColor(Color.RED); -// ((EditText) vContainer.findViewById(R.id.act_edit_endtime)).setTextColor(Color.RED); - - showNotes("请输入正确的活动结束时间"); - } - } - } - return isPass; - } - - @Override - void submitSvrObj(){ - - setDetails(); - - - - if(validSubmit()){ - - saveSvrObj(); - - // QLog.getLogger().d(dTAG, "uploading activity is:" +Utils.getGsonString(currentAct)); - - postSvr(); - - } - - } - - void postSvr() { - this.postJsonWS(Utils.getGsonString(currentAct),RestMethods.ACT_P_IMPORT/* "mb/activity/"*/); - } - - - boolean validSubmit(){ - if(currentAct.getUserId() <=0){ - activity.showLogin(); - return false; - } - - - if(TextUtils.isEmpty(currentAct.getName() .trim())){ - -// act_edit_title.setBackgroundColor(Color.YELLOW); - act_edit_title.setHintTextColor(Color.RED); - act_edit_title.setSelected(true); - this.showNotes("请输入活动标题"); - return false; - } - if(TextUtils.isEmpty(currentAct.getStartPlace() )){ - -// act_edit_title.setBackgroundColor(Color.YELLOW); - ((EditText) vContainer.findViewById(R.id.act_edit_startGeo)).setHintTextColor(Color.RED); - this.showNotes("请设置活动起始地点"); - return false; - } - - if(TextUtils.isEmpty(currentAct.getDescription() .trim())){ - -// act_edit_title.setBackgroundColor(Color.YELLOW); - act_edit_description.setHintTextColor(Color.RED); - this.showNotes("请输入活动须知信息"); - return false; - } - - - - - return !TextUtils.isEmpty(currentAct.getName().toString().trim()) - && !TextUtils.isEmpty(currentAct.getStartPlace().toString().trim()) - && !TextUtils.isEmpty(currentAct.getDescription().toString().trim()) - && validDate(); - - - - } - - @Override - void saveSvrObj(){ - setDetails(); - writeLocalObjCache(); - - } - - void writeLocalObjCache(){ - writeActivitiesCache(currentAct); - showNotes("已保存草稿",false); - } - - void loadLocalActivity(){ - try { - currentAct = getActFromWebCache(0,0); - } catch (JsonSyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - - - @Override - void joinSvrObj(){ - int userId=activity.app.user.getUserbean().getId(); - int actId =currentAct.getSvrNumber(); - String userName=activity.app.user.getUserbean().getUserName(); - String rest =RestMethods.ACT_P_DEL_MEMBER; - if(btn_actJoin.getText().toString().equalsIgnoreCase(getResources().getString(R.string.act_join))){ - rest=RestMethods.ACT_P_ADD_MEMBER; - } - - doMemberOperation(actId,currentAct.getName(),currentAct.getUserId(),userId, userName,rest); - - - - } - - @Override - void removeUser(int userId){ - doMemberOperation(currentAct.getSvrNumber(),currentAct.getName(),currentAct.getUserId(),userId, activity.app.user.getUserbean().getUserName(),RestMethods.ACT_P_DEL_MEMBER); - } - - /*void doMemberOperation(int svrId, String svrName,int ownerId,int userId,String userName,final String restMethod){ - - if(userId<=0||svrId<=0){ - return; - } - - final JSONObject json = new JSONObject(); - try { - json.put("svrId", String.valueOf(svrId)); - json.put("userId", String.valueOf( userId)); - json.put("ownerId", String.valueOf( ownerId)); - json.put("userName", userName); - json.put("svrName", svrName); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - if(restMethod.equalsIgnoreCase(RestMethods.ACT_P_DEL_MEMBER) - || restMethod.equalsIgnoreCase(RestMethods.GRP_P_DEL_MEMBER)) { - AlertDialog.Builder builder = new Builder(activity); - builder.setMessage("确认继续此退出操作?"); - builder.setTitle("提示"); - builder.setCancelable(false); - builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - - postJsonWS(json.toString(), restMethod); - - - } - }); - builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - }); - builder.create().show(); - }else - postJsonWS(json.toString(), restMethod); - - - - - - - *//*if(btn_actJoin.getText().toString().equalsIgnoreCase(getResources().getString(R.string.act_join))) - postJsonWS(json.toString(), RestMethods.ACT_P_ADD_MEMBER"mb/activity/addmember"); - else - postJsonWS(json.toString(),RestMethods.ACT_P_DEL_MEMBER "mb/activity/delmember");*//* - - - }*/ - - @Override - void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{ - pirntCookies(); - if(jsonObject==null)return; - - if(method.equalsIgnoreCase(RestMethods.ACT_P_ADD_MEMBER) - || method.equalsIgnoreCase(RestMethods.GRP_P_ADD_MEMBER)){ //joinAct() -// if(Boolean.valueOf(jsonObject.getString(QiYouConstant.SIMPLE_KEY))){ - if(jsonObject!=null && jsonObject.has(QiYouConstant.SIMPLE_KEY) ){ - //success -// this.showNotes(msg/*"您已加入"*/); - OperationType optype = OperationType.NORMAL; - optype= OperationType.valueOf(Integer.valueOf(jsonObject.getString(QiYouConstant.SIMPLE_KEY))); - - - if(optype == OperationType.DONE) { - btn_actJoin.setText(R.string.act_left); -// lastMemberQueryPara=""; -// doUserQuery(); - }else if(optype == OperationType.INPROGRESS){ - btn_actJoin.setText(R.string.act_joinInprogress); - btn_actJoin.setEnabled(false); - }else if(optype == OperationType.NORMAL){ - - } - - shareObj(); - - }else{ - //failed -// this.showNotes(msg/*"加入失败"*/); - } - - this.showNotes(msg/*"您已加入"*/); - - return; - } - - else if(method.equalsIgnoreCase(RestMethods.ACT_P_DEL_MEMBER) - ||method.equalsIgnoreCase(RestMethods.GRP_P_DEL_MEMBER) - ){ //LEAVE activity,group - if(Boolean.valueOf(jsonObject.getString(QiYouConstant.SIMPLE_KEY))){ - //success - this.showNotes(msg/*"退出成功"*/); - if(btn_actJoin!=null) { - btn_actJoin.setText(R.string.act_join); - } -// lastMemberQueryPara=""; -// doUserQuery(); - - }else{ - //failed - this.showNotes(msg/*"退出失败"*/); - } - - return; - } - - else if(method.equalsIgnoreCase(RestMethods.ACT_P_IMPORT)){ //sumbmit act - - - int svrNo= jsonObject.getInt("svrNumber"); - if(svrNo<=0)return; - - //check and upload image - - // activity.app.user.getUserbean().setScore(jsonObject.getInt("userScore")); - // activity.app.updateUserPref(); - currentAct.setLastupdated(jsonObject.getInt("lastupdated")); -// svrNumber =currentAct.getSvrNumber(); - - if(currentAct.getSvrNumber()!=svrNo){ - - currentAct.setSvrNumber(svrNo); - - doMemberOperation(svrNo,currentAct.getName(),currentAct.getUserId(),activity.app.user.getUserbean().getId(),activity.app.user.getUserbean().getUserName(), RestMethods.ACT_P_ADD_MEMBER); - - writeActivitiesCache(currentAct); - if(!TextUtils.isEmpty(currentAct.getAlbum())){ - setMD(currentAct.getAlbum(),0,null,null); - } - showSubmitedObj(svrNo); - - }else{ - showNotes(msg/*"更新成功!"*/); - } - - - - - return; - - - - }else if(method.equalsIgnoreCase(RestMethods.ACT_P_UPDATE_ROODBOOK)){ - - if(Boolean.valueOf(jsonObject.getString(QiYouConstant.SIMPLE_KEY))){ - //success - this.showNotes(msg/*"路书更新成功"*/); - - - }else{ - //failed - this.showNotes(msg/*"路书更新失败"*/); - } - return; - } - - } - - @Override - void shareObj(){ - String shareTitle = super.BBSsubCateName ; - String shareType = this.currentAct!=null?"队伍":"活动"; - String shareContent = "欢迎加入"+shareType+",约吗?"; -// Bitmap b = this.imgTopBanner.getDrawingCache(); -// Bitmap b = ((BitmapDrawable)imgTopBanner.getDrawable()).getBitmap(); - Bitmap b = Utils.getBitmapFromView(imgTopBanner); -// String imgurl = currentAct !=null ? currentAct.getAlbum() : - String type = BBSCate.values()[super.BBScate].toString(); - String url = String.format("%slist?%s=%s", QiYouConstant.BASE_URL,type.toLowerCase(),super.BBSSubcate); - MobclickAgent.onEvent(activity,"shareObj-" + type); - QLog.getLogger().d(dTAG, "url is:" + url +", sharecontent is "+shareContent +",title is "+ title); - activity.doShare(shareTitle, shareContent, "", b , url); - - - } - - - void checkSvrObjUserResult( JSONObject response) throws JSONException { - - if(response!=null && response.has(QiYouConstant.SIMPLE_KEY) ){ - OperationType optype = OperationType.NORMAL; - optype= OperationType.valueOf(Integer.valueOf(response.getString(QiYouConstant.SIMPLE_KEY))); - - /* try{ - optype= OperationType.valueOf(Integer.valueOf(response.getString(QiYouConstant.SIMPLE_KEY))); - }catch(IllegalArgumentException e){ - - }*/ - -// boolean isInTheAct=Boolean.valueOf(response.getString(QiYouConstant.SIMPLE_KEY)); -// btn_actJoin.setText(isInTheAct?R.string.act_left:R.string.act_join); - int res=optype==OperationType.DONE?R.string.act_left //has been in - :optype==OperationType.INPROGRESS?R.string.act_joinInprogress //waiting for approve - : R.string.act_join; - btn_actJoin.setEnabled(optype!=OperationType.INPROGRESS); - btn_actJoin.setText(res); - } - } - - - void checkSvrObjUser(int actId,int userId){ - if(actId<=0 || userId<=0){ - return; - } - RequestParams params = new RequestParams(); - params.add("actId", String.valueOf( actId)); - params.add("userId", String.valueOf( userId)); - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - getJsonWs(params,RestMethods.ACT_G_IS_MEMBER_HAS_ACT /*"mb/activity/isMemberHasAct"*/,true); - } - - - - @Override - void processGetJsonObject(String method,JSONObject jsonObject,String msg) throws JSONException,NullPointerException, NoWebObjectException { - super.processGetJsonObject(method, jsonObject, msg); - - if(method.equalsIgnoreCase(RestMethods.ACT_G_IS_MEMBER_HAS_ACT)){ - checkSvrObjUserResult(jsonObject); - - }else if(method.equalsIgnoreCase(RestMethods.GRP_G_IS_MEMBER_HAS_GRP)){ - checkSvrObjUserResult(jsonObject); - } - - } - - - void showSubmitedObj(int svrNo) { - act_svrNo.setText(svrNo+""); - showNotes("上传成功!云编号:"+svrNo); - - - activity.updateActionBarTitle(title); - validInputs(); - getDetails(); - mapViewOnActivityCreated(); - shareObj(); - - } - - -// @Override -// void showActivity(Activity_bean act) { -// this.currentAct=act; -// getDetails(); -// } - - - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - - super.onActivityResult(requestCode, resultCode, data); - /*if(requestCode ==SELECT_PIC_KITKAT ||requestCode ==SELECT_PIC) - if (resultCode == Activity.RESULT_OK) { -// picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH); -// Log.i(TAG, "最终选择的图片="+picPath); -// Bitmap bm = BitmapFactory.decodeFile(picPath); -// imageView.setImageBitmap(bm); - - Uri photoUri = data.getData(); - String path= Utils.getPath(activity,photoUri); - setMD(path,System.currentTimeMillis(),mdWp,mediaType.PIC); - - }*/ - } - - - @Override - protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){ - - - - if (currentAct.getSvrNumber() > 0){ - Media md = new Media(); - md.setTrackSvrNumber(currentAct.getSvrNumber()); - md.setUri(picName); - md.setType(mediaType.PIC); - md.setSvrUri(currentAct.getAlbum()); - try { - super.postBinaryWS(md, RestMethods.ACT_P_UPLOAD_ALBUM); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - }else { - IL.DisplayImage(picName,imgTopBanner); - currentAct.setAlbum(picName); - } - - - } - - @Override - void uploadMediasOnReturn(JSONObject jo) { - this.showNotes("图片上传成功!"); - if (jo!=null){ - try { - if (currentAct!=null){ - currentAct.setAlbum(jo.getString("svrUri")); - } - - IL.DisplayImage(QiYouConstant.BASE_MD_URL + jo.getString("svrUri"),imgTopBanner); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - -// @Override -// void processTabQuery(){ -// } - - @Override - public void onResume() { -// activity.app.currentActiveFragment =TAG; - super.onResume(); - activity.updateActionBarTitle(title); - setFindResult(); - validInputs(); - - } - @Override - void generateQcode(){ - if (currentAct.getSvrNumber() > 0){ - - - - JSONObject json = new JSONObject(); - try { - json.put(QiYouConstant.EXTRA_KEY_SVRID, String.valueOf(currentAct.getSvrNumber())); - json.put("ownerId", String.valueOf( currentAct.getUserId())); - json.put("svrName", currentAct.getName()); - json.put(QiYouConstant.EXTRA_KEY_RESTMETHOD,RestMethods.ACT_P_ADD_MEMBER); - json.put(QiYouConstant.EXTRA_KEY_QCODEDESC, currentAct.getName()); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - activity.showQcode(json.toString()); - } - } - @Override - void shareEndUrl(int viewId){ - - Intent sendIntent = new Intent(); - sendIntent.setAction(Intent.ACTION_SEND); - String url =viewId==R.id.act_txt_startGeo_share? currentAct.getStartAddressUrl() - : currentAct.getEndAddressUrl(); - String title =viewId==R.id.act_txt_startGeo_share? currentAct.getStartPlace() - : currentAct.getEndPlace(); - title =this.currentAct.getName() +"【活动地址】"+title; - if(viewId==R.id.act_txt_startGeo_share) - sendIntent.putExtra(Intent.EXTRA_TEXT,title+ url); - sendIntent.setType("text/plain"); - startActivity(Intent.createChooser(sendIntent,title )); - - } - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ActivityHome.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ActivityHome.java deleted file mode 100644 index 7ed8067..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ActivityHome.java +++ /dev/null @@ -1,656 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.util.ArrayList; -import java.util.Map; - -import org.json.JSONArray; - -import android.content.Intent; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnTouchListener; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.RadioGroup; -import android.widget.TextView; - -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.enums.WebQueryCate; -import com.qiyou.mb.android.utils.server.RestMethods; - -public class ActivityHome extends ActivityDetail { - - @Override - public String getCurrentTag() { - // TODO Auto-generated method stub - setFTag(); - return TAG; - } - - @Override - public void setFTag() { - // TODO Auto-generated method stub - TAG = "com.qiyou.ActivityHome"; - // FirstTabTextColor= getResources().getColorStateList(R.color.red); - // FirstTabBackGround=R.drawable.icon_star; - } - - public static String getFTag() { - return "com.qiyou.ActivityHome"; - } - - public static ActivityHome newInstance(Activity_bean activity/* - * int - * inType,int - * actId - */) { - - ActivityHome f = new ActivityHome(); - f.currentAct = activity; - /* - * Bundle args = new Bundle(); args.putInt(QiYouConstant.EXTRA_KEY_ID, - * actId); f.setArguments(args); - */ - return f; - } - - public static ActivityHome newInstance() { - - ActivityHome f = new ActivityHome(); - - return f; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - if (currentAct == null) { - - currentAct = new Activity_bean(); - - } - // svrNumber =currentAct.getSvrNumber(); - - title = currentAct.getSvrNumber() > 0 ? -// getResources().getString(R.string.bottom_web)+ "》"+ - getResources().getString(R.string.frg_actdetail) - + "|" - + currentAct.getName() : getResources().getString( - R.string.frg_actnew); - - currentLayout = R.layout.activity_home; - vContainer = inflater.inflate(currentLayout, container, false); - - webTab = "活动"; - initialViews(); - // initialLLViews(); - // initialMapview(); - - return vContainer; - } - - private LinearLayout roadBookbar; - private TextView actTitle, actLevel, actTime, actAvs, actDist; - protected Button btnHeadDetail; - - @Override - protected void initialViews() { - // android:id="@+id/actList_level" android:id="@+id/actList_avs" - // android:id="@+id/actList_sportTime" android:id="@+id/" - // android:id="@+id/actList_svrNo" android:id="@+id/actList_name" - txtNote = (TextView) vContainer.findViewById(R.id.txtNotice); - btnHeadDetail = (Button) vContainer.findViewById(R.id.btnHeadDetail); - btnHeadDetail.setOnClickListener(super.ButtonOnClickListener); - - initialExtraViews(); - -// imgWebPlus = (ImageView) vContainer.findViewById(R.id.img_webAdd); -// imgWebPlus.setOnClickListener(ButtonOnClickListener); -// imgWebPlus.setVisibility(View.GONE); - initialTabhost(); - - bbsbar = (LinearLayout) vContainer.findViewById(R.id.bbsBar); - - liveMap = (LinearLayout) vContainer.findViewById(R.id.liveMap); - liveList = (LinearLayout) vContainer.findViewById(R.id.ll_liveList); - liveList.setVisibility(View.VISIBLE); - lvWeb = (ListView) vContainer.findViewById(R.id.tr_listWeb);// .act_member_list); - lvWeb.setOnItemClickListener(itemListener); - // lvWeb.setOnTouchListener(new OnTouchListener() { - // @Override - // public boolean onTouch(View v, MotionEvent event) { - // Utils.hideSoftKeyboard(activity); - // return false; - // } - // }); - initialMapview(); - initialLoadingMore(); - - } - - @Override - void hideNotes(){} - - // initial act summary,roadbookbar,etc,need to be overrided - @Override - void initialExtraViews() { - - act_svrNo = (TextView) vContainer.findViewById(R.id.actList_svrNo); - - // act_roadbook = (EditText) - // vContainer.findViewById(R.id.act_edit_roadbook); - actTitle = (TextView) vContainer.findViewById(R.id.actList_name); - actLevel = (TextView) vContainer.findViewById(R.id.actList_level); - ; - actAvs = (TextView) vContainer.findViewById(R.id.actList_avs); - ; - actTime = (TextView) vContainer.findViewById(R.id.actList_sportTime); - ; - actDist = (TextView) vContainer.findViewById(R.id.actList_dist); - ; - - // noRec = (TextView) vContainer.findViewById(R.id.trakList_tv_norec); - - - roadBookbar = ((LinearLayout) vContainer.findViewById(R.id.roadBookbar)); - initialRoadBookViews(); - } - - private void initialRoadBookViews() { - boolean canEdit = canEdit(); - - btn_loadRoadbook = (Button) vContainer - .findViewById(R.id.act_btn_loadRoadbook); - btn_loadRoadbook.setOnClickListener(ButtonOnClickListener); - - lvWeb = (ListView) vContainer.findViewById(R.id.tr_listWeb); - // lvWeb =(SwipeListView)vContainer.findViewById(R.id.tr_listWeb); - - act_roadbook = (EditText) vContainer - .findViewById(R.id.act_edit_roadbook); - - roadbookRdGroup = (RadioGroup) vContainer - .findViewById(R.id.act_rdGroup_rooadbook); - if (roadbookRdGroup != null) - roadbookRdGroup.setOnCheckedChangeListener(rdgChanged); - - btn_loadRoadbook.setEnabled(canEdit); - act_roadbook.setEnabled(canEdit); - this.roadbookRdGroup.setEnabled(canEdit); - for (int i = 0; i < roadbookRdGroup.getChildCount(); i++) { - roadbookRdGroup.getChildAt(i).setEnabled(canEdit); - } - - - } - - @Override - void showObjDetail() { - activity.showActvity(currentAct); - } - - @Override - void showWebObject() { - showDetail(currentAct.getSvrNumber()); - } - - private void showDetail(int actid) { - if (actid > 0 && currentAct != null - && actid == currentAct.getSvrNumber()) { - - if(currentAct.getRoadbooks().size()>0){ -// doWebTrackQuery();//query and .show roadbook list - } - - getDetails(); - } - - } - - @Override - void addTabs() { - tabBbs = tabhost.newTabSpec(bbsTab); - tabBbs.setIndicator(bbsTab); - tabBbs.setContent(tabResourceId); - - tabhost.addTab(tabBbs); - tabhost.addTab(tabRoadbook); - tabhost.addTab(tabUser); - tabhost.addTab(tabTrack); - tabhost.addTab(tabLive); - - } - - @Override - void refresh() { - - // if(currentTab==0){ - // requestActFromWeb( currentAct.getSvrNumber()); - // - // }else - if (isWebTrackQuery) { // show road book - - this.initialWebQuery(); - } else if (isActivityQuery) { - - this.initialWebQuery(); - - } else if (isLiveQuery) { - showLive(); - - } else if (isMemberQuery) { - this.initialWebQuery(); - - } else if (this.isShareQuery) { - if (currentAct == null || currentAct.getSvrNumber() == 0) - return; - this.initialWebQuery(); - } - - } - - @Override - void getDetails() { - - this.BBScate = BBSCate.ACT.toInt(); // act - this.BBSSubcate = currentAct.getSvrNumber(); - this.BBSsubCateName = currentAct.getName(); - BBSSubcateOwner = currentAct.getUserId(); - - actTitle.setText(currentAct.getName()); - actLevel.setText(String.format("%.0f", currentAct.getRateLevel())); - actAvs.setText(String.format("%.0f", currentAct.getAvSpeed())); - actDist.setText(String.format("%.0f", currentAct.getDistance())); - actTime.setText(currentAct.getAvSpeed() > 0 ? String.format("%.0f", - currentAct.getDistance() / currentAct.getAvSpeed()) : "--"); -// act_svrNo.setText(currentAct.getSvrNumber() + ""); - act_svrNo.setText(String.format("距你 %s , %s",Utils.getDistanceRange(/*ab.getDistrange()*/0, currentAct.getLat(), currentAct.getLon()) - , getTimeLeft(currentAct))); - - } - - @Override - public void initialWebQuery() { - super.initialWebQuery(); - if (this.isShareQuery) { - lastActShareQueryPara = ""; - - doShareQuery(); - } - } - - @Override - void processTabQuery() { - super.processTabQuery(); - - if (isShareQuery) { - - if (shareTrackData == null) - doShareQuery(); - else - showWebTrackListData(shareTrackData); - if (shareTrackData != null) - showNoRecText(shareTrackData.size() == 0); - // } - } else if (isLiveQuery) { - // ((LinearLayout)vContainer.findViewById(R.id.tab_map)).setVisibility( - // View.VISIBLE ); - - liveLv.setVisibility(View.VISIBLE); - showLive(); - - } - - } - - @Override - void switchTabOptions(int queryType) { - getQueryType(queryType); - lvWeb.setVisibility(View.GONE); - bbsbar.setVisibility(isBBSQuery ? View.VISIBLE : View.GONE); -// imgWebPlus.setVisibility(isBBSQuery ? View.VISIBLE : View.GONE); - liveMap.setVisibility(isLiveQuery ? View.VISIBLE : View.GONE); - setNote(); - } - - void getQueryType(int queryType) { - isBBSQuery = queryType == 0; - isWebTrackQuery = queryType == 1; - isMemberQuery = queryType == 2; - isShareQuery = queryType == 3; - isLiveQuery = queryType == 4; -// currentActTab = currentTab; - roadBookbar.setVisibility(isWebTrackQuery ? View.VISIBLE : View.GONE); - } - - void doWebQuery() { // do roadbook query - // initialWebListView(R.id.tr_listWeb); - - if (currentAct != null && currentAct.getRoadbooks().size() > 0 - && trackData == null) - - doWebTrackQuery(); - else if (trackData == null) { - trackData = new ArrayList>(); - showWebTrackListData(trackData); - } - - /* - * if(trackData!=null) showNoRecText(trackData.size()==0); - */ - - } - - // draw the roadbook - @Override - void showWebTrack(Track track) { - if (isWebTrackQuery) { // show roadbook detail - super.showWebTrack(track); - return; - } else if (isLiveQuery) { // draw gpx on map - drawActNaviRoadbook(track); - return; - } else if (isShareQuery) { // draw gpx on map - super.showWebTrack(track); - return; - } - } - - @Override - void showLive() { - doLiveQuery(); - - // show gpx track - if (currentAct != null && currentAct.getRoadbooks().size() > 0) { - Track tr = null; - try { - tr = activity.app.getTrackCache().get( - Integer.valueOf(currentAct.getRoadbooks().get(0))); - } catch (Exception e) { - Utils.logStackTrace(e, dTAG); - } - if (tr == null) { - - if (trackData == null) { - doWebQuery(); - } else { - - tr = getWebTrackDetail(0); - } - } - drawActNaviRoadbook(tr); - - } - - } - - void drawActNaviRoadbook(Track gpxTrack) { - if (gpxTrack != null) { - activity.app.getTrackCache().put( - gpxTrack.getTrackBean().getSvrNumber(), gpxTrack); - if (gpxDrawd == null) { - gpxDrawd = new ArrayList(); - } - drawGpx(); - } - } - - void showTabButtons(int tabIndex) { - - /* - * btn_saveAct.setVisibility(View.GONE); - * btn_submitAct.setVisibility(View.GONE); - * - * btn_actJoin.setVisibility(View.GONE); - * - * - * switch (tabIndex){ case 0: { - * btn_saveAct.setVisibility(btn_saveAct.isEnabled - * ()?View.VISIBLE:View.GONE); - * btn_submitAct.setVisibility(btn_submitAct. - * isEnabled()?View.VISIBLE:View.GONE ); - * btn_actJoin.setVisibility(btn_actJoin - * .isEnabled()?View.VISIBLE:View.GONE ); break; } case 1:{ // - * btn_saveAct.setVisibility(View.VISIBLE); // - * btn_submitAct.setVisibility(View.VISIBLE); // - * btn_actJoin.setVisibility(View.VISIBLE); break; } case 2:{ - * btn_actJoin - * .setVisibility(btn_actJoin.isEnabled()?View.VISIBLE:View.GONE); - * break; } case 3:{ break; } case 4: { break; } } - */ - } - - @Override - public void setFindResult() { - - } - - @Override - public void validInputs() { - - } - - @Override - void processTrackJsonArray(JSONArray jsonArrary) { - if (isShareQuery) { - // shareTrackData = getWebTrackList( jsonArrary); - shareTrackData = getListData(shareTrackData, - getWebTrackList(jsonArrary)); - showNoRecText(shareTrackData.size() == 0); - showWebTrackListData(shareTrackData); - } else/* if(isWebTrackQuery) */{ - // trackData = getWebTrackList( jsonArrary); - trackData = getListData(trackData, getWebTrackList(jsonArrary)); - showNoRecText(trackData.size() == 0); - if (!isLiveQuery) { - showWebTrackListData(trackData); - - }else{ - showLive(); - } - - } - - } - - void doShareQuery() { - Utils.hideSoftKeyboard(activity); - // noRec.setVisibility(View.GONE); - this.isShareQuery = true; - // lvWeb.setVisibility(View.VISIBLE); - // lv.setVisibility(View.GONE); - // QLog.getLogger().d(dTAG, TAG+"------begin share query--------- "); - - // getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo); - // lastWebQueryPara - // QLog.getLogger().d(dTAG, - // String.format("firstLoad ?%s,lastActShareQueryPara :%s",firstLoad, - // lastActShareQueryPara)); - if (this.firstLoad && !TextUtils.isEmpty(lastActShareQueryPara)) { - return; - } - RequestParams param = buildShareQueryParames(); - if (param != null - && !lastActShareQueryPara.equalsIgnoreCase(param.toString())) { - - // QLog.getLogger().d(dTAG, lastActShareQueryPara); - // QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param, RestMethods.TRACK_G_LIST/* - * RestMethods. - * TRACK_G_FIND_BY_ACT_GRP - *//* "mb/track/list" */); - lastActShareQueryPara = param.toString(); - selectActShareItem = -1; - - } - - } - - RequestParams buildShareQueryParames() { - RequestParams params = super.buildTrackQueryParames(); - isShowPic = true; - - if (currentAct != null && currentAct.getSvrNumber() > 0) { - // QLog.getLogger().d(dTAG, TAG+" act id is : "+ - // currentAct.getSvrNumber()); - params.add("actId", String.valueOf(currentAct.getSvrNumber())); - } - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - RequestParams buildMemberQueryParames() { - - int actId = currentAct == null ? -1 : currentAct.getSvrNumber(); - - if (actId <= 0) { - return null; - } - - RequestParams params = new RequestParams();// super.buildMemberQueryParames(); - params.add("actId", String.valueOf(actId)); - /* - * // String svrNo= edSvrNo.getText().toString(); - * - * params.add("page", String.valueOf(memberPageNo)); - * params.add("pagesize", String.valueOf(pageSize)); - * //QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON - * - * // params.add("actid",String.valueOf(actId )); - */ - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - RequestParams buildLiveQueryParames() { - RequestParams params = new RequestParams(); - // final int GEO_CITY_TYPE=2; - - // if(currentAct==null) return null; - params.add("actId", String.valueOf(currentAct.getSvrNumber())); - params.add("from", String.valueOf(lastMaxLiveTime)); - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - RequestParams buildTrackQueryParames() { - - /* - * RequestParams params = new RequestParams(); // final int - * GEO_CITY_TYPE=2; isShowPic =true; if(currentAct==null - * ||currentAct.getRoadbooks().size()==0 )return null; - * params.add("svrNos", - * currentAct.getRoadbooks().toString().replace("[", "").replace("]", - * "")); params.add("page", String.valueOf(pageNo)); - * params.add("pagesize", String.valueOf(pageSize)); // - * params.add("type", String.valueOf(webTrackType)); - * params.add("showpic", String.valueOf(isShowPic)); - * params.add("swidth", - * String.valueOf(QiYouConstant.PV_INT_SCREEN_WIDTH)); - * params.add("sheight", - * String.valueOf(QiYouConstant.PV_INT_SCREEN_HEIGHT)); - * params.add("mytrack", String.valueOf(false)); - */ - - RequestParams params = null; - if (currentAct != null && currentAct.getRoadbooks().size() > 0) { - - params = super.buildTrackQueryParames(); - params.add("svrNos", - currentAct.getRoadbooks().toString().replace("[", "") - .replace("]", "")); - }else{ - super.showWebTrackListData(new ArrayList>() ); -// lvWeb.setVisibility(View.VISIBLE); - } - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - return params; - } - - @Override - void loadingMore() { - super.loadingMore(); - - /* - * if(isLastPage){ return; } - */ - if (isShareQuery) { - lastActShareQueryPara = ""; - pageNo++; - doShareQuery(); - } - - } - @Override - void setNote(){ - txtNote.setVisibility(View.VISIBLE); - String noteTxt =""; - - if (isBBSQuery){ - noteTxt = "欢迎来到" + super.BBSsubCateName + "的说说发表高见!"; - }else if(isWebTrackQuery){ - noteTxt = super.BBSsubCateName + " 相关路书"; - }else if(isMemberQuery){ - noteTxt = super.BBSsubCateName + "成员"; - }else if(isShareQuery){ - noteTxt = super.BBSsubCateName + "的运动分享"; - }else if(isLiveQuery){ - noteTxt = super.BBSsubCateName + "位置直播"; - }else if(isActivityQuery){ - noteTxt = super.BBSsubCateName + "的相关活动"; - }else if(super.isGroupQuery){ - noteTxt = super.BBSsubCateName + "的相关队伍"; - } - - if(!TextUtils.isEmpty(noteTxt)){ - txtNote.setText(noteTxt); - }else{ - txtNote.setVisibility(View.GONE); - } - - } - -// protected int currentActTab; - - // not to remember last selected tab. -/* @Override - protected void setSelectedTab() { - if (tabhost != null && tabhost.getCurrentTab() != currentTab) { - tabhost.setCurrentTab(currentTab); - } - } -*/ - - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - // int size = currentAct!=null && currentAct.getSvrNumber()>0?4:2; - maxTabIndex = 5; - MAPVIEW_INDEX = 5;// currentAct!=null && - // currentAct.getSvrNumber()>0?4:-1; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GpxDetail_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GpxDetail_fragment.java deleted file mode 100644 index 041ef2a..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GpxDetail_fragment.java +++ /dev/null @@ -1,583 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.JSONException; -import org.json.JSONObject; - -import android.os.Bundle; -import android.text.InputFilter; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnClickListener; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ListAdapter; -import android.widget.ListView; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.SimpleAdapter.ViewBinder; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Statics_bean; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.WorkingTrackType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; - -public class GpxDetail_fragment extends TrackDetail_fragment { - @Override - public void setFTag(){ - TAG="com.qiyou.GpxDetail_fragment"; - } - public static String getFTag(){ - return "com.qiyou.GpxDetail_fragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.GpxDetail_fragment"; - } - - - public GpxDetail_fragment() { - // TODO Auto-generated constructor stub - workingTrackType= WorkingTrackType.GPX; - } - - public static GpxDetail_fragment newInstance(int inType,int trackId,boolean isWebQuery) - { - - GpxDetail_fragment f = new GpxDetail_fragment(); - Bundle args = new Bundle(); -// args.putString(QiYouConstant.EXTRA_KEY_ID, trackId); -// args.putString(QiYouConstant.EXTRA_KEY_TYPE, inType); - args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId); - args.putInt(QiYouConstant.EXTRA_KEY_TYPE, inType); - args.putBoolean(QiYouConstant.EXTRA_KEY_WEB_REQUEST, isWebQuery); - f.setArguments(args); - return f; - } - - private TextView txt_creator; - private TextView txt_src; - private TextView txt_routeType; - int svrNumber; - private Button btn_edit; - private Button btnDelWebTrack; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); -// if(activity.app.currentTrack!=null)app.initialStatTrack(activity.app.currentTrack.getTrackBean().getType().toInt()); - QLog.getLogger().d(dTAG, TAG+" onCreate, app Current trackid is: "+ app.getCurrentTrack().getTrackBean().getTrackId()); - inflat_source =R.layout.gpx_detail_fragment; - } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - this.setWorkingTrack(); - if(mTrack!=null && mTrack.isLushu()) - inflat_source =R.layout.gpx_lushu_fragment; - vContainer= super. onCreateView( inflater, container, savedInstanceState); -// if(!isWebRequest){ -// rdGroup.setVisibility(View.GONE); -// } - txt_creator =(TextView)vContainer.findViewById(R.id.td_textView_creator); - txt_src =(TextView)vContainer.findViewById(R.id.td_textView_src); - - chk_showGpx=(CheckBox)vContainer.findViewById(R.id.chk_showGpxDetail); - btn_edit=(Button)vContainer.findViewById(R.id.rt_btn_edit); - btnDelWebTrack =(Button)vContainer.findViewById(R.id.td_btnDeleteTtrack); - btnDelWebTrack.setOnClickListener(ButtonOnClickListener); - - btn_edit.setOnClickListener( new OnClickListener() { - @Override - public void onClick(View view) { - if(trackId>0) - activity.showRoute(trackId); - } - } - ); - btn_edit.setVisibility(View.VISIBLE); - - - lv = (ListView) vContainer.findViewById(R.id.tent_list); - - btnImport = (Button) vContainer.findViewById(R.id.td_btnImport); - btnImport.setOnClickListener(ButtonOnClickListener); - - txt_routeType =(TextView)vContainer.findViewById(R.id.td_textView_routeType); - - return vContainer; - } - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - - if(isWebRequest){ - currentStat=new Statics_bean(app.getCurrentTrack().getTrackBean()); -// chk_showGpx.setEnabled(false); - chk_showGpx.setVisibility(View.GONE); - super.onActivityCreated(savedInstanceState); - svrNumber = this.trackId; - return; - } - super.onActivityCreated(savedInstanceState); - - chk_showGpx.setChecked(app.getGpxShowingTracks().contains(trackId)); -// chk_showGpx.setOnCheckedChangeListener(gpxCheckboxListener); - chk_showGpx.setOnClickListener(new OnCheckBoxClickListener()); - - } - - - class OnCheckBoxClickListener implements OnClickListener { - - @Override - public void onClick(View view) { -// CheckBox checkBox = (CheckBox) view; - QLog.getLogger().d(dTAG, "gpx_checkbox checked?" +chk_showGpx.isChecked()); - if(mTrack_bean==null || mTrack_bean.getTrackId()<=0)return; - activity.app.setGpxShowingTracks(String.valueOf( mTrack_bean.getTrackId()), chk_showGpx.isChecked()); - if(chk_showGpx.isChecked() &&mTrack!=null){ - activity.app.getTrackCache().put(Integer.valueOf(mTrack_bean.getTrackId()), mTrack); - } - - } - - } - - @Override - protected void setTrackDesc(){ - super.setTrackDesc(); - boolean canEdit=trackId>0 && !isWebRequest; - this.btnNewCate.setEnabled(canEdit); - - this.mNameEdit.setEnabled(canEdit); - mDescEdit.setEnabled(canEdit); - this.spDetailTrackType.setEnabled(canEdit && inType!=TrackType.GPX.toInt()) ; - - int visible = canEdit?View.VISIBLE:View.INVISIBLE; - if(btnSave!=null){ - btnSave.setVisibility(visible); - btnSave.setOnClickListener(ButtonOnClickListener); - } - -// this.btnUpload.setVisibility(visible); - - } - - @Override - protected void validEditButtons(){ - super.validEditButtons(); - btn_edit.setEnabled(td_btn_export.isEnabled()); - if(td_btnContinue!=null){ - td_btnContinue.setVisibility(View.GONE); - } - } - @Override - protected void setTrackDetailMax(){ - - } - @Override - protected void setTrackDetailAv(){ - - } - @Override - protected void setLastTrackDetai(){ - - } - @Override - protected void setTrackDetail1(){ - super.setTrackDetail1(); - try{ - if(currentStat!=null ){ - if(txt_creator!=null ) - txt_creator.setText(currentStat.getCreator()); - if(txt_src!=null ) - txt_src.setText(currentStat.getSrc()); - } - - txt_creator.setText(mTrack.getTrackBean().getUserid()==activity.app.user.getUserbean().getId()? - activity.app.user.getUserbean().getUserName():currentStat.getCreator()); - - - - - - if(txt_routeType!=null){ - txt_routeType.setText(getRouteType(mTrack.getTrackBean().getIsCheckedIn())); - } - - if(mTrack.getTrackBean().getSvrNumber()>0 ||isWebRequest){ - - txt_src.setText(QiYouConstant.BASE_URL+"gpx/"+mTrack.getTrackBean().getSvrNumber()+".gpx"); - -// if(TextUtils.isEmpty(txt_creator.getText())){ -// txt_creator.setText(mTrack.getTrackBean().getUserName()); -// } -// - setUserLinkSpanTxt(txt_creator,mTrack.getTrackBean().getUserid(),mTrack.getTrackBean().getUserName()); - - - - - - } - - - if(mTrack_bean.getType()==TrackType.GPX){ - showTentData(); - } - - - }catch(Exception e){ - Utils.logStackTrace(e, dTAG); - } - - } - - @Override - protected void locationToTrackEnd(){ - super.locationToTrackEnd(); - if(mTrack_bean ==null )return; - - top_sptime.setText(Utils.getTimeCnt(mTrack_bean.getTotalTime(), false) ); -// top_speed.setText("_._"); - float avs =mTrack_bean.getTavs(); - top_speed.setText((avs>0?String.format("%.2f",avs):"--") ); - } - /*@Override - protected void setStaticMap() - { -// if(staticMapImg.getVisibility()==View.VISIBLE)return; - this.staticMapImg.setVisibility(View.GONE); - if (!this.isWebRequest) { - super.setStaticMap(); - return; - } - - String webStaticUrl=Utils.getBaiduStaticMapUrl(mTrack);; - QLog.getLogger().d(dTAG, " webStaticUrl is:"+webStaticUrl); - QLog.getLogger().i(dTAG, " webStaticUrl is:"+webStaticUrl); - if (!TextUtils.isEmpty(webStaticUrl) && this.staticMapImg != null) { - this.IL.DisplayImage(webStaticUrl, this.staticMapImg); - this.staticMapImg.setVisibility(View.VISIBLE); - } - - } - */ - /*@Override - void uploadTrack(Track track){ //导入web 记录 - if(!isWebRequest){ - super.uploadTrack(track); - return; - } - if(isForShare) return; - track.getTrackBean().setTrackId(0); - track.getTrackBean().setType(TrackType.GPX); -// track.getTrackBean().setSrc(track.getTrackBean().getSrc()); - String creator=track.getTrackBean().getCreator(); - creator=TextUtils.isEmpty(creator)||creator.equalsIgnoreCase("null")?track.getTrackBean().getUserName() - :creator+" -- "+track.getTrackBean().getUserName(); - track.getTrackBean().setCreator(creator); - track.getTrackBean().setSvrNumber(0); - activity.app.getImportedGpx().clear(); - - activity.app.getImportedGpx().add(track); - activity.app.impGpx(); - showNotes("导入任务已提交,您可以在 历史-->路书 列表中找到导入到路线。"); - this.btnUpload.setEnabled(false); - }*/ - - void importTrack(){ - - mTrack_bean.setTrackId(0); - mTrack_bean.setType(TrackType.GPX); -// track.getTrackBean().setSrc(track.getTrackBean().getSrc()); - String creator=mTrack_bean.getCreator(); - creator=TextUtils.isEmpty(creator)||creator.equalsIgnoreCase("null")?mTrack_bean.getUserName() - :creator+" -- "+mTrack_bean.getUserName(); - mTrack_bean.setCreator(creator); - mTrack_bean.setSvrNumber(0); - activity.app.getImportedGpx().clear(); - - activity.app.getImportedGpx().add(mTrack); - activity.app.impGpx(); - showNotes("导入任务已提交,您可以在 菜单-->我的记录-->路书 列表中找到导入到路线。"); - this.btnImport.setEnabled(false); - } - - @Override - void updateUploadButton(){ - - super.updateUploadButton(); - boolean canDel =mTrack_bean.getUserid()==activity.app.user.getUserbean().getId() - ||this.isAdmin(); - - - - if(isWebRequest){ - btnImport.setVisibility(View.VISIBLE); -// btnUpload.setText("导入"); - if(btnSave!=null){ - this.btnSave.setEnabled(false); - btnUpload.setVisibility(View.INVISIBLE); - } -// this.btnExportFm.setEnabled(false); -// this.btnDel.setEnabled(false); - this.btnDel.setEnabled(canDel); - int status =mTrack_bean.getAvStatus()==TrackAvStatus.PRIVATE? - R.string.track_edit_public: R.string.track_edit_private; - - btnDel.setText(status); - - btnDelWebTrack.setVisibility(mTrack_bean.getSvrNumber() >0 && mTrack_bean.getUserid() == app.user.getUserbean().getId()?View.VISIBLE : View.GONE); - btnDelWebTrack.setEnabled(mTrack_bean.getUserid() == app.user.getUserbean().getId() ); - /* if(app!=null&&app.mStatistics!=null&&app.mStatistics.getExistedSvrNos().contains(Integer.valueOf(trackId))){ - btnImport.setEnabled(false); - } */ - - } - - else{ - btnImport.setVisibility(View.GONE); - if(btnUpload!=null){ - btnUpload.setEnabled(canDel); - } - } - - } - @Override - protected void startNavi(boolean isSimulation){ - super.startNavi(isSimulation); - if(!isSimulation &&this.isWebRequest){ - app.setLastNavWeb(String.valueOf(svrNumber)+mTrack.getTrackBean().getLastdbTime()); - } - } - - - @Override - protected void updateTrackAvstatus(){ - if(this.isWebRequest){ - - TrackAvStatus status =mTrack_bean.getAvStatus()==TrackAvStatus.PRIVATE? - TrackAvStatus.PUBLIC:TrackAvStatus.PRIVATE; - mTrack_bean.setAvStatus(status); - updateTrackStatus(mTrack_bean.getSvrNumber(),status); - return; - } - - super.updateTrackAvstatus(); - - - } - -// @Override -// void updateUIOnRequestResonsed(String method) { -//// btnSubmit.setEnabled(true); -// updateUploadButton(); -// } - - @Override - public void onResume() { - super.onResume(); - - } - - - private List> mData; - private ListView lv = null; - - void showTentData(){ - - if(mData==null){ - Waypoint_bean lastWb =mTrack_bean.getStartWp().getWb(); - int i=0; - for(Waypoint_bean wb:mTrack_bean.getRoadWps()){ - if(wb.getTurnFlag()!=wpFlag.TENT) continue; - - HashMap data = new HashMap(); - data.put("number", "D" + ++i ); - data.put("icon", String.valueOf(i>1?R.drawable.icon_tent:R.drawable.icon_sstart)); - String startgeo=" "; - - if(lastWb.getGeo()!=null){ - startgeo=(TextUtils.isEmpty( lastWb.getGeo().getCity())?Utils.getProvince(lastWb.getGeo().getProvince()):lastWb.getGeo().getCity()+",") - +lastWb.getGeo().getDistrict(); - QLog.getLogger().d(dTAG, "lastWb.getGeo().getProvince:"+ lastWb.getGeo().getProvince()); - QLog.getLogger().d(dTAG, "lastWb.getGeo().getCity():"+ lastWb.getGeo().getCity()); - QLog.getLogger().d(dTAG, "lastWb.getGeo().getDistrict():"+ lastWb.getGeo().getDistrict()); - - - } - data.put("start", Utils.getGeoDistrict(startgeo,9)); - String endgeo=" "; - if(wb.getGeo()!=null){ - endgeo= (TextUtils.isEmpty( wb.getGeo().getCity())?Utils.getProvince(wb.getGeo().getProvince()):wb.getGeo().getCity()+",") - +wb.getGeo().getDistrict(); - QLog.getLogger().d(dTAG, "wb.getGeo().getProvince:"+ wb.getGeo().getProvince()); - QLog.getLogger().d(dTAG, "wb.getGeo().getCity():"+ wb.getGeo().getCity()); - QLog.getLogger().d(dTAG, "wb.getGeo().getDistrict():"+ wb.getGeo().getDistrict()); - - } - data.put("to", Utils.getGeoDistrict(endgeo,9) ); - data.put("distance", Utils.getFormatedDistance((wb.getSumDist()- lastWb.getSumDist())) ); - data.put("time", String.valueOf(wb.getTime())); - data.put("cmnt", wb.getComment()); - lastWb=wb; - if(mData==null) - mData =new ArrayList>(); - mData.add(data); - } - - if(mData!=null){ - - - HashMap data = new HashMap(); - data.put("number", "D" + ++i ); - data.put("icon", String.valueOf(R.drawable.icon_send)); - String startgeo=" "; - if(lastWb.getGeo()!=null){ - startgeo=(TextUtils.isEmpty( lastWb.getGeo().getCity())?Utils.getProvince(lastWb.getGeo().getProvince()):lastWb.getGeo().getCity()+",")+lastWb.getGeo().getDistrict(); - - } - data.put("start",Utils.getGeoDistrict(startgeo,9) ); - String endgeo=" "; - if(mTrack_bean.getLastWp().getWb().getGeo()!=null){ - endgeo =(TextUtils.isEmpty( mTrack_bean.getLastWp().getWb().getGeo().getCity())?Utils.getProvince(mTrack_bean.getLastWp().getWb().getGeo().getProvince()):mTrack_bean.getLastWp().getWb().getGeo().getCity()+",") - +mTrack_bean.getLastWp().getWb().getGeo().getDistrict(); - - } - data.put("to",Utils.getGeoDistrict(endgeo,9) ); - data.put("distance", Utils.getFormatedDistance((mTrack_bean.getLastWp().getWb().getSumDist()- lastWb.getSumDist())) ); - data.put("time", String.valueOf(mTrack_bean.getLastWp().getWb().getTime())); - data.put("cmnt", mTrack_bean.getLastWp().getWb().getComment()); - mData.add(data); - } - - - - - } - - if(mData==null)return; - - - QSimpleAdapter adapter = new QSimpleAdapter(activity,mData,R.layout.tent_list_detail, - new String[]{"number","icon","start","to","distance","time"}, - new int[]{R.id.tent_number,R.id.tent_img, R.id.tent_from,R.id.tent_to,R.id.tent_km,R.id.tent_time}); - - adapter.setViewBinder( new ViewBinder(){ - @Override - public boolean setViewValue(View view, Object data,String textRepresentation) { - - view.setVisibility(View.VISIBLE); - if(data ==null || TextUtils.isEmpty(data.toString())){ - view.setVisibility(View.GONE); - return true; - } - else - if( view instanceof com.qiyou.mb.android.utils.image.QimageView && data instanceof String){ - com.qiyou.mb.android.utils.image.QimageView iv = (com.qiyou.mb.android.utils.image.QimageView) view; - iv.setBackgroundResource(Integer.valueOf(data.toString())); - return true; - } else if(view.getId()==R.id.tent_time){ - view.setVisibility(View.GONE); - return false; //if return true then will no value set to the view. - } - return false; - } - }); - - - lv.setAdapter(adapter); - adapter.setSelectItem(selectedFoodmarkItem); - lv.setSelection(selectedFoodmarkItem); - setListViewHeightBasedOnChildren(lv); -// lv.smoothScrollToPosition(selectedFoodmarkItem); -// lv.smoothScrollToPositionFromTop(selectedFoodmarkItem, 50); - } - - //更新个人云端记录是否可见 - @Override - void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{ - if(!isWebRequest){ - super.processJsonObject( method,jsonObject, msg); - return; - } - pirntCookies(); - QLog.getLogger().d(dTAG, "to update avstatus:" +jsonObject.toString()); - boolean sucess =jsonObject!=null;//&& jsonObject.has(QiYouConstant.JSONOBJECT_KEY ) -// && TextUtils.isEmpty(jsonObject.get(QiYouConstant.JSONOBJECT_KEY).toString()); - if(sucess){ - - if (mTrack_bean.getAvStatus() == TrackAvStatus.DELETED){ - showNotes("删除成功!"); - activity.isNeedFresh = true; - this.onBack(); - } - - - showNotes("更新成功!"); - Track_bean tb=(Track_bean) Utils.getGsonObject(jsonObject.toString(), Track_bean.class); -// String lastdbupdated=jsonObject.get(QiYouConstant.JSONOBJECT_KEY).toString(); - app.updateTrackAvStatus(mTrack_bean.getTrackId()); //update local record - updateUploadButton(); - - try { //update local gpx cache file. - Utils.writeSDFile(getCacheFileName(QiYouConstant.GPX_CACHE_PATH,String.valueOf(svrNumber)+tb.getLastdbTime()), mTrack_bean.toString()); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - else - showNotes("未知错误"); - - } - - - /* - @Override - void initialCateViews(){ - - } - @Override - void initialEditViews(){ - mDescEdit = (EditText) vContainer.findViewById(R.id.td_edit_desc); - mDescEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)}); - td_track_sumary = (TextView) vContainer.findViewById(R.id.td_track_sumary); - - - } - @Override - protected void showCategoryList(com.qiyou.mb.android.ui.fragments.InnerGridView cateLv , ScrollView textContainer ){ - - }*/ - - private String getRouteType(int type) { - switch(type){ - case 0: return "骑行"; - case 1: return "徒步"; - case 2: return "机动"; - default:return "骑行"; - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GroupDetail.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GroupDetail.java deleted file mode 100644 index 81d151c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GroupDetail.java +++ /dev/null @@ -1,599 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.content.Intent; -import android.graphics.Color; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; - -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.GEO_bean; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.Media; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.enums.mediaType; -import com.qiyou.mb.android.utils.server.RestMethods; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.FileNotFoundException; -import java.io.IOException; - -public class GroupDetail extends ActivityDetail { - - /*@Override - public String getCurrentTag() { - // TODO Auto-generated method stub - return TAG; - }*/ - - @Override - public void setFTag() { - // TODO Auto-generated method stub - TAG="com.qiyou.GroupDetail"; -// FirstTabTextColor= getResources().getColorStateList(R.color.red); -// FirstTabBackGround=R.drawable.icon_group; - } - - public static String getFTag() { - return "com.qiyou.GroupDetail"; - } - - - - private Group_bean currentGroup ; - public static GroupDetail newInstance(Group_bean group) { - - GroupDetail f = new GroupDetail(); - f.currentGroup =group; - return f; - } - - public static GroupDetail newInstance() { - - GroupDetail f = new GroupDetail(); - return f; - } - - public void setCurrentGroup(Group_bean group){ - currentGroup =group; -// initialWebQuery(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - super.BBScate = BBSCate.GROUP.toInt(); - } - - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - if (currentGroup == null) { - - currentGroup = new Group_bean(); - - } - -// svrNumber =currentGroup.getId(); - - - - title =currentGroup.getId()>0 ? getResources().getString(R.string.frg_groupdetail) - +"|"+currentGroup.getName() - : getResources().getString(R.string.frg_groupnew); - - - currentLayout =R.layout.group_detail_edit; - vContainer = inflater.inflate(currentLayout, container, false); - - - initialViews( ); -// initialLLViews(); -// initialMapview(); - - return vContainer; - } - - - - /*@Override - void initialMapview(){ - super.initialMapview(); - - }*/ - - EditText edit_grpspeed; - @Override - void initialExtraViews(){ - - edit_grpspeed = (EditText)vContainer.findViewById(R.id.act_edit_speed); - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - } - @Override - Group_bean getCurrentGroup(){ - return currentGroup; - } - - - @Override - void showWebObject(){ -// showDetail(svrNumber); - if(currentGroup.getId()>0 && currentGroup!=null /*&& currentGroup.getId()==currentGroup.getId()*/){ - -// doWebTrackQuery();//query and show roadbook list - - }else{ //start new action - newGroup(); - } - - getDetails(); - - } - - - @Override - protected void initialViews(){ - - super.initialViews(); - } - - - - void newGroup(){ - loadLocalGroup(); - if(currentGroup==null||currentGroup.getId()>0){ - currentGroup = new Group_bean(); - currentGroup.setUserId(activity.app.user.getUserbean().getId()); - currentGroup.setUserName(activity.app.user.getUserbean().getUserName()); - } - } - - void loadLocalGroup(){ - try { - currentGroup = getGroupFromWebCache(0,0); - } catch (JsonSyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Override - void getDetails(){ - - if(currentGroup.getId()>0 ){ -// act_creator.setText(currentGroup.getUserName()); - setUserLinkSpanTxt(act_creator,currentGroup.getUserId(),currentGroup.getUserName()); - this.BBScate = BBSCate.GROUP.toInt(); // act - this.BBSSubcate = currentGroup.getId(); - this.BBSsubCateName = currentGroup.getName(); - }else{ - act_creator.setText(activity.app.user.getUserbean().getUserName()); - } - - - if ( !TextUtils.isEmpty(currentGroup.getAlbum()) ){ - if (currentGroup.getId() > 0){ - IL.DisplayImage(QiYouConstant.BASE_MD_URL + currentGroup.getAlbum(), this.imgTopBanner); - }else{ - IL.DisplayImage(currentGroup.getAlbum(), this.imgTopBanner); - } - }else { - this.imgTopBanner.setBackgroundResource(R.drawable.icon_grpbanner); - } - - - act_edit_title.setText(currentGroup.getName() ); -// this.edit_act_endGeo.setText(currentGroup.getEndAddress()); -// this.edit_act_startGeo.setText(currentGroup.getStartAddress()); - this.edit_act_startGeo.setText(currentGroup.getPlace()); - urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,currentGroup.getGeo().getSharedAddressUrl()); - - if(currentGroup.getId()>0){ - act_svrNo.setText(currentGroup.getId()+""); - - } - - act_edit_description.setText(currentGroup.getDesc()); -// if(currentGroup.getId()>0) - act_levlRatingBar.setRating(currentGroup.getLevel()); - - edit_act_startTime.setText(Utils.getFormatedTime(currentGroup.getCreated())); - - edit_act_distance.setText(String.format("%.1f",currentGroup.getDistance()/1000)); - //edit_act_distance.setText( Utils.getFormatedDistance(currentGroup.getDistance()) ); - if(currentGroup.getSportTime()>0){ - float spd =currentGroup.getDistance()/(currentGroup.getSportTime()/1000) *3.6f; - edit_grpspeed.setText(String.format("%.1f", spd)); - } - } - @Override - void setDetails(){ - if(currentGroup.getId()==0 || currentGroup.getUserId()<=0){ - currentGroup.setUserId(activity.app.user.getUserbean().getId()); - currentGroup.setUserName(activity.app.user.getUserbean().getUserName()); - act_creator.setText(currentGroup.getUserName()); - } -// - if ( TextUtils.isEmpty(currentGroup.getAlbum()) ){ - IL.DisplayImage(currentGroup.getAlbum(), this.imgTopBanner); - }else { - this.imgTopBanner.setBackgroundResource(R.drawable.icon_banner); - } - currentGroup.setName(act_edit_title.getText().toString()); - currentGroup.setDesc(act_edit_description.getText().toString()); -// currentGroup.setRateLevel(act_levlRatingBar.getNumStars()); -// currentGroup.setLevel(act_levlRatingBar.getRating()); -// currentGroup.setPlace(((EditText) vContainer.findViewById(R.id.act_edit_startGeo)).getText().toString()); - - } -// @Override -// void drawActNaviRoadbook(Track gpxTrack){ -// return; -// } - - - @Override - void validInputs(){ - boolean canEdit = canEdit(); - -// canEdit=false; - int visible=canEdit?View.VISIBLE:View.GONE; - checkSvrObjUser(currentGroup.getId(),activity.app.user.getUserbean().getId()); - - txtStartGeoPicker.setVisibility(visible); - - btn_submitAct.setVisibility(visible); - btn_submitAct.setEnabled(canEdit); - btn_saveAct.setEnabled(currentGroup.getId()==0); - btn_saveAct.setVisibility(currentGroup.getId()==0?View.VISIBLE:View.GONE); - btn_submitAct.setText(currentGroup.getId()>0?R.string.act_update:R.string.act_submit); - - act_edit_title.setEnabled(canEdit); - edit_act_startGeo.setEnabled(canEdit); - act_edit_description.setEnabled(canEdit); - -// edit_act_distance.setEnabled(canEdit); -// edit_act_speed.setEnabled(canEdit); - - - boolean canJoin = currentGroup.getId()>0;// && currentGroup.getUserId() !=activity.app.user.getUserbean().getId(); - visible=canJoin ?View.VISIBLE:View.GONE; - btn_actJoin.setVisibility(visible); - btn_actJoin.setEnabled(canJoin); - btnShare.setVisibility(visible); - -// btn_refresh.setEnabled(currentGroup.getId()>0); -// btn_refresh.setVisibility(currentGroup.getId()>0?View.VISIBLE:View.GONE); - } - @Override - boolean validSubmit(){ - if(currentGroup.getUserId() <=0){ - activity.showLogin(); - return false; - } - - - if(TextUtils.isEmpty(currentGroup.getName())){ - -// act_edit_title.setBackgroundColor(Color.YELLOW); - act_edit_title.setHintTextColor(Color.RED); - act_edit_title.setSelected(true); - this.showNotes("请输入队伍名称"); - return false; - } - if(currentGroup.getName()!=null && currentGroup.getName() .trim().length()<2){ - -// act_edit_title.setBackgroundColor(Color.YELLOW); - act_edit_title.setHintTextColor(Color.RED); - act_edit_title.setSelected(true); - this.showNotes("队伍名称太短了"); - return false; - } - - if( currentGroup.getGeo()==null - || TextUtils.isEmpty(currentGroup.getPlace()) -// || currentGroup.getGeo().getName()==null -// || TextUtils.isEmpty(currentGroup.getGeo().getName().trim()) - - ){ - -// act_edit_title.setBackgroundColor(Color.YELLOW); - ((EditText) vContainer.findViewById(R.id.act_edit_startGeo)).setHintTextColor(Color.RED); - this.showNotes("请设置队伍地点"); - return false; - } - - if(TextUtils.isEmpty(currentGroup.getDesc().trim())){ - -// act_edit_title.setBackgroundColor(Color.YELLOW); - act_edit_description.setHintTextColor(Color.RED); - this.showNotes("请输入队伍介绍"); - return false; - } - - - - - return !TextUtils.isEmpty(currentGroup.getName().trim()) - && currentGroup.getGeo()!=null -// && currentGroup.getGeo().getName()!=null -// && !TextUtils.isEmpty(currentGroup.getGeo().getName().trim()) - && !TextUtils.isEmpty(currentGroup.getPlace()) - && !TextUtils.isEmpty(currentGroup.getDesc().trim()) - && validDate(); - - - - } - - @Override - void postSvr() { - this.postJsonWS(Utils.getGsonString(currentGroup),RestMethods.GRP_P_IMPORT/* "mb/group/"*/); - - } - - - @Override - void writeLocalObjCache(){ - writeGroupCache(currentGroup); - showNotes("已保存草稿",false); - } - @Override - void joinSvrObj(){ - int userId=activity.app.user.getUserbean().getId(); - int groupId =currentGroup.getId(); - String userName=activity.app.user.getUserbean().getUserName(); - String rest =RestMethods.GRP_P_DEL_MEMBER; - if(btn_actJoin.getText().toString().equalsIgnoreCase(getResources().getString(R.string.act_join))){ - rest=RestMethods.GRP_P_ADD_MEMBER; - } - - doMemberOperation(groupId,currentGroup.getName(),currentGroup.getUserId(),userId, userName,rest); - - } - - @Override - void removeUser(int userId){ - doMemberOperation(currentGroup.getId(),currentGroup.getName(),currentGroup.getUserId(),userId, "",RestMethods.GRP_P_DEL_MEMBER); - } - - @Override - void setbackGeoInfo(int textViewId){ - if(textViewId == R.id.act_txt_startGeo_picker){ - activity.latToshow =currentGroup.getLat(); - activity.lngToshow =currentGroup.getLon(); - - } - - } - @Override - boolean canEdit(){ - return currentGroup.getId()==0 - || currentGroup==null - || currentGroup.getId()==0 - || currentGroup.getUserId() ==activity.app.user.getUserbean().getId() - ||this.isAdmin(); - } - - @Override - void setFindResult(){ - if(canEdit() && activity.geoAddress!=null &&activity.geoAddress.getLat()>0 && activity.addressTextId!=0){ - -// int txtid=activity.addressTextId == R.id.ll_start_place?R.id.act_edit_startGeo -// :activity.addressTextId == R.id.ll_end_place?R.id.act_edit_endGeo:-1; - - - int txtid=activity.addressTextId == R.id.act_txt_startGeo_picker?R.id.act_edit_startGeo : -1; - - - if(txtid==-1)return; - - if(activity.geoAddress==null || TextUtils.isEmpty(activity.geoAddress.getCity()) ||TextUtils.isEmpty(activity.geoAddress.getCity().replace("null", "")))return; - - EditText text =((EditText)vContainer.findViewById(txtid)); - - if(text!=null){ - text.setText(activity.geoAddress.getName()); - - if(txtid ==R.id.act_edit_startGeo){ - currentGroup.setGeo(new GEO_bean(activity.geoAddress )); - currentGroup.getGeo().setSharedAddressUrl(activity.sharedAddressUrl ); -// currentGroup.setStartAddressUrl(activity.sharedAddressUrl); -// currentGroup.setStartAddress(activity.geoAddress.getAddress()); -// currentGroup.setStartPlace(activity.geoAddress.getName()); -// currentGroup.getGeo().setName(activity.geoAddress.getName()); - currentGroup.setLat(activity.geoAddress.getLat()); - currentGroup.setLon(activity.geoAddress.getLon()); - currentGroup.setPlace(activity.geoAddress.getName() ); - currentGroup.setAddress(activity.geoAddress.getAddress()); - - urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,activity.sharedAddressUrl ); - } - - activity.geoAddress=null; - activity.addressTextId=0; - } - } - } - - - @Override - void checkSvrObjUser(int groupId,int userId){ - if(groupId<=0 || userId<=0){ - return; - } - RequestParams params = new RequestParams(); - params.add("groupId", String.valueOf( groupId)); - params.add("userId", String.valueOf( userId)); - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - getJsonWs(params,RestMethods.GRP_G_IS_MEMBER_HAS_GRP /*"mb/group/isMemberHasGrp"*/,true); - } - - - @Override - void shareEndUrl(int viewId){ - - Intent sendIntent = new Intent(); - sendIntent.setAction(Intent.ACTION_SEND); - String url =currentGroup.getGeo().getSharedAddressUrl(); /*viewId==R.id.act_txt_startGeo_share? currentGroup.getStartAddressUrl() - : currentGroup.getEndAddressUrl();*/ - String title =edit_act_startGeo.getText().toString();//currentGroup.getGeo().getName(); - title =String.format("【%s】 %s", currentGroup.getName(),title); - if(viewId==R.id.act_txt_startGeo_share) - sendIntent.putExtra(Intent.EXTRA_TEXT, url); - sendIntent.setType("text/plain"); - startActivity(Intent.createChooser(sendIntent,title )); - - } - - - - - - @Override - void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{ - super.processJsonObject(method, jsonObject, msg); - - if(method.equalsIgnoreCase(RestMethods.GRP_P_IMPORT)){ //sumbmit act - - - int svrNo= jsonObject.getInt("id"); - if(svrNo<=0)return; -// activity.app.user.getUserbean().setScore(jsonObject.getInt("userScore")); -// activity.app.updateUserPref(); - currentGroup.setLastupdated(jsonObject.getInt("lastupdated")); - - if(currentGroup.getId()==0){ - //remove the cache file. - delCachedGroup(0,0); - } - - if(currentGroup.getId()!=svrNo){ - - currentGroup.setId(svrNo); - - doMemberOperation(svrNo,currentGroup.getName(),currentGroup.getUserId(),activity.app.user.getUserbean().getId(),activity.app.user.getUserbean().getUserName(), - RestMethods.GRP_P_ADD_MEMBER); - - if(!TextUtils.isEmpty(currentGroup.getAlbum())){ - setMD(currentGroup.getAlbum(),0,null,null); - } - - showSubmitedObj(svrNo); - - - } - else{ - showNotes(msg); - } - - return; - } - } - - @Override - void showGroup(Group_bean group) { - getDetails(); - } - - @Override - boolean validDate(){ - return true; - } - - @Override - protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){ - - - IL.DisplayImage(picName,imgTopBanner); - if (currentGroup.getId()> 0){ - Media md = new Media(); - md.setTrackSvrNumber(currentGroup.getId()); - md.setUri(picName); - md.setType(mediaType.PIC); - md.setSvrUri(currentGroup.getAlbum()); - try { - super.postBinaryWS(md, RestMethods.GRP_P_UPLOAD_ALBUM); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - }else { - currentGroup.setAlbum(picName); - } - - - } - @Override - void uploadMediasOnReturn(JSONObject jo) { - this.showNotes("图片上传成功!"); - if (jo!=null){ - try { - if (currentGroup!=null){ - currentGroup.setAlbum(jo.getString("svrUri")); - } - - IL.DisplayImage(QiYouConstant.BASE_MD_URL + jo.getString("svrUri"),imgTopBanner); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - @Override - void generateQcode(){ - if (currentGroup.getId() > 0){ - - JSONObject json = new JSONObject(); - try { - json.put(QiYouConstant.EXTRA_KEY_SVRID, String.valueOf(currentGroup.getId())); - json.put("ownerId", String.valueOf( currentGroup.getUserId())); - json.put("svrName", currentGroup.getName()); - json.put(QiYouConstant.EXTRA_KEY_RESTMETHOD,RestMethods.GRP_P_ADD_MEMBER); - json.put(QiYouConstant.EXTRA_KEY_QCODEDESC, currentGroup.getName()); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - activity.showQcode(json.toString()); - } - } - @Override - public void onResume() { -// activity.app.currentGroupiveFragment =TAG; - super.onResume(); -// activity.updateActionBarTitle(title); -// setFindResult(); -// validInputs(); - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GroupHome.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GroupHome.java deleted file mode 100644 index c175828..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/GroupHome.java +++ /dev/null @@ -1,447 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.TextView; - -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; - -public class GroupHome extends ActivityHome { - - /*@Override - public String getCurrentTag() { - // TODO Auto-generated method stub - return TAG; - }*/ - - @Override - public void setFTag() { - // TODO Auto-generated method stub - TAG="com.qiyou.GroupHome"; -// FirstTabTextColor= getResources().getColorStateList(R.color.red); -// FirstTabBackGround=R.drawable.icon_group; - } - - public static String getFTag() { - return "com.qiyou.GroupHome"; - } - - - - private Group_bean currentGroup ; - public static GroupHome newInstance(Group_bean group) { - - GroupHome f = new GroupHome(); - f.currentGroup =group; - return f; - } - - public static GroupHome newInstance() { - - GroupHome f = new GroupHome(); - return f; - } - - public void setCurrentGroup(Group_bean group){ - currentGroup =group; -// initialWebQuery(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - -// activity =(MainActivity)getActivity(); - -// if(activity.app!=null)activity.app.currentActiveFragment =TAG; -// currentLayout =R.layout.trackingbasic_fragment; - // QLog.getLogger().d(dTAG,TAG+" "+ "onCreate"); -// drawTrack=true; - } - - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - if (currentGroup == null) { - - currentGroup = new Group_bean(); - - } - - title = getResources().getString(R.string.frg_groupdetail) - +"|"+currentGroup.getName(); - - - currentLayout =R.layout.group_home; - vContainer = inflater.inflate(currentLayout, container, false); - - - initialViews( ); -// initialLLViews(); -// initialMapview(); - - return vContainer; - } - - - private TextView grpTitle, grpLevel, grpTime, grpDist,grpSvrno; - - /*@Override - void initialMapview(){ - super.initialMapview(); - - }*/ - - EditText edit_grpspeed; - @Override - void initialExtraViews(){ - - edit_grpspeed = (EditText)vContainer.findViewById(R.id.act_edit_speed); - - - - grpLevel = (TextView)vContainer.findViewById(R.id.grp_level); - grpTime = (TextView)vContainer.findViewById(R.id.grp_time); - grpDist = (TextView)vContainer.findViewById(R.id.grp_dist); - grpTitle = (TextView)vContainer.findViewById(R.id.grp_name); - grpSvrno = (TextView)vContainer.findViewById(R.id.grp_svrno); - - - - - - - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - } - @Override - Group_bean getCurrentGroup(){ - return currentGroup; - } - - - @Override - void showWebObject(){ - - - getDetails(); - - } - @Override - void mapViewOnActivityCreated(){ - - if(currentGroup!=null && currentGroup.getLat()>0){ - locateMapCenter(currentGroup.getLat(),currentGroup.getLon()); - - - - }else{ - if(QiYouConstant.PV_LAST_LAT>0 ){ - locateMapCenter(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON); - } - } - } - - @Override - protected void initialViews(){ - - webTab="队伍"; - roadbookTab ="活动"; - super.initialViews(); - } - - @Override - void addTabs(){ - -// newTabId=1; -// tabBbs = tabhost.newTabSpec(bbsTab); -// tabBbs.setIndicator(bbsTab); -//// tabBbs.setContent(R.id.tab_bbs); -// tabBbs.setContent(tabResourceId); - - tabhost.addTab(tabBbs); - - tabhost.addTab(tabUser); - tabhost.addTab(tabAct); - tabhost.addTab(tabTrack); - - tabhost.addTab(tabLive); - - } - - - - @Override - void getDetails(){ - - this.BBScate = BBSCate.GROUP.toInt(); //act - this.BBSSubcate = currentGroup.getId(); - this.BBSsubCateName =currentGroup.getName(); - BBSSubcateOwner = currentGroup.getUserId(); - grpTitle.setText(currentGroup.getName()); - grpLevel.setText(currentGroup.getLevel()+""); - grpTime.setText( String.format("%.1f", currentGroup.getSportTime()/1000/3600.0) ); -// grpSvrno.setText(currentGroup.getId()+""); - grpSvrno.setText(String.format("距你 %s", Utils.getDistanceRange(/*ab.getDistrange()*/0, currentGroup.getLat(), currentGroup.getLon()))); - grpDist.setText( String.format("%.1f", currentGroup.getDistance()/1000) ); - - - - - /* - if(currentGroup.getId()>0 ){ - act_creator.setText(currentGroup.getUserName()); - }else{ - act_creator.setText(activity.app.user.getUserbean().getUserName()); - } - - act_edit_title.setText(currentGroup.getName()); -// this.edit_act_endGeo.setText(currentGroup.getEndAddress()); -// this.edit_act_startGeo.setText(currentGroup.getStartAddress()); - this.edit_act_startGeo.setText(currentGroup.getPlace()); - urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,currentGroup.getGeo().getSharedAddressUrl()); - - if(currentGroup.getId()>0){ - act_svrNo.setText(currentGroup.getId()+""); - } - - act_edit_description.setText(currentGroup.getDesc()); -// if(currentGroup.getId()>0) - act_levlRatingBar.setRating(currentGroup.getLevel()); - - edit_act_startTime.setText(Utils.getFormatedTime(currentGroup.getCreated())); - - edit_act_distance.setText(String.format("%.1f",currentGroup.getDistance()/1000)); - //edit_act_distance.setText( Utils.getFormatedDistance(currentGroup.getDistance()) ); - if(currentGroup.getSportTime()>0){ - float spd =currentGroup.getDistance()/(currentGroup.getSportTime()/1000) *3.6f; - edit_grpspeed.setText(String.format("%.1f", spd)); - }*/ - } - - @Override - void drawActNaviRoadbook(Track gpxTrack){ - return; - } - - - - @Override - void removeUser(int userId){ - doMemberOperation(currentGroup.getId(),currentGroup.getName(),currentGroup.getUserId(),userId, activity.app.user.getUserbean().getUserName(),RestMethods.GRP_P_DEL_MEMBER); - } - -// private int currentActTab; -// //not to remember last selected tab. -// @Override -// protected void setSelectedTab(){ -// if(tabhost!=null&& tabhost.getCurrentTab()!=currentActTab){ -// tabhost.setCurrentTab(currentActTab); -// } -// } - - - @Override - void getQueryType(int queryType){ - isBBSQuery = queryType == 0; - - isMemberQuery =queryType==1; - isActivityQuery = queryType==2; - isShareQuery =queryType==3; - isLiveQuery =queryType==4; -// currentab = currentTab; - - } - - void doWebQuery(){ //do roadbook query - initialWebListView(R.id.tr_listWeb); - - if( trackData==null) - - doWebTrackQuery(); - else - showWebTrackListData(trackData); - if(trackData!=null) - showNoRecText(trackData.size()==0); - - } - - /* - * - * build query for activities the group users in - * @see com.qiyou.mb.android.ui.fragments.WebList_fragment#buildNearByQueryParames() - */ - @Override - RequestParams buildActQueryParames(){ - RequestParams params = this.buildBasicParames(pageNo, -1); - - params.add("groupId", String.valueOf(currentGroup.getId())); - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - -/* RequestParams buildActNearByQueryParames(){ - if(svrNumber<=0){ - return null; - } - RequestParams params = new RequestParams(); - params.add("page", String.valueOf(pageNo)); - params.add("pagesize", String.valueOf(pageSize)); - //QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON -// params.add("lat",String.valueOf(QiYouConstant.PV_LAST_LAT)); -// params.add("lon",String.valueOf(QiYouConstant.PV_LAST_LON)); - params.add("memberId",String.valueOf(activity.app.user.getUserbean().getId())); - - params.add("groupId",String.valueOf(svrNumber)); - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - */ - - @Override - RequestParams buildShareQueryParames(){ - - RequestParams params = super.buildShareQueryParames() ; - - - if(currentGroup != null && currentGroup.getId()>0 ) { - params.add("groupId", String.valueOf(currentGroup.getId())); - } - - QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - RequestParams buildMemberQueryParames(){ - - int groupId=currentGroup==null?-1:currentGroup.getId(); - - if(groupId<=0 ) { - return null; - } - - - - RequestParams params = new RequestParams(); - params.add("groupId", String.valueOf(groupId)); - // String svrNo= edSvrNo.getText().toString(); - - params.add("page", String.valueOf(pageNo)); - params.add("pagesize", String.valueOf(pageSize)); - //QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON - -// params.add("actid",String.valueOf(actId )); - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - void showLive(){ - - doLiveQuery(); - } - - - - @Override - RequestParams buildLiveQueryParames(){ - RequestParams params = new RequestParams(); -// final int GEO_CITY_TYPE=2; - - if(currentGroup==null) return null; - params.add("groupId", String.valueOf(currentGroup.getId())); - params.add("from", String.valueOf(lastMaxLiveTime)); - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - void showObjDetail(){ - activity.showGroup(currentGroup); - } -// @Override -// void showGroup(Group_bean group) { -// getDetails(); -// } - - @Override - boolean validDate(){ - return true; - } - @Override - void refresh(){ - if(this.isShareQuery){ - if(currentGroup==null ||currentGroup.getId()==0 )return ; - - }else if(isLiveQuery){ - showLive(); - return ; - } - - - this.initialWebQuery(); - - - } - - - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub -// int size =currentGroup!=null && currentGroup.getId()>0?4:2; -// maxTabIndex =size; -// MAPVIEW_INDEX=currentGroup!=null && currentGroup.getId()>0?4:-1; - maxTabIndex =5; - MAPVIEW_INDEX=5; - - - } - - @Override - public void onResume() { -// activity.app.currentActiveFragment =TAG; - super.onResume(); -// activity.updateActionBarTitle(title); -// setFindResult(); -// validInputs(); - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ImageDetailFragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ImageDetailFragment.java deleted file mode 100644 index 7f0f69f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ImageDetailFragment.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.io.File; -import java.util.List; - -import uk.co.senab.photoview.PhotoViewAttacher; -import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.drawable.BitmapDrawable; -import android.os.Bundle; -import android.util.AttributeSet; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.ProgressBar; -import android.widget.Toast; - -import com.nostra13.universalimageloader.core.ImageLoader; -import com.nostra13.universalimageloader.core.assist.FailReason; -import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; -import com.nostra13.universalimageloader.utils.DiskCacheUtils; -import com.nostra13.universalimageloader.utils.MemoryCacheUtils; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.ui.MainActivity; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.image.QimageView; -import com.qiyou.mb.android.utils.log.QLog; - - -public class ImageDetailFragment extends QiyouFragment { -// public static final String TAG ="com.qiyou.ImageDetailFragment"; -// public static final String dTAG ="com.qiyou"; - - @Override - public void setFTag(){ - TAG="com.qiyou.ImageDetailFragment"; - } - public static String getFTag(){ - return "com.qiyou.ImageDetailFragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.ImageDetailFragment"; - } - private String mImageUrl; - private QimageView mImageView; - private ProgressBar progressBar; - private PhotoViewAttacher mAttacher; - ImageDetailFragment fragment ; - protected MainActivity activity; - public static ImageDetailFragment newInstance(String imageUrl) { - final ImageDetailFragment f = new ImageDetailFragment(); - - final Bundle args = new Bundle(); - args.putString("url", imageUrl); - f.setArguments(args); - - return f; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mImageUrl = getArguments() != null ? getArguments().getString("url") : null; - String fileProtocol ="file://"; - String httpProtocol ="http"; - if(!mImageUrl.startsWith(fileProtocol) &&!mImageUrl.startsWith(httpProtocol) ){ - mImageUrl =fileProtocol+mImageUrl; - } - fragment =this; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - final View v = inflater.inflate(R.layout.image_detail_fragment, container, false); - mImageView = (QimageView) v.findViewById(R.id.image); - mAttacher = new PhotoViewAttacher(mImageView); - - mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() { - - @Override - public void onPhotoTap(View arg0, float arg1, float arg2) { -// getActivity().finish(); -// FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction(); -// FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction(); -// fragmentTransaction.remove(fragment); -// fragmentTransaction.commitAllowingStateLoss(); - - } - }); - - progressBar = (ProgressBar) v.findViewById(R.id.loading); - return v; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); -// activity = (MainActivity)getActivity(); -// activity.app.currentActiveFragment =TAG; - -// DisplayImageOptions dio =new DisplayImageOptions(); -// -// ImageLoader.getInstance().displayImage(mImageUrl, mImageView, null); - -// ImageLoader.getInstance().displayImage(mImageUrl, mImageView, new SimpleImageLoadingListener() - - ImageLoader.getInstance().displayImage(mImageUrl, mImageView, new SimpleImageLoadingListener() { - // @Override - // public void onLoadingStarted(String imageUri, View view) { - // progressBar.setVisibility(View.VISIBLE); - // } - boolean cacheFound; - - @Override - public void onLoadingStarted(String imageUri, View view) { - // QLog.getLogger().d(dTAG,TAG+" begin to load image of :" +imageUri ); - - QLog.getLogger().d(dTAG,TAG+" begin to load image of :" +imageUri ); - - progressBar.setVisibility(View.VISIBLE); - List memCache = MemoryCacheUtils - .findCacheKeysForImageUri(imageUri, ImageLoader - .getInstance().getMemoryCache()); - cacheFound = !memCache.isEmpty(); - if (!cacheFound) { - File discCache = DiskCacheUtils.findInCache( - imageUri, ImageLoader.getInstance() - .getDiskCache()); - if (discCache != null) { - cacheFound = discCache.exists(); - } - } - QLog.getLogger().d(dTAG, "Cache exits?"+cacheFound); - } - // - @Override - public void onLoadingComplete(String imageUri, View view, - Bitmap loadedImage) { - progressBar.setVisibility(View.GONE); - try{ - QLog.getLogger().d(dTAG, " loading complete"); - mAttacher.update(); - }catch (Exception e){ - Utils.logStackTrace(e, dTAG); - } - - if (cacheFound) { - /* MemoryCacheUtils.removeFromCache(imageUri, - ImageLoader.getInstance().getMemoryCache()); - DiskCacheUtils.removeFromCache(imageUri, ImageLoader - .getInstance().getDiskCache()); */ - - - } - - } - - @Override - public void onLoadingFailed(String imageUri, View view, FailReason failReason) { - String message = null; - switch (failReason.getType()) { - case IO_ERROR: - message = "下载错误,图片不存在"; - break; - case DECODING_ERROR: - message = "图片无法显示"; - break; - case NETWORK_DENIED: - message = "网络有问题,无法下载"; - break; - case OUT_OF_MEMORY: - message = "内存不足,图片太大无法显示"; - // ImageLoader.getInstance().destroy(); - // activity.app.initialImageLoader(); - ImageLoader.getInstance().clearMemoryCache(); - // ImageLoader.getInstance().getMemoryCache().clear(); - ImageLoader.getInstance().clearDiskCache(); - mAttacher.cleanup(); - break; - case UNKNOWN: - message = "未知的错误"; - break; - } - // Toast.makeText(activity, message, Toast.LENGTH_SHORT).show(); - showNotes(message); - progressBar.setVisibility(View.GONE); - } - - // @Override - // public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { - // progressBar.setVisibility(View.GONE); - // mAttacher.update(); - // } - }); - - - } - - @Override - public void onResume() { - super.onResume(); -// activity.app.currentActiveFragment =TAG; - - - } - - - @Override - public void onDestroy(){ - QLog.getLogger().d(dTAG,TAG+ " Fragment onDestory...."); - - BitmapDrawable drawable =mImageView==null?null: (BitmapDrawable)mImageView.getDrawable(); - - if(drawable!=null){ - Bitmap bmp = drawable.getBitmap(); - if (null != bmp && !bmp.isRecycled()){ - bmp.recycle(); - // bmp = null; - mAttacher.cleanup(); -// mAttacher=null; -// System.gc(); - QLog.getLogger().d(dTAG,TAG+ " Image recycled when fragment destory."); - } - } - super.onDestroy(); - } - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } - - /* class MyImageView extends ImageView { - - public MyImageView (Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - protected void onDraw(Canvas canvas) { - try { - super.onDraw(canvas); - } catch (Exception e) { - QLog.getLogger().d(dTAG,"trying to use a recycled bitmap"); - } - } - }*/ -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ImagePager_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ImagePager_fragment.java deleted file mode 100644 index 1b24254..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/ImagePager_fragment.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentStatePagerAdapter; -import android.support.v4.view.ViewPager.OnPageChangeListener; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.ui.MainActivity; -import com.qiyou.mb.android.utils.HackyViewPager; - -public class ImagePager_fragment extends QiyouFragment { -// public static final String TAG ="com.qiyou.ImagePager_fragment"; -// public static final String dTAG ="com.qiyou"; - - @Override - public void setFTag(){ - TAG="com.qiyou.ImagePager_fragment"; - } - public static String getFTag(){ - return "com.qiyou.ImagePager_fragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.ImagePager_fragment"; - } - private static final String STATE_POSITION = "STATE_POSITION"; - public static final String EXTRA_IMAGE_INDEX = "image_index"; - public static final String EXTRA_IMAGE_URLS = "image_urls"; - - private HackyViewPager mPager; - private int pagerPosition; - private TextView indicator; - private View vContainer; - protected MainActivity activity; - String[] imgUrls; - public static ImagePager_fragment newInstance(int posision,String[] urls) - { - - ImagePager_fragment f = new ImagePager_fragment(); - - Bundle args = new Bundle(); - args.putInt(EXTRA_IMAGE_INDEX, posision); - args.putStringArray(EXTRA_IMAGE_URLS, urls); - f.setArguments(args); - return f; - } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - activity = (MainActivity)getActivity(); -// ImageLoader.getInstance().destroy(); -// activity.app.initialImageLoader(); - - - Bundle bd =this.getArguments(); - pagerPosition = bd.getInt(EXTRA_IMAGE_INDEX, 0); - imgUrls =bd.getStringArray(EXTRA_IMAGE_URLS); - initialView( savedInstanceState); - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - vContainer = inflater.inflate(R.layout.image_detail_pager, container, false); - return vContainer; - } - void initialView(Bundle savedInstanceState){ - mPager = (HackyViewPager) vContainer.findViewById(R.id.pager); - ImagePagerAdapter mAdapter = new ImagePagerAdapter( -// activity.getSupportFragmentManager(), - getChildFragmentManager(), //ViewPager is layouted inside a fragment (not an activty) - imgUrls); - mPager.setAdapter(mAdapter); - indicator = (TextView)vContainer. findViewById(R.id.indicator); - - CharSequence text = getString(R.string.viewpager_indicator, 1, mPager - .getAdapter().getCount()); - indicator.setText(text); - // 鏇存柊涓嬫爣 - mPager.setOnPageChangeListener(new OnPageChangeListener() { - - @Override - public void onPageScrollStateChanged(int arg0) { - } - - @Override - public void onPageScrolled(int arg0, float arg1, int arg2) { - } - - @Override - public void onPageSelected(int arg0) { - CharSequence text = getString(R.string.viewpager_indicator, - arg0 + 1, mPager.getAdapter().getCount()); - indicator.setText(text); - } - - }); - if (savedInstanceState != null) { - pagerPosition = savedInstanceState.getInt(STATE_POSITION); - } - - mPager.setCurrentItem(pagerPosition); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - outState.putInt(STATE_POSITION, mPager.getCurrentItem()); - } - - private class ImagePagerAdapter extends FragmentStatePagerAdapter { - - public String[] fileList; - - public ImagePagerAdapter(FragmentManager fm, String[] fileList) { - super(fm); - this.fileList = fileList; - } - - @Override - public int getCount() { - return fileList == null ? 0 : fileList.length; - } - - @Override - public Fragment getItem(int position) { - String url = fileList[position]; - return ImageDetailFragment.newInstance(url); - } - - } - - - @Override - public void onResume() { - super.onResume(); -// activity.app.currentActiveFragment =TAG; - } - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/InnerGridView.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/InnerGridView.java deleted file mode 100644 index 8026eb3..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/InnerGridView.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.MotionEvent; -import android.widget.GridView; -import android.widget.ScrollView; - - -public class InnerGridView extends GridView { - - ScrollView parentScrollView; - - public ScrollView getParentScrollView() { - return parentScrollView; - } - - public void setParentScrollView(ScrollView parentScrollView) { - this.parentScrollView = parentScrollView; - } - - private int maxHeight; - - public int getMaxHeight() { - return maxHeight; - } - - public void setMaxHeight(int maxHeight) { - this.maxHeight = maxHeight; - } - - public InnerGridView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - // TODO Auto-generated method stub - - if (maxHeight > -1) { - - heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST); - - } - - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - System.out.println(getChildAt(0)); - } - - @Override - public boolean onInterceptTouchEvent(MotionEvent ev) { - - switch (ev.getAction()) { - case MotionEvent.ACTION_DOWN: - - setParentScrollAble(false); - case MotionEvent.ACTION_MOVE: - - break; - case MotionEvent.ACTION_UP: - - case MotionEvent.ACTION_CANCEL: - setParentScrollAble(true); - break; - default: - break; - } - return super.onInterceptTouchEvent(ev); - } - - /** - * @param flag - */ - private void setParentScrollAble(boolean flag) { - if(parentScrollView!=null) - parentScrollView.requestDisallowInterceptTouchEvent(!flag); - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/LocationPickerFragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/LocationPickerFragment.java deleted file mode 100644 index 1431fd8..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/LocationPickerFragment.java +++ /dev/null @@ -1,535 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.JSONObject; - -import android.content.Intent; -import android.location.Location; -import android.location.LocationManager; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnClickListener; -import android.widget.AdapterView; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; -import android.widget.AdapterView.OnItemClickListener; - -import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback; -import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener; -import com.baidu.mapapi.map.MapStatus; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.search.core.PoiInfo; -import com.baidu.mapapi.search.geocode.GeoCodeResult; -import com.baidu.mapapi.search.geocode.GeoCoder; -import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; -import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption; -import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; -import com.baidu.mapapi.search.poi.PoiAddrInfo; -import com.baidu.mapapi.search.poi.PoiNearbySearchOption; -import com.baidu.mapapi.search.poi.PoiResult; -import com.baidu.mapapi.search.share.OnGetShareUrlResultListener; -import com.baidu.mapapi.search.share.PoiDetailShareURLOption; -import com.baidu.mapapi.search.share.ShareUrlResult; -import com.baidu.mapapi.search.share.ShareUrlSearch; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.log.QLog; - -public class LocationPickerFragment extends Route_fragment implements - IlocationFragment { - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - vContainer = inflater.inflate(R.layout.location_picker, container, false); - activity.updateActionBarTitle(R.string.frg_route); - - setFTag(); - initialViews(); - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - activity.geoAddress= new GEOaddress(); -// activity.latToshow -// activity.lngToshow - canLocationMap = true; - locationInMap(null); - locateMapCenter( activity.latToshow,activity.lngToshow); - - - - mBaiduMap.setOnMapStatusChangeListener( new OnMapStatusChangeListener() { - /** - * 手势操作地图,设置地图状态等操作导致地图状态开始改变。 - * @param status 地图状态改变开始时的地图状态 - */ - public void onMapStatusChangeStart(MapStatus status){ - } - /** - * 地图状态变化中 - * @param status 当前地图状态 - */ - public void onMapStatusChange(MapStatus status){ - } - /** - * 地图状态改变结束 - * @param status 地图状态改变结束后的地图状态 - */ - public void onMapStatusChangeFinish(MapStatus status){ - loadPOIs(); - } - }); - } - - @Override - protected void routeInitial(){ - - } - - private ListView lvAdreess = null; - QSimpleAdapter addressSimpleAdapter; - boolean isStartNetLocaiton =false; - - EditText txtSelectedName; - TextView textSelectedAdress; -// TextView textSelectedAdress; - Button btn_locationConfirm; - double lat ; - double lng ; - String uid=""; - private ShareUrlSearch mShareUrlSearch = null; - private GeoCoder mGeoSearch; - - boolean canLoadPoi = true; - // 条目上单击处理方法. - OnItemClickListener itemListener = new OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, - long id) { - selectedAddressItem =position; - addressSimpleAdapter.setSelectItem(position); - addressSimpleAdapter.notifyDataSetInvalidated(); - -// lvAdreess.setSelection(position); - HashMap localHashMap = (HashMap) addressSimpleAdapter.getItem(position); - String pt =localHashMap.get("pt") ; - String[] latlng =pt.split(","); -// int lat =Integer.parseInt(latlng[0]); -// int lng=Integer.parseInt(latlng[1]); - uid =localHashMap.get("uid"); - double lat =Double.parseDouble(latlng[0]); - double lng=Double.parseDouble(latlng[1]); - canLoadPoi = false; - if(canLocationMap){ - locationInMap(null); - - } - - -// mMapController.setCenter(new GeoPoint( lat, lng)); -// mMapView.refresh(); - - locateBaiduMapCenter(lat, lng); - setSelectedText( position); - - } - - - }; - - /* @Override - void loadPtAdrress(LatLng gp){ - mPoiSearch.reverseGeocode(gp); - }*/ - - @Override - public void updateUI(Location location, Boolean isOnPause){ - - updateMapView(location); - - - - } - - @Override - protected void initalLvs(){ - - } - - - @Override - protected void initialViews(){ - initialMapview(); -// initialMkSearch(); - initalFinderViews(); - - lvAdreess =(ListView)vContainer.findViewById(R.id.loc_list); - lvAdreess.setOnItemClickListener(itemListener); - - txtSelectedName =(EditText)vContainer.findViewById(R.id.text_selected_address_name); - textSelectedAdress=(TextView)vContainer.findViewById(R.id.text_selected_address); - btn_locationConfirm=(Button)vContainer.findViewById(R.id.btn_location_confirm); - btn_locationConfirm.setOnClickListener(ButtonOnClickListener); - - rt_cross =(ImageView) vContainer.findViewById(R.id.rt_cross); - rt_cross.setVisibility(View.VISIBLE); - - initialPoiSearch(); - mShareUrlSearch = ShareUrlSearch.newInstance(); - mShareUrlSearch.setOnGetShareUrlResultListener( - - new OnGetShareUrlResultListener(){ - - @Override - public void onGetLocationShareUrlResult(ShareUrlResult result) { - processShareUrl(result); - } - - @Override - public void onGetPoiDetailShareUrlResult(ShareUrlResult result) { - processShareUrl(result); - } - - @Override - public void onGetRouteShareUrlResult(ShareUrlResult arg0) { - - } - - } - - ); - - - mGeoSearch = GeoCoder.newInstance(); - mGeoSearch.setOnGetGeoCodeResultListener( - - new OnGetGeoCoderResultListener(){ - - @Override - public void onGetGeoCodeResult(GeoCodeResult arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void onGetReverseGeoCodeResult( - ReverseGeoCodeResult result) { - - processAddress(result); - } - - } - ); - - } - - - @Override - void pickLocation(){ - - if(activity.addressComponent==null) return; - - - - activity.geoAddress= new GEOaddress(); - activity.geoAddress.setCity(activity.addressComponent.city); - activity.geoAddress.setDistrict( activity.addressComponent.district); - activity.geoAddress.setProvince(activity.addressComponent.province); - activity.geoAddress.setStreet(activity.addressComponent.street); - activity.geoAddress.setStreetNo(activity.addressComponent.streetNumber); - activity.geoAddress.setName(txtSelectedName.getText().toString()); - activity.geoAddress.setAddress(textSelectedAdress.getText().toString()); -// activity.geoAddress.setLat((float) Utils.getggLat(lat/1e6, lng/1e6 )); -// activity.geoAddress.setLon( (float) Utils.getggLon(lat/1e6, lng/1e6)); - activity.geoAddress.setLat((float) Utils.getggLat(lat, lng )); - activity.geoAddress.setLon( (float) Utils.getggLon(lat, lng)); - if(TextUtils.isEmpty(activity.geoAddress.getName().trim())){ - txtSelectedName.setEnabled(true); - txtSelectedName.setSelected(true); - txtSelectedName.requestFocus(); - }else{ - activity.sharedAddressUrl =""; - LatLng gp = new LatLng(lat,lng); - QLog.getLogger().d(dTAG, " to share url lat,lng is" +lat +" , "+lng); - mShareUrlSearch.requestPoiDetailShareUrl(new PoiDetailShareURLOption().poiUid(uid)) ; - //.poiRGCShareURLSearch(gp , "爱骑驴分享-"+ activity.geoAddress.getName(),activity.geoAddress.getAddress()); - - } -// onBack(); - - } - - - @Override - protected - void showMapViews(){ - - } - - @Override - void loadPOIs(){ -// GeoPoint gp = mMapView.getProjection().fromPixels(mMapView.getCenterPixel().x,mMapView.getCenterPixel().y ); -// mBaiduMap.getMapStatus().targetScreen; -// mPoiSearch.searchNearby(new PoiNearbySearchOption().location( mBaiduMap.getMapStatus().target).keyword("")); - if (canLoadPoi){ - mGeoSearch.reverseGeoCode(new ReverseGeoCodeOption().location(mBaiduMap.getMapStatus().target)); - } - canLoadPoi = true; - } - int selectedAddressItem =-1; - - void processAddress(ReverseGeoCodeResult res){ - - selectedAddressItem=-1; - addressData = new ArrayList>(); - - if(res==null){ - // list clear - - return; - } -// activity.sharedAddressUrl =""; -// mSearch.poiRGCShareURLSearch(res.geoPt, "爱骑驴位置分享",""); - Map t;// = new HashMap(); - - if(res.getPoiList()!=null){ - for( PoiInfo info : res.getPoiList() ){ - if ( info.location != null ){ - QLog.getLogger().d(dTAG, info.address); - // mMapView.getController().animateTo(info.pt); - // break; - t = new HashMap(); - t.put("name", info.name); - t.put("address", info.address ); - t.put("pt", info.location.latitude+","+info.location.longitude); - t.put("uid", info.uid); - addressData.add(t); - } - } - }else{ - QLog.getLogger().d(dTAG, res.getAddress()); - t = new HashMap(); - t.put("name", res.getBusinessCircle()); - t.put("address", res.getAddress() ); - t.put("pt", res.getLocation().latitude+","+ res.getLocation().latitude); - - addressData.add(t); - - } - - activity.addressComponent= res.getAddressDetail(); - selectedAddressItem=0; - showAddressData(); - if(canLocationMap){ - locationInMap(null); - } - - } - - - /* @Override - void processAddress(PoiResult result ){ - - super.processAddress(result); - - selectedAddressItem=-1; - addressData = new ArrayList>(); - - if(result==null){ - // list clear - - return; - } -// activity.sharedAddressUrl =""; -// mPoiSearch.poiRGCShareURLSearch(res.geoPt, "爱骑驴位置分享",""); - Map t;// = new HashMap(); - - if(result.getAllAddr()!=null){ - for( PoiAddrInfo info : result.getAllAddr()){ - if ( info.location!= null ){ - QLog.getLogger().d(dTAG, info.address); - // mMapView.getController().animateTo(info.pt); - // break; - t = new HashMap(); - t.put("name", info.name); - t.put("address", info.address ); - t.put("pt", info.location.latitude+","+info.location.latitude); - addressData.add(t); - } - } - }else{ -// QLog.getLogger().d(dTAG, result.strAddr); - t = new HashMap(); - t.put("name", result.); - t.put("address", res.strAddr); - t.put("pt", res.geoPt.getLatitudeE6()+","+ res.geoPt.getLongitudeE6()); - - addressData.add(t); - - } -// activity.addressComponent= result.//res.addressComponents; - selectedAddressItem=0; - showAddressData(); - if(canLocationMap){ - locationInMap(null); - } - - }*/ - - - void processShareUrl (ShareUrlResult res){ - activity.sharedAddressUrl =""; - if(res==null){ - - QLog.getLogger().d(dTAG, " return res is null") ; - - // return; - }else { - activity.sharedAddressUrl =res.getUrl(); - QLog.getLogger().d(dTAG, "return url is "+res.getUrl()) ; - } - - onBack(); - } - - - List> addressData; - - int currentActRow=0; - protected void showAddressData( ){ - - addressSimpleAdapter = new QSimpleAdapter(activity,addressData,R.layout.simple_lv_detail, - new String[]{ - "name", - "address", - "pt" - }, - new int[]{ - R.id.simple_lv_name, - R.id.simple_lv_address, - R.id.simple_lv_value - }); - - - lvAdreess.setAdapter(addressSimpleAdapter); - addressSimpleAdapter.setSelectItem( selectedAddressItem ); - lvAdreess.setSelection(selectedAddressItem); - setSelectedText(selectedAddressItem); - } - - - - void setSelectedText(int position){ - HashMap localHashMap = (HashMap) addressSimpleAdapter.getItem(position); - String pt =localHashMap.get("pt") ; - String[] latlng =pt.split(","); -// lat =Integer.parseInt(latlng[0]); -// lng=Integer.parseInt(latlng[1]); - lat =Double.parseDouble(latlng[0]); - lng=Double.parseDouble(latlng[1]); - -// String name =localHashMap.get("name") ; -// String address =localHashMap.get("address") ; - txtSelectedName.setText(localHashMap.get("name")); - textSelectedAdress.setText(localHashMap.get("adress")); - txtSelectedName.setEnabled(false); - if(TextUtils.isEmpty(txtSelectedName.getText())){ - txtSelectedName.setEnabled(true); - txtSelectedName.setSelected(true); - } -// activity.sharedAddressUrl =""; -// GeoPoint gp = new GeoPoint(lat,lng); -// mPoiSearch.poiRGCShareURLSearch(gp , "爱骑驴位置分享爱骑驴位置分享爱骑驴位\n置分享爱骑驴位置分享爱骑驴位置分享xfsf",txtSelectedName.getText().toString()); - } - - - - - @Override - public void setFTag(){ - TAG="com.qiyou.LocaitonPicker_fragment"; - } - public static String getFTag(){ - return "com.qiyou.LocaitonPicker_fragment"; - } - @Override - public String getCurrentTag(){ - -// QLog.getLogger().e(dTAG,TAG+" Track_fragment, app.currentActiveFragment: "+activity.app.currentActiveFragment); - return "com.qiyou.LocaitonPicker_fragment"; - - } - - - @Override - public void onResume() { - super.onResume(); - activity.app.updateUIstatus(true); - - /* isStartNetLocaiton = !activity.app.isNetworkLocationRequestStarted; - - - - if(!Utils.isNetworkConnected(activity) && !Utils.isGpsEnabled(activity)){ - Toast.makeText(activity, "地图定位需要开启GPS或网络连接", Toast.LENGTH_SHORT).show(); - } - if(isStartNetLocaiton) { //started -// activity.app.startAndroidGPSRequest(); - activity.app.startNetworkLocationRequest(false); - - }*/ - activity.app.isLocationFinding=true; -// activity.app.startNetworkLocationRequest(false); - - } - - @Override - public void onPause() { - super.onPause(); - activity.app.updateUIstatus(false); - /*if(isStartNetLocaiton) { //started -// activity.app.startAndroidGPSRequest(); - activity.app.stopNetworkLocationRequest(); - - } - */ -// activity.app.stopNetworkLocationRequest(); - activity.app.isLocationFinding=false; - - } - @Override - public void onDestroy() { - super.onDestroy(); - } - - @Override - void tabOnresume(){ - - } - @Override - void routeResume(){ - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/LoginFragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/LoginFragment.java deleted file mode 100644 index 4b6dbe5..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/LoginFragment.java +++ /dev/null @@ -1,463 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.io.UnsupportedEncodingException; - -import org.json.JSONException; -import org.json.JSONObject; - -import android.content.Context; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; - -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; -import com.tencent.tauth.IUiListener; -import com.tencent.tauth.UiError; -import com.umeng.message.PushAgent; -import com.umeng.message.UTrack; - -public class LoginFragment extends QiyouFragment { - - @Override - public void setFTag() { - TAG = "com.qiyou.LoginFragment"; - } - - public static String getFTag() { - return "com.qiyou.LoginFragment"; - } - - @Override - public String getCurrentTag() { - return "com.qiyou.LoginFragment"; - } - - public static LoginFragment newInstance() { - LoginFragment f = new LoginFragment(); - return f; - } - - // Progress Dialog Object -// ProgressDialog prgDialog; - // Error Msg TextView Object - TextView errorMsg; - // account Edit View Object - EditText accountET; - // Passwprd Edit View Object - EditText pwdET; - private Button btnLogin,btnLogout; - private Button btnLinkToRegisterScreen; - private Button btnQQLogin; - Context context; -// String account ; - String mail; - // Get Password Edit View Value - String password ; - // Instantiate Http Request Param Object - ScrollView textContainer; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - activity.updateActionBarTitle(R.string.frg_login); - context=activity.getApplicationContext(); - // activity=(MainActivity)getActivity(); - // activity.app.currentActiveFragment =TAG; - vContainer = inflater.inflate(R.layout.login, container, false); - initialView(); - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - textContainer =(android.widget.ScrollView)vContainer.findViewById(R.id.td_scrollView); - if(textContainer!=null) - textContainer.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - - } - - void initialView() { - -// errorMsg = (TextView) vContainer.findViewById(R.id.login_error); - // Find account Edit View control by ID - accountET = (EditText) vContainer.findViewById(R.id.loginAccount); - // Find Password Edit View control by ID - pwdET = (EditText) vContainer.findViewById(R.id.loginPassword); - // Instantiate Progress Dialog object -// if(activity.app.user.getUserbean()!=null){ -// accountET.setText(activity.app.user.getUserbean().getAccount()); -// } - - if(activity.app.user.getUserbean()!=null - &&activity.app.user.getUserbean().getLoginType()==0){ - accountET.setText(activity.app.user.getUserbean().getMail()); - } - - btnQQLogin= (Button) vContainer.findViewById(R.id.btnQQLogin); - btnQQLogin.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - doQQLogin(); - } - }); - btnLinkToRegisterScreen = (Button) vContainer.findViewById(R.id.btnLinkToRegisterScreen); - btnLinkToRegisterScreen.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - activity.is4Login=true; - activity.showRegist(); - } - }); - btnLogin =(Button) vContainer.findViewById(R.id.btnLogin); - btnLogin.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - try { - Utils.hideSoftKeyboard(activity); - activity.is4Login=false; - loginUser(); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }); - - - btnLogout = (Button) vContainer.findViewById(R.id.btnLogout); - btnLogout.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - logout(); -// activity.app.logout(); -// Toast.makeText(activity, "您已登出",Toast.LENGTH_SHORT).show(); -// activity.isTabHome(); - - } - }); - btnLogout.setVisibility(activity.app.user.getUserbean().getId() > 0 ? View.VISIBLE:View.GONE); - btnLogout.setVisibility(View.GONE); - - initalCurrentLoginUserVuew(); - } - - void initalCurrentLoginUserVuew(){ - TextView tv =(TextView)vContainer.findViewById(R.id.current_loginAccount); - - if(activity.app.user.getUserbean().getId()<=0 -// || this.getUser().getLoginType()==0 && activity.app.user.getUserbean().getExprires()==0 - ){ - tv.setVisibility(View.GONE); - return; - } - tv.setVisibility(View.VISIBLE); - - - String loginTitle = activity.app.user.getUserbean().getId()<=0?"": - activity.app.user.getUserbean().getUserName()/*.getAccount()*/ ; - - int loginType =activity.app.user.getUserbean().getLoginType(); - tv.setText("登录状态"); - tv.setText(String.format("当前已登录%s:%s",loginType==1?"(QQ认证用户)":"用户", loginTitle )) ; - - - - - - } - - - /** - * Method gets triggered when Login button is clicked - * - * @param view - * @throws JSONException - * @throws UnsupportedEncodingException - */ - public void loginUser() throws JSONException, UnsupportedEncodingException { - // Get account Edit View Value - /* account*/mail = accountET.getText().toString(); - // Get Password Edit View Value - password = pwdET.getText().toString(); - password= Utils.getMD5Str(password); - // Instantiate Http Request Param Object -// RequestParams params = new RequestParams(); - // When account Edit View and Password Edit View have values other than - // Null - - if( !Utils.validate(mail)) { - Toast.makeText(activity, "请输入您注册用的邮箱", - Toast.LENGTH_LONG).show(); - return; - } - - if (!TextUtils.isEmpty(mail) && !TextUtils.isEmpty(password) ) { - // When account entered is Valid -// if (QiYouConstant.DEVELOPER_MODE||Utils.validate(account)) { - // Put Http parameter username with value of account Edit View - // control - /* JSONObject json = new JSONObject(); - json.put("mail", mail); - json.put("passwd", Utils.getMD5Str(password)); - json.put("phoneid", activity.app.getPhoneId());*/ - User_bean u =new User_bean(); - u.setMail(mail); - u.setPassword(password); - u.setPhoneId(activity.app.getPhoneId()); - -// setCookie(); - postJsonWS(Utils.getGsonString(u),RestMethods.USER_P_USER_LOGIN/*"mb/user/login"*/); - QLog.getLogger().d(dTAG, "登陆。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"); - QLog.getLogger().d(dTAG, Utils.getGsonString(u)); -// StringEntity entity = new StringEntity(json.toString()); -// invokeWS(entity); -// postJsonWS(entity,"mb/user/login"); - -// params.put("json", strparams); - -// params.put("username", account); - // Put Http parameter password with value of Password Edit Value - // control -// params.put("password", password); - // Invoke RESTful Web Service with Http parameters -//// invokeWS(params); -// } -// // When account is invalid -// else { -// Toast.makeText(activity, "账号输入错误", -// Toast.LENGTH_LONG).show(); -// } - } - // When any of the Edit View control left blank - else { - this.showNotes("登录邮箱和密码不能为空", true); - } - - } - - - - @Override - void processJsonObject(String method,JSONObject response,String msg) throws JSONException{ - activity.app.setLastStatSyncTime(0); - User_bean ub =(User_bean) Utils.getGsonObject(response.toString(), User_bean.class); - if(TextUtils.isEmpty(ub.getUserName()) - && !TextUtils.isEmpty(ub.getAccount())){ - ub.setUserName(ub.getAccount()); - } - activity.app.user.setUserbean(ub); - activity.app.updateUserPref(ub); - activity.app.setAuth(); - updatePushAlias(); -// initPrgDialog(); -// activity.app.mStatistics=null;//new Statistics(); - activity.app.isNewLogin=true; - activity.app.syncStatistics(); - - - - QLog.getLogger().d(dTAG, TAG+" response user:" +response.toString()); - /* activity.app.updateUserPref(response.getInt("id"), - response.getString("mail"), - response.getString("account"), - password , - response.getString("title"), - response.getInt("score"), - response.getInt("paiming") - );*/ -// setCookie(); - - onBack();//返回 - -// new Thread(){ -// public void run() { -// try{ -// Instrumentation inst = new Instrumentation(); -// inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); -// } -// catch (Exception e) { -// Log.e("Exception when onBack", e.toString()); -// } -// } -// }.start(); - - - } - - protected void updatePushAlias(){ - if ( activity.app.user.getUserbean().getId() > 0) { - PushAgent mPushAgent = PushAgent.getInstance(activity); - String id = activity.app.user.getUserbean().getId()+""; -// id = 951+""; - mPushAgent.addAlias(id ,"i7lvid", new UTrack.ICallBack() { - @Override - public void onMessage(boolean isSuccess, String message) { - QLog.getLogger().d(dTAG, " alia is success ?" + isSuccess +"," + message); - } - }); - } - - } - - - String SCOPE = "get_simple_userinfo,add_topic";//所有权限用“all” - public void doQQLogin() { - IUiListener listener = new BaseUiListener() { - @Override - protected void doComplete(/*JSONObject*/Object values) { - onAuth20LoginComplete(values); - } - }; - activity.mTencent.login(this, SCOPE, listener); - QLog.getLogger().d(dTAG, " QQ Login begin......"); - } - - private void onAuth20LoginComplete(Object values){ - - try { - JSONObject json =(JSONObject)values; - QLog.getLogger().d(dTAG, json.toString()); - QiYouConstant.PV_OPEN_ID =json.getString("openid"); - QiYouConstant.PV_ACCESS_TOKEN =json.getString("access_token"); - QiYouConstant.PV_EXPIRES_IN =System.currentTimeMillis()+Long.parseLong(json.getString("expires_in"))*1000; - activity.app.saveAuth20Token(); - -// activity.mTencent.request(SocialConstants. arg1, arg2) - String url="https://graph.qq.com/user/get_user_info" ;//?access_token=YOUR_ACCESS_TOKEN&oauth_consumer_key=YOUR_APP_ID&openid=YOUR_OPENID - - RequestParams params = new RequestParams(); - params.put("access_token", QiYouConstant.PV_ACCESS_TOKEN); - params.put("oauth_consumer_key", QiYouConstant.TENCENT_APP_ID); - params.put("openid", QiYouConstant.PV_OPEN_ID); - - get3dJsonWs(params,url,false); - - - - - - - - - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - QLog.getLogger().d(dTAG, " QQ Login get response and begin to request user info from qq..."); - } - - - @Override - void process3dpartJson(JSONObject response) throws JSONException{ - QLog.getLogger().d(dTAG, " user info from qq success..."); - - if(response==null)return; - -// figureurl - - User_bean u = new User_bean(); - u.setQqOpenId(QiYouConstant.PV_OPEN_ID); - u.setQqExprires(QiYouConstant.PV_EXPIRES_IN); - u.setQqToken(QiYouConstant.PV_ACCESS_TOKEN ); - u.setQqAbulmUrl(response.getString("figureurl_qq_1")); - u.setQqName(response.getString("nickname")); - u.setUserName(response.getString("nickname")); - u.setAccount(QiYouConstant.PV_OPEN_ID); - u.setLat(QiYouConstant.PV_LAST_LAT); - u.setLon(QiYouConstant.PV_LAST_LON); - u.setLoginType(1); - u.setPhoneId(activity.app.getPhoneId()); - postJsonWS(Utils.getGsonString(u),RestMethods.USER_P_USER_LOGIN/*"mb/user/login"*/); - QLog.getLogger().d(dTAG, " QQ Login get response and syncing with i7lv..."); - } - - - @Override - public void showNotes(String notes,Boolean showToast){ - if(TextUtils.isEmpty(notes))return; - - if(vContainer==null)return; - TextView txtNote=(TextView)vContainer.findViewById(R.id.txtNotice); - if(txtNote!=null){ - txtNote.setText(notes); - txtNote.setVisibility(View.VISIBLE); - } - - } - - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } - //http://blog.csdn.net/zhaoyazhi2129/article/details/26983145 - private class BaseUiListener implements IUiListener { - @Override - public void onComplete(Object response) { - //V2.0版本,参数类型由JSONObject 改成了Object,具体类型参考api文档 -// mBaseMessageText.setText("onComplete:"); - QLog.getLogger().d(dTAG, "Tencent Auth2.0 on Complete."); - doComplete(response); - } - protected void doComplete(/*JSONObject*/Object values) { - - } - @Override - public void onError(UiError e) { - QLog.getLogger().e("onError:", "code:" + e.errorCode + ", msg:" - + e.errorMessage + ", detail:" + e.errorDetail); - } - @Override - public void onCancel() { -// showResult("onCancel", ""); - } - - } - @Override - void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){ - super.asynClientOnFailure(statusCode, msg, headers); - if (statusCode == 417) { - - showNotes("出错了,错误信息:"+msg,true); - } - // When Http response code other than 404, 500 - - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteDetail.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteDetail.java deleted file mode 100644 index c65b79a..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteDetail.java +++ /dev/null @@ -1,642 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.content.DialogInterface; -import android.os.Bundle; -import android.text.SpannableString; -import android.text.Spanned; -import android.text.TextUtils; -import android.text.method.LinkMovementMethod; -import android.text.style.ClickableSpan; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnClickListener; -import android.widget.AdapterView; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.SimpleAdapter.ViewBinder; - -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.Note; -import com.qiyou.mb.android.beans.basic.NoteMessage; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.ui.fragments.Querybase_fragment.ListviewOnScroll; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.exception.NoWebObjectException; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; - -public class NoteDetail extends NoteList { - @Override - public void setFTag() { - TAG = "com.qiyou.NoteDetail"; - } - - public static String getFTag() { - return "com.qiyou.NoteDetail"; - } - - @Override - public String getCurrentTag() { - return "com.qiyou.NoteDetail"; - } - - public static NoteDetail newInstance(Note note, NoteMessage msg) { - NoteDetail f = new NoteDetail(); - f.currentNote = note; - f.currentMsg = msg; - return f; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - activity.updateActionBarTitle(R.string.frg_notedetail); - - vContainer = inflater.inflate(R.layout.notes_detail, container, false); - initialView(); - return vContainer; - } - - EditText editTitle, editBody; - TextView viewTitle, viewBody, txtCate, txtSubcate; - - Button btnEdit; - - @Override - protected void initialView() { - super.initialView(); - editTitle = (EditText) vContainer.findViewById(R.id.edit_note_title); - editBody = (EditText) vContainer.findViewById(R.id.edit_note_detail); - btnDel = (Button) vContainer.findViewById(R.id.btn_delNote); - btnEdit = (Button) vContainer.findViewById(R.id.btn_editNote); - btnEdit.setOnClickListener(ButtonOnClickListener); - - btnDel.setOnClickListener(ButtonOnClickListener); - viewTitle = (TextView) vContainer.findViewById(R.id.view_note_title); - viewBody = (TextView) vContainer.findViewById(R.id.view_note_detail); - txtCate = (TextView) vContainer.findViewById(R.id.txt_note_cate); - txtSubcate = (TextView) vContainer.findViewById(R.id.txt_note_subcate); - - lvNotes =(ListView)vContainer.findViewById(R.id.listNotes); - lvNotes.setOnScrollListener( new ListviewOnScroll()); - lvNotes.setOnItemClickListener(itemListener); - - // lvNotes.setOnItemClickListener(null); - // btnSubmit=(Button)vContainer.findViewById(R.id.btn_submitNote); - - /* - * btnSubmit.setOnClickListener(new OnClickListener() { - * - * @Override public void onClick(View view) { try { - * Utils.hideSoftKeyboard(activity); - * - * submitNote(); - * - * } catch (JSONException e) { // TODO Auto-generated catch block - * e.printStackTrace(); } catch (UnsupportedEncodingException e) { // - * TODO Auto-generated catch block e.printStackTrace(); } } }); - */ - - } - - - OnItemClickListener itemListener = new OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - QLog.getLogger().d(dTAG, String.format("adapter count %s,postion is %s", parent.getCount(),position)); - - - if(parent.getCount()==position+1 || !canclick)return; - - - canclick =false; - - lastIndexOnMore =-1; -// isLoadMoreIndex =false; - selectNotesItem =position; - if (isNoteQuery) { - showMsgDetail(position) ; - canclick =true; - return; - } - } - }; - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); -// if (currentMsg != null) { -// setMsgDetail(); -// } else - setNoteDetail(); - -// boolean showDel = this.isAdmin() || getUser().getId() == currentNote.getUserId(); - btnDel.setVisibility(canDelete() ? View.VISIBLE : View.GONE); - btnEdit.setVisibility(canEdit() ? View.VISIBLE : View.GONE); - - } - - private String cacheKey = ""; - - private void setNoteDetail() { - viewTitle.setVisibility(View.VISIBLE); - lvNotes.setVisibility(View.VISIBLE); - btnNew.setVisibility(View.VISIBLE); - viewTitle.setText(currentNote.getTitle().toString()); - viewBody.setText(currentNote.getBody().toString()); -// this.btnNew.setVisibility(this.currentNote.getStatus()==0 ?View.VISIBLE:View.GONE); - this.btnNew.setEnabled(this.currentNote.getStatus()==0); -// String name =currentNote.getUserName(); -// final int userId = currentNote.getUserId(); - /* - SpannableString spannableString1 = new SpannableString(name); - spannableString1.setSpan(new ClickableSpan() { - @Override - public void onClick(View view) { - - final int cate = BBSCate.USER.toInt(); - cacheKey = cate + "-" + userId; - String restMethod = ""; - Boolean isCached = activity.app.getWebObjcache().containsKey(cacheKey); - - if (isCached) { - User_bean obj = (User_bean) activity.app.getWebObjcache() - .get(cacheKey); - showMember(obj); - - } else { - restMethod = RestMethods.USER_G_FIND_BY_ID; - } - - - if (!TextUtils.isEmpty(restMethod)){ - RequestParams params = new RequestParams(); - params.add("id", String.valueOf( userId)); - QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params,restMethod ); - } - - } - - }, - 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - */ - - TextView txt = (TextView) vContainer.findViewById(R.id.view_note_author); - setUserLinkSpanTxt(txt,currentNote.getUserId(),currentNote.getUserName()); -// txt.setText( getUserLinkSpanTxt(currentNote.getUserId(),currentNote.getUserName()) ); -// txt.setMovementMethod(LinkMovementMethod.getInstance()); - - com.qiyou.mb.android.utils.image.QroundimageView imgv = (( com.qiyou.mb.android.utils.image.QroundimageView) vContainer.findViewById(R.id.msgimgUserAbulm)); - - IL.DisplayImage(Utils.getUserAlbum(currentNote.getUserAlbum()), imgv); - - ((TextView) vContainer.findViewById(R.id.view_note_created)) - .setText(Utils.getFormatedTime(currentNote.getCreated())); - - if (this.BBScate != currentNote.getCategory() - && this.BBSSubcate != currentNote.getSubCate()) { - this.txtCate.setText("[" - + BBSCate.values()[currentNote.getCategory()].toCHString() - + "]"); - -// this.txtSubcate.setText("[" + currentNote.getSubCateName()+ "]"); - - String text1 = currentNote.getSubCateName() ; - SpannableString spannableString1 = new SpannableString(text1); - spannableString1.setSpan(new ClickableSpan() { - @Override - public void onClick(View view) { - - if (currentNote.getSubCate() == 0) { - return; - } - - final int cate = currentNote.getCategory(); - cacheKey = cate + "-" + currentNote.getSubCate(); - String restMethod = ""; - - - - Boolean isCached = activity.app.getWebObjcache().containsKey(cacheKey); - - if (cate == BBSCate.ACT.toInt()) { - if (isCached) { - Activity_bean obj = (Activity_bean) activity.app.getWebObjcache() - .get(cacheKey); - showActivity(obj); - - } else { - restMethod = RestMethods.ACT_G_FIND_BY_ID; - } - } else if (cate == BBSCate.GROUP.toInt()) { - if (isCached) { - Group_bean obj = (Group_bean) activity.app.getWebObjcache() - .get(cacheKey); - showGroup(obj); - - } else { - restMethod = RestMethods.GRP_G_FIND_BY_ID; - } - } else if (cate == BBSCate.USER.toInt()) { - if (isCached) { - User_bean obj = (User_bean) activity.app.getWebObjcache() - .get(cacheKey); - showMember(obj); - - } else { - restMethod = RestMethods.USER_G_FIND_BY_ID; - } - } else if (cate == BBSCate.TRACK.toInt()) { - if (isCached) { - Track obj = (Track) activity.app.getWebObjcache() - .get(cacheKey); - showWebTrack(obj); - - } else { - restMethod = RestMethods.TRACK_G_FIND_BY_ID; - } - } else if (cate == BBSCate.GEO.toInt()) { - activity.showNoteList(cate, currentNote.getSubCate()); - } - - if (!TextUtils.isEmpty(restMethod)){ - RequestParams params = new RequestParams(); - params.add("id", String.valueOf( currentNote.getSubCate())); - params.add("swidth", String.valueOf(QiYouConstant.PV_INT_SCREEN_WIDTH)); - params.add("sheight", String.valueOf(QiYouConstant.PV_INT_SCREEN_HEIGHT)); - QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params,restMethod ); - } - - - } - }, 0, text1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - - txtSubcate.setText( spannableString1 ); - txtSubcate.setMovementMethod(LinkMovementMethod.getInstance()); - - } - - } - - private void setMsgDetail() { - - /* - viewBody.setText(currentMsg.getBody().toString()); - ((TextView) vContainer.findViewById(R.id.view_note_author)) - .setText(currentMsg.getUserName().toString()); - ((TextView) vContainer.findViewById(R.id.view_note_created)) - .setText(Utils.getFormatedTime(currentMsg.getCreated())); - - lvNotes.setVisibility(View.GONE); - btnNew.setVisibility(View.GONE); - viewTitle.setVisibility(View.GONE); - */ - - } - - @Override - void editNote() { - if (canEdit()) { - activity.showEditNote(currentNote, null); - } - - } - - - - private void editMessage(){ - activity.showEditNote(null, currentMsg); - } - - @Override - void doNoteQuery() { - if (currentNote == null && currentMsg != null) { - requestNoteFromWeb(currentMsg.getId()); - return; - } - Utils.hideSoftKeyboard(activity); - - isNoteQuery = true; - // lvWeb.setVisibility(View.VISIBLE); - // lv.setVisibility(View.GONE); - QLog.getLogger() - .d(dTAG, TAG + "------begin Note reply query--------- "); - - /* - * if( this.firstLoad&&!TextUtils.isEmpty(lastNoteQueryPara)){ return; } - */ - RequestParams param = buildNotesQueryParames(0, currentNote.getId()); - if (param != null) { - - QLog.getLogger().d(dTAG, lastNoteQueryPara); - QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param, RestMethods.NOTEMSG_G_LIST /* "mb/user/actusers" */); - - selectNotesItem = -1; - - } - - } - - JSONArray msgArray; - @Override - void processNotesJsonArray(JSONArray jsonArrary) { - ArrayList> tmpData = new ArrayList>(); - JSONObject jo = null; - NoteMessage ab; - msgArray = jsonArrary; - if (jsonArrary != null) - for (int i = 0; i < jsonArrary.length(); i++) { - try { - jo = jsonArrary.getJSONObject(i); - if (jo == null) - continue; - // QLog.getLogger().d(dTAG, "jsonarray:--> " - // +jo.toString()); - ab = (NoteMessage) Utils.getGsonObject(jo.toString(), - NoteMessage.class); - - } catch (JsonSyntaxException je) { - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - if (ab != null) { - Map t = new HashMap(); - // t.put("title", ab.getTitle()/*.getAccount()*/); - t.put("id", String.valueOf(ab.getId())); - t.put("body", ab.getBody()); - t.put("username", ab.getUserName()+"split%.A.#B&.#C" + ab.getUserId() ); - t.put("created", Utils.getFormatedTime(ab.getCreated())); - t.put("album", Utils.getUserAlbum(ab.getUserAlbum())); - t.put("userid", String.valueOf(ab.getUserId())); - tmpData.add(t); - } - - } - - noteData = getListData(noteData, tmpData); - - showNoRecText(noteData.size() == 0); - - showNoteData(); - setListViewHeightBasedOnChildren(lvNotes); - QLog.getLogger().e( - dTAG, - String.format("notesPageNo is%s, actual pageno is %s ", - notesPageNo, noteData.size() / pageSize)); - - } - - @Override - protected void showNoteData() { - - notesSimpleAdapter = new QSimpleAdapter(activity, noteData, - R.layout.notes_list_detail_msg, new String[] { - /* "title", */ - "body", "id", "username", "created","album" }, new int[] { - /* R.id.list_note_name, */ - R.id.list_note_body, R.id.list_note_id, - R.id.list_note_username, R.id.list_note_created ,R.id.list_note_imgUserAbulm}); - - - notesSimpleAdapter.setViewBinder( new ViewBinder(){ - @Override - public boolean setViewValue(View view, Object data,String textRepresentation) { - - switch (view.getId() ){ - - case R.id.list_note_username:{ - - - if(data==null )return false; - - - String[] res = data.toString().split("split%.A.#B&.#C"); - - if (res.length != 2){ - return true; - } - - final int userId = Integer.valueOf(res[1]); - String name = res[0]; - /* - SpannableString spannableString1 = new SpannableString(name); - spannableString1.setSpan(new ClickableSpan() { - @Override - public void onClick(View view) { - - - - final int cate = BBSCate.USER.toInt(); - cacheKey = cate + "-" + userId; - String restMethod = ""; - Boolean isCached = activity.app.getWebObjcache() != null - && activity.app.getWebObjcache().containsKey(cacheKey); - - - if (isCached) { - User_bean obj = (User_bean) activity.app.getWebObjcache() - .get(cacheKey); - showMember(obj); - - } else { - restMethod = RestMethods.USER_G_FIND_BY_ID; - } - - - if (!TextUtils.isEmpty(restMethod)){ - RequestParams params = new RequestParams(); - params.add("id", String.valueOf( userId)); - QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params,restMethod ); - } - - - } - - }, - 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - */ - TextView txt = (TextView)view; - setUserLinkSpanTxt(txt,userId,name); -// txt.setText( getUserLinkSpanTxt( userId,name) ); -// txt.setMovementMethod(LinkMovementMethod.getInstance()); - - - return true; - } - case R.id.list_note_imgUserAbulm:{ - com.qiyou.mb.android.utils.image.QroundimageView imgv = (com.qiyou.mb.android.utils.image.QroundimageView) view; - - if(data==null )return false; - QLog.getLogger().d(dTAG, " displaying available image of " + data.toString()); - IL.DisplayImage( data.toString(),imgv); - - return true; - } - - } - - return false; - }}); - - - bindListView(notesSimpleAdapter, lvNotes, selectNotesItem, - isNotesLastPage); - - - - - - - lvNotes.setDividerHeight(2); - - } - - @Override - void requestNoteFromWeb(int noteId) { - if (noteId <= 0) - return; - RequestParams params = new RequestParams(); - params.add("id", String.valueOf(noteId)); - getJsonWs(params, RestMethods.NOTEMSG_G_FIND_BY_ID); - } - - void showMsgDetail(int position) { - try { - -// HashMap localHashMap = (HashMap) this.notesSimpleAdapter -// .getItem(position); -// noteId = Integer.parseInt(localHashMap.get("id")); -// int userId = Integer.parseInt(localHashMap.get("userid")); - - - - QLog.getLogger().d("com.qiyou", - TAG + " get selected noteId:" + this.noteId); - - currentMsg = (NoteMessage) Utils.getGsonObject(msgArray.get(position).toString(), - NoteMessage.class); - - if (super.canEdit()){ - - this.notesSimpleAdapter.setSelectItem(position); - this.notesSimpleAdapter.notifyDataSetInvalidated(); - this.lvNotes.setSelection(position); - editMessage(); -// activity.showEditNote(null, currentMsg); -// activity.showNoteDetail(null, currentMsg); - - - - } - - - } catch (NumberFormatException ne) { - Utils.logStackTrace(ne, TAG); - showNotes("出错了"); - return; - } catch (java.lang.IndexOutOfBoundsException IndexException) { - Utils.logStackTrace(IndexException, TAG); - } catch (Exception er) { - Utils.logStackTrace(er, TAG); - } - - - - } - - - - - @Override - void processGetJsonObject(String method, JSONObject jsonObject, String msg) - throws JSONException, NullPointerException, NoWebObjectException { - - super.processGetJsonObject(method, jsonObject, msg); - - if (method.equalsIgnoreCase(RestMethods.NOTEMSG_G_FIND_BY_ID)) { - - // activity.showNoteDetail(null, - // (NoteMessage)Utils.getGsonObject(jsonObject.toString(), - // NoteMessage.class)); - - currentNote = null; - currentMsg = (NoteMessage) Utils.getGsonObject( - jsonObject.toString(), NoteMessage.class); - setMsgDetail(); - - } - } - - - - @Override - void showActivity(Activity_bean act) { - activity.app.getWebObjcache().put(cacheKey, act); - super.showActivity(act); - } - - @Override - void showWebTrack(Track tr) { - activity.app.getWebObjcache().put(cacheKey, tr); - super.showWebTrack(tr); - } - - @Override - void showGroup(Group_bean group) { - activity.app.getWebObjcache().put(cacheKey, group); - super.showGroup(group); - } - - @Override - void showMember(User_bean user) { - activity.app.getWebObjcache().put(cacheKey, user); - super.showMember(user); - } - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteList.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteList.java deleted file mode 100644 index 9eeedd2..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteList.java +++ /dev/null @@ -1,520 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.content.DialogInterface; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnClickListener; -import android.widget.AdapterView; -import android.widget.Button; -import android.widget.ListView; -import android.widget.AdapterView.OnItemClickListener; - -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.Note; -import com.qiyou.mb.android.beans.basic.NoteMessage; -import com.qiyou.mb.android.ui.fragments.Querybase_fragment.ListviewOnScroll; -import com.qiyou.mb.android.utils.ImageLoader; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.exception.NoWebObjectException; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; - -public class NoteList extends Querybase_fragment { - - @Override - public void setFTag() { - TAG = "com.qiyou.NoteList"; - } - - public static String getFTag() { - return "com.qiyou.NoteList"; - } - - @Override - public String getCurrentTag() { - return "com.qiyou.NoteList"; - } - - public static NoteList newInstance() { - NoteList f = new NoteList(); - return f; - } - public static NoteList newInstance(int cate,int subCate) { - NoteList f = new NoteList(); - f.BBScate = cate; - f.BBSSubcate = subCate; - return f; - } - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - activity.updateActionBarTitle(R.string.frg_notes); - - vContainer = inflater.inflate(R.layout.notes_list, container, false); - initialView(); - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - pageSize=20; -// doNoteQuery(); - } - int BBScate = 0; - int BBSSubcate = 0; - int BBSSubcateOwner = 0; - String BBSsubCateName = ""; - - NoteMessage currentMsg; - Note currentNote; - ListView lvNotes =null; - int selectNotesItem =0; - boolean isNoteQuery ; - String lastNoteQueryPara; - int notesPageNo; - int noteId; - int svrNo; - List> noteData; - Button btnNew , btnDel; ;//,btnRefresh; - @Override - protected void initialView() { - IL = new ImageLoader(activity); -// lvNotes =(ListView)vContainer.findViewById(R.id.listNotes); -// lvNotes.setOnScrollListener( new ListviewOnScroll()); -// lvNotes.setOnItemClickListener(itemListener); - - initialLoadingMore(); - btnNew=(Button)vContainer.findViewById(R.id.btn_newNote); -// btnRefresh=(Button)vContainer.findViewById(R.id.btn_refreshNotes); -// btnRefresh.setOnClickListener(ButtonOnClickListener); - btnNew.setOnClickListener(ButtonOnClickListener); - - } - - protected OnClickListener ButtonOnClickListener = new OnClickListener() { - @Override - public void onClick(View view) { - switch (view.getId() ){ - case R.id.btn_newNote: {postNewNote();break;} -// case R.id.btn_refreshNotes: {initialNotesQuery() ;break;} - case R.id.btn_delNote: {delNote() ;break;} - case R.id.btn_editNote: {editNote() ;break;} - - }}}; - - - void editNote(){} - void postNewNote(){ - activity.showNewNote(currentNote); - } - - public void setCurrentMsg(NoteMessage msg){ - currentMsg=msg; - } - public void setCurrentNote(Note note){ - currentNote=note; - } - - - boolean canclick=true; - -// -// OnItemClickListener itemListener = new OnItemClickListener() { -// @Override -// public void onItemClick(AdapterView parent, View view, int position, long id) { -// -// QLog.getLogger().d(dTAG, String.format("adapter count %s,postion is %s", parent.getCount(),position)); -// -// if(parent.getCount()==position+1 || !canclick)return; -// canclick =false; -// -// lastIndexOnMore =-1; -//// isLoadMoreIndex =false; -// selectNotesItem =position; -// if (isNoteQuery) { -// showNoteDetail(position) ; -// canclick =true; -// return; -// } -// }}; - - - void doNoteQuery(){ - Utils.hideSoftKeyboard(activity); - - isNoteQuery=true; -// lvWeb.setVisibility(View.VISIBLE); -// lv.setVisibility(View.GONE); - QLog.getLogger().d(dTAG, TAG+"------begin Note query--------- "); - - - /* if( - this.firstLoad&&!TextUtils.isEmpty(lastNoteQueryPara)){ - return; - }*/ - RequestParams param=buildNotesQueryParames(0,0); - if(param!=null ) { - - QLog.getLogger().d(dTAG, lastNoteQueryPara); - QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param,RestMethods.NOTE_G_LIST /*"mb/user/actusers"*/); - - selectNotesItem =-1; - - - } - - } - - RequestParams buildNotesQueryParames(int ownerId,int svrNo){ - RequestParams params = new RequestParams(); - - params.add("ownerId", String.valueOf(ownerId)); - params.add("page", String.valueOf(notesPageNo)); - params.add("pagesize", String.valueOf(pageSize)); - params.add("svrNo", String.valueOf( svrNo)); - - - return params; - - } - - - void showNoteDetail(int position){ - try{ - this.notesSimpleAdapter.setSelectItem(position); - this.notesSimpleAdapter.notifyDataSetInvalidated(); - this.lvNotes.setSelection(position); - HashMap localHashMap = (HashMap)this.notesSimpleAdapter.getItem(position); - noteId = Integer.parseInt(localHashMap.get("id")) ; - - QLog.getLogger().d("com.qiyou", TAG + " get selected noteId:" + this.noteId); - - }catch(NumberFormatException ne ){ - Utils.logStackTrace(ne, TAG); - showNotes("出错了"); - return; - } - catch (java.lang.IndexOutOfBoundsException IndexException){ - Utils.logStackTrace(IndexException, TAG); - } - catch (Exception er){ - Utils.logStackTrace( er, TAG); - } - - requestNoteFromWeb(noteId); - - } - - - void requestNoteFromWeb(int noteId){ - if(noteId<=0) return; - RequestParams params = new RequestParams() ; - params.add("id", String.valueOf(noteId)); - getJsonWs(params, RestMethods.NOTE_G_FIND_BY_ID); - } - - - - void processNotesJsonArray(JSONArray jsonArrary){ - ArrayList> tmpData = new ArrayList>(); - JSONObject jo = null; - Note ab; - - if(jsonArrary!=null) - for(int i=0;i " +jo.toString()); - ab=(Note) Utils.getGsonObject(jo.toString(), Note.class); - - }catch( JsonSyntaxException je){ - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - - if(ab!=null){ - Map t = new HashMap(); - t.put("title", ab.getTitle()/*.getAccount()*/); - t.put("id", String.valueOf(ab.getId())); - t.put("body",ab.getBody()); - t.put("username",ab.getUserName()/*ab.getOwner()!=null?ab.getOwner().getUserName():""*/); - t.put("created", Utils.getFormatedTime(ab.getCreated())); - t.put("replycnt", ab.getReplyCnt() +""); - t.put("lastreply",ab.getLastupdated() >ab.getCreated() ?ab.getLastReplyer():""); - - tmpData.add(t); - } - - } - - noteData = getListData(noteData,tmpData); - - showNoRecText(noteData.size()==0); - - showNoteData(); - - QLog.getLogger().e(dTAG, String.format("notesPageNo is%s, actual pageno is %s ",notesPageNo,noteData.size()/pageSize)); - - } - - QSimpleAdapter notesSimpleAdapter; - - int currentUserRow=0; - protected void showNoteData( ){ - - notesSimpleAdapter = new QSimpleAdapter(activity,noteData,R.layout.notes_list_detail, - new String[]{ - "title", - "body" - ,"id" - ,"username" - ,"created" - ,"replycnt" - ,"lastreply" - }, - new int[]{ - R.id.list_note_name, - R.id.list_note_body - , R.id.list_note_id - ,R.id.list_note_username - ,R.id.list_note_created - ,R.id.list_note_reply_cnt - ,R.id.list_note_reply_user - }); - - - bindListView(notesSimpleAdapter,lvNotes,selectNotesItem,isNotesLastPage); - - lvNotes.setDividerHeight(2); - - } - - - boolean isNotesLastPage; - - - void processNotesPageInfo(JSONObject jo) throws JSONException{ - if(jo==null){ - processGrpJsonArray(null); - return; - } - isNotesLastPage =jo.getBoolean("last"); -// isGrpFirstPage =jo.getBoolean("first"); - QLog.getLogger().d(dTAG, TAG+" isNoteLastPage--- " + isNotesLastPage); - - processNotesJsonArray(jo.getJSONArray("content")); - } - - /* - @Override - void processGetJsonObject(String method,JSONObject jsonObject,String msg) throws JSONException,NullPointerException, NoWebObjectException { - - super.processGetJsonObject(method, jsonObject, msg); - - if(method.equalsIgnoreCase(RestMethods.NOTE_G_LIST) ||method.equalsIgnoreCase(RestMethods.NOTEMSG_G_LIST) ) { - - if(checkJsonArray(jsonObject)){ - - - QLog.getLogger().d(dTAG, TAG+"------get notes web query data--------- "); - QLog.getLogger().d(dTAG, TAG+" notes : "+jsonObject.toString()); - - processNotesPageInfo(jsonObject ); - - } - - }else if(method.equalsIgnoreCase(RestMethods.NOTE_G_FIND_BY_ID) ) { - - activity.showNoteDetail( (Note)Utils.getGsonObject(jsonObject.toString(), Note.class),null); - - } - - } - */ - - @Override - void loadingMore(){ - - QLog.getLogger().d(dTAG, "------ can loading more 2 .. " + canLoadingMore); - - isLoadingMore =true; -// isLoadMoreIndex=true; - lastIndexOnMore =visibleLastIndex; - if(isNoteQuery){ -// lastGrpQueryPara=""; - notesPageNo++; - doNoteQuery(); - } - - - - } - - void initialNotesQuery(){ - notesPageNo=1; - doNoteQuery(); - } - - - @Override - public void onResume() { - - initialNotesQuery(); - super.onResume(); - } - - - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } - - @Override - public void doQuery() { - // TODO Auto-generated method stub - this.initialNotesQuery(); - } - - void delNote() { - -// if (canDelete()) { - - final JSONObject json = new JSONObject(); - - int id = currentNote == null ? currentMsg.getId() : currentNote - .getId(); - final String method = currentNote == null ? RestMethods.NOTEMSG_P_DEL - : RestMethods.NOTE_P_DEL; - try { - json.put("noteId", id); - - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - AlertDialog.Builder builder = new Builder(activity); - builder.setMessage("确认删除吗?"); - builder.setTitle("提示"); - builder.setCancelable(false); - builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - - postJsonWS(json.toString(), method); - - - } - }); - builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - }); - builder.create().show(); - - - -// } - - } - @Override - void processJsonObject(String method, JSONObject response, String msg) - throws JSONException { - - /* - * QLog.getLogger().d(dTAG,"发布成功!" ); QLog.getLogger().d(dTAG, - * response.toString() ); Toast.makeText(activity, "删除成功!", - * Toast.LENGTH_LONG).show(); - */ - - this.showNotes(msg); - if (method.equalsIgnoreCase(RestMethods.NOTE_P_DEL) - || method.equalsIgnoreCase(RestMethods.NOTEMSG_P_DEL)) { // LEAVE - // activity,group - if (Boolean.valueOf(response.getString(QiYouConstant.SIMPLE_KEY))) { - // success - activity.isNeedFresh=true; - onBack(); - - } - } -// btnSubmit.setEnabled(true); - - else if(method.equalsIgnoreCase(RestMethods.NOTE_P_IMPORT) || method.equalsIgnoreCase(RestMethods.NOTEMSG_P_IMPORT) ) { //LEAVE activity,group - if(Boolean.valueOf(response.getString(QiYouConstant.SIMPLE_KEY))){ - - activity.isNeedFresh=true; - onBack(); //success - - } - } - - } - - boolean canDelete(){ - return (this.currentNote != null && (currentNote.getUserId() == this - .getUser().getId() || isAdmin())) - || (this.currentMsg != null && (currentMsg.getUserId() == this - .getUser().getId() - || isAdmin())) - || this.currentNote != null && (currentNote.getCateOwnerId() == this - .getUser().getId()); - } - boolean canEdit() { - return canDelete() ; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteNew.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteNew.java deleted file mode 100644 index 75ac70e..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/NoteNew.java +++ /dev/null @@ -1,451 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.graphics.Color; -import android.graphics.Typeface; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.Spinner; -import android.widget.TextView; - -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.Note; -import com.qiyou.mb.android.beans.basic.NoteMessage; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; - -import org.json.JSONException; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -public class NoteNew extends NoteList { - - @Override - public void setFTag() { - TAG = "com.qiyou.NoteNew"; - } - - public static String getFTag() { - return "com.qiyou.NoteNew"; - } - - @Override - public String getCurrentTag() { - return "com.qiyou.NoteNew"; - } - - private CheckBox chkMainTop, chkCateTop, chkTop, chkNoReply; // bbs_chk_main_top - boolean isEdit; - - public static NoteNew newInstance(Note note) { - NoteNew f = new NoteNew(); - f.currentNote = note; - f.isEdit = false; - return f; - } - - public static NoteNew newInstance(Note note, NoteMessage currentMsg) { - NoteNew f = new NoteNew(); - f.currentNote = note; - f.currentMsg = currentMsg; - f.isEdit = true; - return f; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - } - - boolean isReply; - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - if (isEdit) { - if (currentMsg != null) { - editTitle.setVisibility(View.GONE); - editBody.setText(currentMsg.getBody()); - - } else if (currentNote != null) { - editTitle.setVisibility(View.VISIBLE); - editTitle.setText(currentNote.getTitle()); - editBody.setText(currentNote.getBody()); - - } - } else { - - editTitle.setVisibility(isReply ? View.GONE : View.VISIBLE); - } - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - // if(vContainer==null) - // vContainer = inflater.inflate(R.layout.trackingbasic_fragment, - // container, false); - activity.updateActionBarTitle(isEdit ? R.string.frg_noteEdit - : R.string.frg_noteNew); - vContainer = inflater.inflate(R.layout.notes_new, container, false); - initialViews(); - - return vContainer; - } - - EditText editTitle, editBody; - Button btnSubmit; - - void initialViews() { - isReply = !isEdit && currentNote.getId() > 0; - editTitle = (EditText) vContainer.findViewById(R.id.edit_note_title); - editBody = (EditText) vContainer.findViewById(R.id.edit_note_detail); - btnSubmit = (Button) vContainer.findViewById(R.id.btn_submitNote); - editTitle.setVisibility(currentNote == null ? View.VISIBLE - : View.INVISIBLE); - btnDel = (Button) vContainer.findViewById(R.id.btn_delNote); - btnDel.setOnClickListener(ButtonOnClickListener); - btnSubmit.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - - try { - Utils.hideSoftKeyboard(activity); - - if (isEdit) { - if (currentNote == null) { - submitNoteMsg(); - } else { - submitNote(); - } - - } else if (currentNote == null || currentNote.getId() == 0) { - submitNote(); - } else { - submitNoteMsg(); - } - - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }); - - // chkMainTop,chkCateTop,chkTop; - - chkMainTop = (CheckBox) vContainer.findViewById(R.id.bbs_chk_main_top); - chkCateTop = (CheckBox) vContainer.findViewById(R.id.bbs_chk_cate_top); - chkTop = (CheckBox) vContainer.findViewById(R.id.bbs_chk_top); - chkNoReply = (CheckBox) vContainer.findViewById(R.id.bbs_chk_noreply); - - // if ( isReply || currentNote == null ){ - - btnDel.setVisibility(currentMsg != null? View.VISIBLE - : View.GONE); - chkMainTop.setVisibility(View.GONE); - chkCateTop.setVisibility(View.GONE); - chkTop.setVisibility(View.GONE); - this.chkNoReply.setVisibility(View.GONE); - - // } - - if (currentMsg != null) { - - boolean enable = currentMsg.getUserId() == activity.app.user.getUserbean().getId() || isAdmin() ; - editBody.setEnabled(enable); - editTitle.setEnabled(enable); - btnSubmit.setEnabled(enable); - - } else if (!isReply && currentNote != null) { - - vContainer.findViewById(R.id.txtbbsCate) - .setVisibility(View.VISIBLE); - spWebInputType = (Spinner) vContainer.findViewById(R.id.sp_bbsCate); - spWebInputType.setVisibility(View.VISIBLE); - initialSpCate(); - spWebInputType.setSelection(currentNote.getCategory()); - // spWebInputType.setEnabled(isEdit); - - // below is for check box - chkMainTop.setChecked(currentNote.getMainPriority() > 0); - chkCateTop.setChecked(currentNote.getCatePriority() > 0); - chkTop.setChecked(currentNote.getPriority() > 0); - chkNoReply.setChecked(currentNote.getStatus() > 0); - - if (!this.isAdmin() && currentNote.getStatus() > 1) { // than author - // can do - this.chkNoReply.setVisibility(View.GONE); - } - - if (isAdmin()) { - chkMainTop.setVisibility(View.VISIBLE); - chkCateTop.setVisibility(View.VISIBLE); - chkTop.setVisibility(View.VISIBLE); - this.chkNoReply.setVisibility(View.VISIBLE); - return; - } - - if (currentNote.getCateOwnerId() == activity.app.user.getUserbean() - .getId()) { // its subcate owner - // int visible = currentNote.getId() > 0 ? View.VISIBLE : - // View.GONE; - chkTop.setVisibility(View.VISIBLE); - if (currentNote.getStatus() == 2 - || currentNote.getStatus() == 0) { - chkNoReply.setVisibility(View.VISIBLE); - } - - spWebInputType.setVisibility(View.GONE); - vContainer.findViewById(R.id.txtbbsCate).setVisibility( - View.GONE); - - } - - if (currentNote.getUserId() == activity.app.user.getUserbean() - .getId()) { // note owner - - spWebInputType.setVisibility(View.VISIBLE); - vContainer.findViewById(R.id.txtbbsCate).setVisibility( - View.VISIBLE); - - if (currentNote.getStatus() <= 1) { - this.chkNoReply.setVisibility(View.VISIBLE); - } - } else { // subcate owner can't edit other's msg, but can del - // vContainer.findViewById( - // R.id.btn_delNote).setVisibility(View.GONE); - // btnSubmit.setVisibility(View.GONE); - editBody.setEnabled(false); - editTitle.setEnabled(false); - - } - - } - - } - - public void submitNoteMsg() throws JSONException, - UnsupportedEncodingException { - NoteMessage msg; - if (isEdit) { - msg = currentMsg; - - - } else { - msg = new NoteMessage(); - msg.setUserId(activity.app.user.getUserbean().getId()); -// msg.setUserAlbum(activity.app.user.getUserbean().getAlbum()); - msg.setParentId(0); - msg.setCateOwnerId(currentNote.getCateOwnerId()); - msg.setNoteId(currentNote.getId()); - msg.setTitle(currentNote.getTitle()); - - } - msg.setNoteOwnerId(currentNote.getUserId()); - msg.setLastEditBy(getAuditInfo()); - String s = editBody.getText().toString(); - if (!TextUtils.isEmpty(msg.getBody()) - && msg.getBody().equalsIgnoreCase(s)) { - this.showNotes("没有更改需要提交", true); - return; - // super.onBack(); - } - msg.setBody(s); - if (TextUtils.isEmpty(msg.getBody().trim())) { - this.showNotes("请输入内容", true); - editBody.requestFocus(); - editBody.setHintTextColor(Color.RED); - return; - } - - btnSubmit.setEnabled(false); - postJsonWS(Utils.getGsonString(msg), RestMethods.NOTEMSG_P_IMPORT); - - QLog.getLogger().d(dTAG, "REPLY。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"); - - QLog.getLogger().d(dTAG, Utils.getGsonString(msg)); - - } - - private String getAuditInfo() { - return activity.app.user.getUserbean().getUserName() + "(" - + activity.app.user.getUserbean().getId() + ")"; - } - - public void submitNote() throws JSONException, UnsupportedEncodingException { - - Note note; - if (isEdit) { - note = currentNote; - note.setLastEditBy(getAuditInfo()); - } else { - - note = currentNote == null ? new Note() : currentNote; - note.setUserId(activity.app.user.getUserbean().getId()); -// note.setUserAlbum(activity.app.user.getUserbean().getAlbum()); - } - - note.setBody(editBody.getText().toString()); - note.setTitle(editTitle.getText().toString()); - - note.setPriority(this.chkTop.isChecked() ? 1 : 0); - note.setCatePriority(this.chkCateTop.isChecked() ? 1 : 0); - note.setMainPriority(this.chkMainTop.isChecked() ? 1 : 0); - int noreply = activity.app.user.getUserbean().isPower() ? 3 - : isSubCateOwner() ? 2 : 1; - note.setStatus(this.chkNoReply.isChecked() ? noreply : 0); - - int selectedItem = this.spWebInputType.getSelectedItemPosition(); - // int selctedCate =BBSCate.values()[ selectedItem].toInt(); - note.setCategory(selectedItem); - - if (TextUtils.isEmpty(note.getTitle().trim())) { - this.showNotes("请输入标题", true); - editTitle.requestFocus(); - editTitle.setHintTextColor(Color.RED); - return; - } - if (TextUtils.isEmpty(note.getBody().trim()) - || note.getBody().trim().length() < 5) { - this.showNotes("请输入内容(5-500个字)", true); - editBody.requestFocus(); - editBody.setHintTextColor(Color.RED); - return; - } - - btnSubmit.setEnabled(false); - postJsonWS(Utils.getGsonString(note), RestMethods.NOTE_P_IMPORT); - - QLog.getLogger().d(dTAG, "发布。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"); - - QLog.getLogger().d(dTAG, Utils.getGsonString(note)); - - } - - private boolean isSubCateOwner() { - return currentNote != null - && currentNote.getCateOwnerId() == activity.app.user - .getUserbean().getId(); - } - - @Override - void updateUIOnRequestResonsed(String method) { - btnSubmit.setEnabled(true); - } - - private void initialSpCate() { - // String BBSCity= - // activity.app.user.getUserbean().getGeo().getCityName(); - // //.getGeo().getCityName(); - // if (BBSCity == null || TextUtils.isEmpty(BBSCity)){ - // BBSCity = "地方论坛"; - // - // }; - - // case 0:{return "聚义厅";} - // case 1:{return "活动";} - // case 2:return "队伍"; - // case 3:return "轨迹"; - // case 4:return "驴友"; - // case 5:return "地区"; - // case 6:return "软件使用"; - // case 7:return "运动装备"; - // case 8:return "问题反馈"; - // case 9:return "骑行天地"; - // case 10:return "跑友交流"; - // case 11:return "徒步户外"; - // - // default: return "聚义厅"; - // } - - // String[] bbsCates = { "默认", - // BBSCity,"我的","软件使用","骑行天地","跑友交流","徒步户外","活动相关","队伍相关", - // "车辆装备","问题反馈"}; - List cateList = new ArrayList(); - - for (BBSCate bbscate : BBSCate.values()) { - cateList.add(bbscate.toCHString()); - } - - // List cateList = Arrays.asList(bbsCates); - - spAdapterWeb = new ArrayAdapter(activity, R.layout.myspinner, - cateList) { - @Override - public View getDropDownView(int position, View convertView, - ViewGroup parent) { - TextView v = (TextView) super.getView(position, convertView, - parent); - // v.setMinimumHeight((int) (200* - // getResources().getDisplayMetrics().density)); - - v.setBackgroundResource(R.drawable.linearlayout_horizontal); - - // v.setTextAppearance(activity, R.style.ll_text_view_1); - v.setPadding(5, 8, 5, 8); - int selected = spWebInputType.getSelectedItemPosition(); - if (position == selected) { - v.setTypeface(null, Typeface.BOLD); - v.setBackgroundResource(R.drawable.head_linearlayout); - } - // - // v.getPaint().setFlags(0); - // v.setTypeface(null, Typeface.BOLD); - // LayoutParams lp = new LayoutParams(); - - v.setLayoutParams(new android.widget.AbsListView.LayoutParams( - LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); - return v; - } - };// ArrayAdapter.createFromResource( activity,R.array.webInputType, - // R.layout.thinspinner); - - // 设置下拉列表的风格 - spAdapterWeb.setDropDownViewResource(R.layout.spinner_item); - - // 将adapter2 添加到spinner中 - try { - spWebInputType.setAdapter(spAdapterWeb); - } catch (Exception e) { - Utils.logStackTrace(e, "bbs"); - } - } - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } - - @Override - void initialNotesQuery() { - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/OfflineMaps_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/OfflineMaps_fragment.java deleted file mode 100644 index 5129b27..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/OfflineMaps_fragment.java +++ /dev/null @@ -1,494 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.util.ArrayList; - -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; - -import com.baidu.mapapi.map.offline.MKOLSearchRecord; -import com.baidu.mapapi.map.offline.MKOLUpdateElement; -import com.baidu.mapapi.map.offline.MKOfflineMap; -import com.baidu.mapapi.map.offline.MKOfflineMapListener; - -import com.baidu.mapapi.map.MapView; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.ui.fragments.QiyouFragment; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - -public class OfflineMaps_fragment extends QiyouFragment { - -// public static String TAG="com.qiyou.OfflineMaps_fragment"; -// public static String dTAG="com.qiyou"; - -// implements MKOfflineMapListener { - - - - @Override - public void setFTag(){ - TAG="com.qiyou.OfflineMaps_fragment"; - } - - public static String getFTag(){ - return "com.qiyou.OfflineMaps_fragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.OfflineMaps_fragment"; - } -// MainActivity activity; - private View vContainer; - boolean isPlayback =false; - -// private MapView mMapView = null; - private MKOfflineMap mOffline = null; - private TextView cidView; - private TextView stateView; - private EditText cityNameView; -// private MapController mMapController = null; - /** - * 宸蹭笅杞界殑绂荤嚎鍦板浘淇℃伅鍒楄〃 - */ - private ArrayListlocalMapList =null; - private LocalMapAdapter lAdapter = null; - - public static OfflineMaps_fragment newInstance( ) - { - OfflineMaps_fragment f = new OfflineMaps_fragment(); - return f; - } - - - - public OfflineMaps_fragment() { - // TODO Auto-generated constructor stub - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - activity.updateActionBarTitle(R.string.frg_offlinemap); -// activity=(MainActivity)getActivity(); -// activity.app.currentActiveFragment =TAG; - vContainer = inflater.inflate(R.layout.offlinemaps_fragment, container, false); - initialView(); - - this.vContainer. setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - - } - - private Button btnStart; - private Button btnStop; - private Button btnOffSearch; -// private Button btnOffScan; -// private Button btnDel; -// private Button btnCityList; -// private Button btnlcoalMapList; - void initialView(){ - -// mMapView = activity.app.mMapview; - -// mMapController = mMapView.getController(); - -// mOffline = new MKOfflineMap(); - /** - * 初始化离线地图模块,MapControler可从MapView.getController()获取 - */ - /*mOffline.init(mMapController, new MKOfflineMapListener() { - @Override - public void onGetOfflineMapState(int type, int state) { - switch (type) { - case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: - { - MKOLUpdateElement update = mOffline.getUpdateInfo(state); - //mText.setText(String.format("%s : %d%%", update.cityName, update.ratio)); - //处理下载进度更新提示 - if ( update != null ){ - stateView.setText(String.format("%s : %s , %d%%", update.cityName,formatDataSize(update.size), update.ratio)); - updateView(); - } - } - break; - case MKOfflineMap.TYPE_NEW_OFFLINE: - QLog.getLogger().d(dTAG, String.format("add offlinemap num:%d", state)); - break; - case MKOfflineMap.TYPE_VER_UPDATE: - QLog.getLogger().d(dTAG, String.format("new offlinemap ver")); - break; - } - } - } - ); - localMapList = mOffline.getAllUpdateInfo(); - if ( localMapList == null ){ - localMapList = new ArrayList(); - } - */ - - initialOffMap(); - - ListView localMapListView = (ListView)vContainer.findViewById(R.id.localmaplist); - lAdapter = new LocalMapAdapter(); - localMapListView.setAdapter(lAdapter); - - cidView = (TextView)vContainer.findViewById(R.id.off_cityid); - cityNameView = (EditText)vContainer.findViewById(R.id.off_city); - stateView = (TextView)vContainer.findViewById(R.id.off_state); - - btnStart = (Button) vContainer.findViewById(R.id.off_start); - btnStop = (Button) vContainer.findViewById(R.id.off_stop); -// btnDel =(Button) vContainer.findViewById(R.id.off_del); - btnOffSearch = (Button) vContainer.findViewById(R.id.off_search); -// btnOffScan = (Button) vContainer.findViewById(R.id.off_scan); -// btnCityList = (Button) vContainer.findViewById(R.id.off_clButton); -// btnlcoalMapList = (Button) vContainer.findViewById(R.id.off_localButton); -// btnlcoalMapList.setOnClickListener(ButtonOnClickListener); - -// btnCityList.setOnClickListener(ButtonOnClickListener); - btnStart.setOnClickListener(ButtonOnClickListener); - btnStop.setOnClickListener(ButtonOnClickListener); -// btnOffScan.setOnClickListener(ButtonOnClickListener); - btnOffSearch.setOnClickListener(ButtonOnClickListener); -// btnDel.setOnClickListener(ButtonOnClickListener); - if(activity.app.getGEOinfo()!=null){ - cidView.setText(activity.app.getGEOinfo().getCityId()); - cityNameView.setText(activity.app.getGEOinfo().getCity()); - } - if(TextUtils.isEmpty(cidView.getText())){ - cidView.setText("224"); -// cityNameView.setText("苏州"); - } - this.btnStart.setEnabled(false); - this.btnStop.setEnabled(false); - } - - - - void initialOffMap(){ -// mMapView = new MapView(new Activity()); - - QLog.getLogger().d(dTAG, " offmap update... initializing mapview"); - - /* mMapView = app.mMapview; - - if(mMapView ==null){ - stopSelf(); - return; - }*/ - -// mMapController = mMapView.getController(); - - mOffline = new MKOfflineMap(); - /** - * 初始化离线地图模块,MapControler可从MapView.getController()获取 - */ - -// mOffline.init(mMapController, this); - - mOffline.init(/*mMapController,*/ mylistener); - - - //获取已下过的离线地图信息 - localMapList = mOffline.getAllUpdateInfo(); - if ( localMapList == null ){ - localMapList = new ArrayList(); - } - } - - - MKOfflineMapListener mylistener = new MKOfflineMapListener() { - - @Override - public void onGetOfflineMapState(int type, int state) { - /* switch (type) { - case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: - { - MKOLUpdateElement update = mOffline.getUpdateInfo(state); - if ( update != null ){ - ratio =update.ratio; -// stateView.setText(String.format("%s : %d%%", update.cityName, update.ratio)); -// updateView(); - } - } - break; - case MKOfflineMap.TYPE_NEW_OFFLINE: -// QLog.getLogger().d(dTAG, String.format("add offlinemap num:%d", state)); - break; - case MKOfflineMap.TYPE_VER_UPDATE: -// QLog.getLogger().d(dTAG, String.format("new offlinemap ver")); - break; - } */ - - switch (type) { - case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: - { - MKOLUpdateElement update = mOffline.getUpdateInfo(state); - //mText.setText(String.format("%s : %d%%", update.cityName, update.ratio)); - //处理下载进度更新提示 - if ( update != null ){ - stateView.setText(String.format("%s : %s , %d%%", update.cityName,formatDataSize(update.size), update.ratio)); - updateView(); - } - } - break; - case MKOfflineMap.TYPE_NEW_OFFLINE: - QLog.getLogger().d(dTAG, String.format("add offlinemap num:%d", state)); - break; - case MKOfflineMap.TYPE_VER_UPDATE: - QLog.getLogger().d(dTAG, String.format("new offlinemap ver")); - break; - } - - - } - - - }; - - - - protected OnClickListener ButtonOnClickListener = new OnClickListener() { - @Override - public void onClick(View view) { - switch (view.getId() ){ - case R.id.off_start: {start();break;} - case R.id.off_search:{search();break;} -// case R.id.off_scan:{importFromSDCard();break;} - case R.id.off_stop:{stop();break;} -// case R.id.off_del:{remove();break;} -// case R.id.off_clButton:{clickCityListButton();break;} -// case R.id.off_localButton:{clickLocalMapListButton();break;} - } - - } - }; - - - - /** - * 搜索离线需市 - * @param view - */ -// public void search(View view){ - public void search( ){ - ArrayList records = mOffline.searchCity(cityNameView.getText().toString()); - if (records == null || records.size() != 1){ - this.btnStart.setEnabled(false); - this.btnStop.setEnabled(false); - return; - } - this.btnStart.setEnabled(true); - this.btnStop.setEnabled(true); - cidView.setText(String.valueOf(records.get(0).cityID)); - stateView.setText(String.format("离线包大小%s", formatDataSize(records.get(0).size))); - } - - /** - * 切换至下载管理列表 - * @param view - */ -// public void clickLocalMapListButton(View view){ - public void clickLocalMapListButton(){ -// LinearLayout cl = (LinearLayout)vContainer.findViewById(R.id.off_citylist_layout); -// LinearLayout lm = (LinearLayout)vContainer.findViewById(R.id.off_localmap_layout); -// lm.setVisibility(View.VISIBLE); -// cl.setVisibility(View.GONE); - } - /** - * 开始下载 - * @param view - */ -// public void start(View view){ - public void start(){ - int cityid = Integer.parseInt(cidView.getText().toString()); - mOffline.start(cityid); - clickLocalMapListButton(); - Toast.makeText(activity, "开始下载离线地图. cityid: "+cityid, Toast.LENGTH_SHORT) - .show(); - } - /** - * 暂停下载 - * @param view - */ -// public void stop(View view){ - public void stop( ){ - int cityid = Integer.parseInt(cidView.getText().toString()); - mOffline.pause(cityid); - Toast.makeText(activity, "暂停下载离线地图. cityid: "+cityid, Toast.LENGTH_SHORT) - .show(); - } - /** - * 删除离线地图 - * @param view - */ -// public void remove(View view){ - public void remove(){ - int cityid = Integer.parseInt(cidView.getText().toString()); - mOffline.remove(cityid); - Toast.makeText(activity, "删除离线地图. cityid: "+cityid, Toast.LENGTH_SHORT) - .show(); - } - /** - * 从SD卡导入离线地图安装包 - * @param view - */ -// public void importFromSDCard(View view){ - /* public void importFromSDCard( ){ - int num = mOffline.scan(); - String msg = ""; - if ( num == 0){ - msg = "没有导入离线包,这可能是离线包放置位置不正确,或离线包已经导入过"; - } - else{ - msg = String.format("成功导入 %d 个离线包,可以在下载管理查看",num); - } - Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show(); - }*/ - /** - * 更新状态显示 - */ - public void updateView(){ - localMapList = mOffline.getAllUpdateInfo(); - if ( localMapList == null ){ - localMapList = new ArrayList(); - } - lAdapter.notifyDataSetChanged(); - } - - - - @Override - public void onPause() { - - int cityid = Integer.parseInt(cidView.getText().toString()); - mOffline.pause(cityid); -// mMapView.onPause(); - super.onPause(); - } - - @Override - public void onResume() { -// mMapView.onResume(); - super.onResume(); - } - - - public String formatDataSize(int size) { - String ret = ""; - if (size < (1024 * 1024)) { - ret = String.format("%dK", size / 1024); - } else { - ret = String.format("%.1fM", size / (1024 * 1024.0)); - } - return ret; - } - - class LocalMapAdapter extends BaseAdapter{ - - @Override - public int getCount() { - return localMapList.size(); - } - - @Override - public Object getItem(int index) { - return localMapList.get(index); - } - - @Override - public long getItemId(int index) { - return index; - } - - @Override - public View getView(int index, View view, ViewGroup arg2) { - MKOLUpdateElement e = (MKOLUpdateElement) getItem(index); - view = View.inflate(activity, R.layout.offline_localmap_list,null); - initViewItem(view,e); - return view; - } - - void initViewItem(View view , final MKOLUpdateElement e){ - Button btnUpdate = (Button)view.findViewById(R.id.off_btnupdate); - Button remove = (Button)view.findViewById(R.id.off_remove); - TextView title = (TextView)view.findViewById(R.id.off_title); - TextView update = (TextView)view.findViewById(R.id.off_update); - TextView ratio = (TextView)view.findViewById(R.id.off_ratio); - ratio.setText(e.ratio+"%"); - title.setText(e.cityName); - if ( e.update){ - update.setText("待更新"); - } - else{ - update.setText("最新"); - } - if ( e.update || e.ratio != 100 ){ - btnUpdate.setEnabled(true); - if(e.ratio != 100){ - btnUpdate.setText("继续"); - } - } - else{ - btnUpdate.setEnabled(false); - } - remove.setOnClickListener(new OnClickListener(){ - @Override - public void onClick(View arg0) { - mOffline.remove(e.cityID); - updateView(); - } - }); - btnUpdate.setOnClickListener(new OnClickListener(){ - @Override - public void onClick(View v) { - mOffline.start(e.cityID); - } - }); - } - - } - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Playback_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Playback_fragment.java deleted file mode 100644 index 051632e..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Playback_fragment.java +++ /dev/null @@ -1,442 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.content.Intent; -import android.location.Location; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageButton; -import android.widget.LinearLayout; -import android.widget.SeekBar; -import android.widget.SeekBar.OnSeekBarChangeListener; -import android.widget.TextView; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.service.QNaviSvc; -import com.qiyou.mb.android.service.TrackPlaybackService; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.enums.WorkingTrackType; -import com.qiyou.mb.android.utils.log.QLog; - -public class Playback_fragment extends Track_fragment implements IlocationFragment { -// public static final String TAG ="com.qiyou.Playback_fragment"; - @Override - public void setFTag(){ - TAG="com.qiyou.Playback_fragment"; - } - public static String getFTag(){ - return "com.qiyou.Playback_fragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.Playback_fragment"; - } -// boolean isStartPlay =false; -// boolean isPlayPause =false; - int playbackID =0; - public Playback_fragment() { - // TODO Auto-generated constructor stub - workingTrackType= WorkingTrackType.PLAYBACK; - } - public static Playback_fragment newInstance(int trackId) - { - Playback_fragment f = new Playback_fragment(); - if( trackId<=0) return f; - Bundle args = new Bundle(); - args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId); - f.setArguments(args); - return f; - } - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); -// activity.app.currentActiveFragment =TAG; -// currentLayout =R.layout.playbackmap_fragment; -// activity.app.playbackPaused = true; - if(activity==null){ - activity = (com.qiyou.mb.android.ui.MainActivity)getActivity(); - } - isPlaying=true; - - } - private TextView tbs_playback_time; - - private String PLAY_START; - private String PLAY_END; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - isPlayback =activity.app.playBack; -// if(vContainer==null) -// vContainer = inflater.inflate(R.layout.playbackmap_fragment, container, false); -// vContainer.findViewById(R.id.tm_fragment_container_details).setVisibility(View.GONE);//gone - - -// View vContainer =super.onCreateView(inflater, container, savedInstanceState); -// vContainer.findViewById(R.id.pl_fragment_container_details).setVisibility(View.GONE);//gone -// vContainer.findViewById(R.id.pl_textView_bearing).setVisibility(View.GONE); - // vContainer.findViewById(R.id.pl_chronometer_sport) - super.onCreateView(inflater, container, savedInstanceState); - tbs_playback_time = (TextView) vContainer.findViewById(R.id.tbs_playback_time); - tbs_playback_time.setText("时间快照"); - activity.updateActionBarTitle(activity.app.isNaving?R.string.frg_snavi:R.string.frg_playback); - initialSeekbar(); - btnPlaySpeech = (ImageButton) vContainer.findViewById(R.id.pl_btnSpeech); - btnPlaySpeech.setOnClickListener(ButtonOnClickListener); - vContainer.findViewById(R.id.ll_right_btns).setVisibility(View.GONE); - vContainer.findViewById(R.id.ll_liveshareMsg).setVisibility(View.GONE); - - btnMapLive.setVisibility(View.GONE); - btnLiveList.setVisibility(View.GONE); - btnMapLoadRoadbook.setVisibility(View.GONE); - - QLog.getLogger().d(dTAG, TAG+ String.format(" ----- ll_right_btns is visible? %s ",vContainer.findViewById(R.id.ll_liveshareMsg).getVisibility()==View.VISIBLE )); - - return vContainer; - - } - - /* protected void initialViews(){ - super.initialViews(); - - }*/ - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - activity.app.playbackPaused = true; -// activity.startNaviService(); - Bundle bd =this.getArguments(); - if(bd!=null) - playbackID = bd.getInt(QiYouConstant.EXTRA_KEY_ID) ; -// if(activity.app.currentTrackId ==playbackID) updateUI(new Location("initial"), false ); //draw the track - showPlaybackButtons(); -// mSpeedText.setText( "回放就绪") ; - PLAY_START =activity.app.isNaving?"模拟开始":"回放开始"; - PLAY_END=activity.app.isNaving?"模拟结束":"回放结束"; - startStopPlay(); - if(tabhost!=null ){ - tabhost.setCurrentTab(1); - } - } - - protected void showFullMap(){ -// FrameLayout ll = (FrameLayout)vContainer.findViewById(R.id.playback_fragment_container_details); -// ll.setVisibility(ll.getVisibility()==View.GONE?View.VISIBLE:View.GONE); - - LinearLayout footmark =(LinearLayout)vContainer.findViewById(R.id.tab_footmark); -// ((LinearLayout)vContainer.findViewById(R.id.tab_footmark)).setVisibility(View.INVISIBLE); - if(footmark!=null) footmark.setVisibility( View.INVISIBLE ); - if(this.btnLocation!=null) - btnLocation.setVisibility(View.GONE); - } - - - @Override -protected void startStopPlay(){ - - isStartPlay =!isStartPlay; - if(isStartPlay){ - mSpeedText.setText(PLAY_START ) ; - if(QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2) - activity.app.speech(PLAY_START,0); - isPlayPause =false; - activity.app.playBackStopped =false; - btnPlay.setImageResource(R.drawable.icon_plstop); -// btnPlay.setImageResource(R.drawable.stop); -// btnPlayMap.setText("停止"); - activity.app.playbackPaused = false; - btnPlayPause.setImageResource(R.drawable.icon_plpause); -// -// gpRecordingOverlay.removeAll(); - - activity.startTrackPlayBack(playbackID); - /*if(activity.app.isNaving){ - startNavi(true); - }*/ - playbackSumPausetime=0; - playbackSumOfftime=0; - mTopSpeedText.setText("0.00"); -// activity.app.initialPlayBack(playbackID); - - removeShortLines(); - - }else - { - mSpeedText.setText(PLAY_END ) ; - if(activity.app.isSpeaking()) - activity.app.stopSpeech(); - if(QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2) - activity.app.speech(PLAY_END,0); - - Intent serviceIntent = new Intent(activity, TrackPlaybackService.class); - activity.stopService(serviceIntent); - - if(activity.app.isNaving){ - serviceIntent = new Intent(activity, QNaviSvc.class); - activity.stopService(serviceIntent); - } - - - - activity.app.playBack=false; - activity.app.playBackStopped =true; - activity.app.playbackPaused =false; - btnPlay.setImageResource(R.drawable.icon_play); -// btnPlayMap.setText("开始"); - btnPlayPause.setImageResource(R.drawable.icon_plpause); - } - newTarget=-1; - oldprogress=-1; - activity.app.playProgressTarget=0; - btnPlayPause.setEnabled(isStartPlay); - QiYouConstant.CAN_SPEAK = isStartPlay ; -// btnPlay.setEnabled(false); - - - - } - //开始/停止按钮 - @Override - protected void playbackPause(){ - isPlayPause =!isPlayPause; - - if (isPlayPause) { - activity.app.playbackPaused = true; - btnPlayPause.setImageResource(R.drawable.icon_plresume); -// btnPlayPauseMap.setText("继续"); - tm_textView_bearing.setVisibility(View.GONE); - - } else { - - activity.app.playbackPaused = false; - btnPlayPause.setImageResource(R.drawable.icon_plpause); -// btnPlayPauseMap.setText("暂停"); - - } - QiYouConstant.CAN_SPEAK = !isPlayPause ; - String pre = activity.app.isNaving ? "模拟" :"回放"; - String words = pre + ( isPlayPause?"暂停":"继续" ); - mSpeedText.setText(words) ; - activity.app.speech(words,10); - } - - - - private SeekBar playControl = null; - private SeekBar playSpeed = null; - private void initialSeekbar(){ - - playSpeed = (SeekBar) vContainer.findViewById(R.id.pl_speed_bar); - int span=activity.app.getCurrentTrack().getTrackBean().getGpsSpan(); - span=span>0?span:1000; - final int max=30; - playSpeed.setMax(max); - final int baseSpeed=5; - final int speedStep=span/QiYouConstant.WPS_SAVE_PERCENT_FACTOR/max; - playSpeed.setProgress(max/2); - QiYouConstant.PLAYBACK_TIME_INTERVAL =speedStep*max/2+baseSpeed*speedStep; - playSpeed.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - int progressChanged = 0; - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){ - progressChanged = progress; - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - // TODO Auto-generated method stub - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - progressChanged=progressChanged==0?1:progressChanged; - progressChanged=progressChanged>1?progressChanged-1:progressChanged; - QiYouConstant.PLAYBACK_TIME_INTERVAL=(max-progressChanged)*speedStep +baseSpeed*speedStep;; -// Toast.makeText(activity,"seek bar progress:"+progressChanged, Toast.LENGTH_SHORT).show(); - } - }); - int sumdist = (int) activity.app.getCurrentTrack().getTrackBean().getDistance(); - QLog.getLogger().d(dTAG, "sumdist is " + sumdist); - playControl = (SeekBar) vContainer.findViewById(R.id.pl_progress_bar); - playControl.setMax(sumdist); -// playControl.setEnabled(!activity.app.isNaving);//when naving,disable the seek - playControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - int progressChanged = 0; - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){ - progressChanged = progress; - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - // TODO Auto-generated method stub - oldprogress =seekBar.getProgress(); - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - activity.app.playProgressTarget =progressChanged; - newTarget=progressChanged; -// Toast.makeText(activity,"seek bar progress:"+progressChanged, Toast.LENGTH_SHORT).show(); - } - }); - - } - - - int oldprogress=-1; - int newTarget=-1; - @Override - public void updateUI(Location location, Boolean isOnPause){ - if( isPlayPause||activity.app.playbackPaused )return; - if(location==null)return; - float speed =location.getSpeed(); - if(speed>-1 && (location.getExtras()==null||!location.getExtras().containsKey("wptime")))return; //filter locaitons from gps - float progress = speed==-1?playControl.getMax() : location.getExtras().getFloat("dist") ; - - if (playControl.getMax() == 0 ){ - int sumdist = (int) activity.app.getCurrentTrack().getTrackBean().getDistance(); - QLog.getLogger().d(dTAG, "sumdist is " + sumdist); - playControl = (SeekBar) vContainer.findViewById(R.id.pl_progress_bar); - playControl.setMax(sumdist); - } - - -// if(progress==0)return; -// progress =speed==-1?playControl.getMax():progress; -// QLog.getLogger().d(dTAG, TAG+ String.format("progress?%f,oldprogress?%s,newTarget?%s ",progress,oldprogress,newTarget )); - if(newTarget==oldprogress //no changes - ||newTarget>oldprogress &&progress>=newTarget //forward - || newTarget滑动刚好页面也有滑动效果 - class MyGestureDetector extends SimpleOnGestureListener { - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, - float velocityY) { - - if(tabhost==null)return false; - - maxTabIndex = tabhost.getTabWidget().getChildCount(); - - if(currentTab ==MAPVIEW_INDEX){ - return false; //mapview not effect - } - - if(maxTabIndex==-1)return false; - try { - - QLog.getLogger().d(dTAG, String.format("%s onFiling: currentTab is %s,currentTab ==MAPVIEW_INDEX? %s" + - " ,velocityX is %s" ,TAG,currentTab,currentTab ==MAPVIEW_INDEX,velocityX)); - - int swip_threshold_v =currentTab ==MAPVIEW_INDEX?MAPVIEW_THRESHOLD_VELOCITY:SWIPE_THRESHOLD_VELOCITY; -// // QLog.getLogger().d(dTAG, TAG+" onFiling: currentTab is " +currentTab+",velocityX is "+velocityX); -// // QLog.getLogger().d(dTAG, TAG+" Math.abs(e1.getY() - e2.getY()) "+Math.abs(e1.getY() - e2.getY())); - if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) - return false; - // right to left swipe - activity.app.updateSlidTabs(); - if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE - && Math.abs(velocityX) > swip_threshold_v) { - Log.i("test", "right"); - if (currentTab == maxTabIndex) { - currentTab = 0; - } else { - currentTab++; - } - tabhost.setCurrentTab(currentTab); - } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE - && Math.abs(velocityX) > swip_threshold_v) { - Log.i("test", "left"); - if (currentTab == 0) { - currentTab = maxTabIndex; - } else { - currentTab--; - } - tabhost.setCurrentTab(currentTab); - } - } catch (Exception e) { - } - return false; - } - } - - protected void onMyTabChanged(String tabId){ - if(tabhost==null)return; -// initialTabhostStyle(tabhost); - setSelectedTabhostStyle(tabhost); - currentTab= tabhost.getCurrentTab(); - hideNotes(); - - } - -// private int selectedSize ; -// private int unSelectedSize ; - - -// int FirstTabBackGround ; - -// ColorStateList FirstTabTextColor; - - @TargetApi(Build.VERSION_CODES.FROYO) - void initialTabhostStyle(TabHost tabhost){ - int height= getResources().getDimensionPixelSize(R.dimen.tab_top_height); - - int width=-1; - TabWidget tabWidget = tabhost.getTabWidget(); - for (int i =0; i < tabWidget.getChildCount(); i++) { -// if( tabWidget.getChildAt(i).getId() == R.id.tab_toolbar)continue; - tabWidget.getChildAt(i).getLayoutParams().height = height; - tabWidget.getChildAt(i).getLayoutParams().width = width; - TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title); - if(tv==null){ - continue; - } - - tv.setPadding(5, 0, 0, 0); - - if(i>0){ -// tv.setTextColor( getResources().getColorStateList(R.color.lightslategrey)); - tv.setTextColor( getResources().getColorStateList(R.color.darkgray)); -// tv.setTextSize(unSelectedSize); -// tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray); - }else{ - - - -// tv.setTextSize(selectedSize); - tv.setTextColor( getResources().getColorStateList(R.color.darkslategrey)); - /* tv.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); -// tv.setBackgroundColor(color.darkslategrey) ; - tv.setGravity(Gravity.CENTER_VERTICAL);*/ - - -// if(FirstTabTextColor!=null){ -// tv.setTextColor(FirstTabTextColor); -// -// -// } -// tv.setBackgroundResource(color.darkslategrey); - } - -// addPic((LinearLayout)tabWidget.getChildAt(i),i,tabWidget.getChildCount()); - - - } -// tabhost.getTabWidget().setStripEnabled(true); - } - - - /* - void addPic(LinearLayout ll,int currentTab,int tabsCnt){ - if(FirstTabBackGround==0 ){ - return; - } - ImageView iv = new ImageView(activity); - iv.setBackgroundResource(FirstTabBackGround); - - try{ - ll.setGravity(Gravity.CENTER_VERTICAL); - ll.addView(iv,0); -// ll.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); -// ll.setBackgroundColor(color.darkslategrey) ; - if(tabsCnt>4){ - ll.setPadding(10, 0, 0, 0); - } - }catch(ClassCastException e){ - - } - - }*/ - - - /*TabHost.TabSpec getTab(String label, int drawableId, int content) { - TabHost.TabSpec spec = tabhost.newTabSpec(label); - - View tabIndicator = LayoutInflater.from(activity).inflate(R.layout.tab_indicator, tabhost.getTabWidget(), false); - TextView title = (TextView) tabIndicator.findViewById(R.id.title); - title.setText(label); - ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon); - icon.setImageResource(drawableId); - spec.setIndicator(tabIndicator); - spec.setContent(content); - return spec; - } - */ - - - - - - - public void setSelectedTabhostStyle(TabHost tabhost){ - TabWidget tabWidget = tabhost.getTabWidget(); - for (int i =0; i < tabWidget.getChildCount(); i++) { - - TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title); -// TextView tv = (TextView) ((RelativeLayout)tabWidget.getChildAt(i)).findViewById(android.R.id.title); - - if(tv==null){ - continue; - } - // tv.setTextSize(15); - if(i!=tabhost.getCurrentTab()){ -// tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray); - tv.setTextColor( getResources().getColorStateList(R.color.darkgray)); -// tv.setTextSize(unSelectedSize); - }else{ -// tabWidget.getChildAt(tabhost.getCurrentTab()).setBackgroundResource(R.color.ivory); - tv.setTextColor( getResources().getColorStateList(R.color.darkslategrey)); -// tv.setTextSize(selectedSize); - } -// if(i==0 ) -// if(FirstTabTextColor!=null){ -// tv.setTextColor(FirstTabTextColor); -//// tabWidget.getChildAt(0).setBackgroundColor(color.darkslategrey) ; -// } - - } -// tabhost.getTabWidget().setStripEnabled(true); - } - - protected void showCategoryList(com.qiyou.mb.android.ui.fragments.InnerGridView cateLv , ScrollView textContainer ){ - if(activity.app.mStatistics==null)return; - HashMap> cates= activity.app.mStatistics.getCategoryList(); - - List> cateList = new ArrayList>(); - HashMap map; - final String FLAG=",.*&"; - final String ID_FLAG=FLAG+trackId; - for(String cate:cates.keySet()){ - map =new HashMap(); - map.put("cate", cate); - map.put("chk", cate); - if(trackId>0) - for(int id:cates.get(cate)){ - if(id==trackId){ - map.put("chk", cate+ID_FLAG); - - } - } - cateList.add(map); - } - - - QSimpleAdapter adapter = new QSimpleAdapter(activity,cateList,R.layout.category_list_detail, - new String[]{"cate","chk"}, - new int[]{R.id.txt_cate,R.id.chk_cate}); -// ArrayList srcs = activity.app.getImportedGpxFileList(); - adapter.setViewBinder( new ViewBinder(){ - @Override - public boolean setViewValue(View view, Object data,String textRepresentation) { -// - if(view.getId()==R.id.chk_cate){ - CheckBox cb = (CheckBox) view; - String value= (String)data; - String tmp=""; - if(isCateQuery){ - cb.setChecked(activity.app.getQueryCategoryList().contains(value) ); - } - else - if(value.indexOf(FLAG)>0){ - cb.setChecked(true ); - tmp=value.substring(0,value.indexOf(FLAG)); - } - final String CATE=TextUtils.isEmpty(tmp)?value:tmp; - // // QLog.getLogger().d(dTAG, "trackId is" + trackId +",CATE is" +CATE ); - cb.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){ - @Override - public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { - -// // QLog.getLogger().d(dTAG, "trackId is" + trackId +",CATE is" +CATE +", isDel "+!isChecked); - // QLog.getLogger().d(dTAG, " isCateQuery? " +isCateQuery+", CATE is " +CATE ); - if(isChecked){ - if(isCateQuery){ - if(!activity.app.getQueryCategoryList().contains(CATE)) - activity.app.getQueryCategoryList().add(CATE); - }else{ - - if(activity.app.getNewCategoryList().get(trackId) ==null){ - activity.app.getNewCategoryList().put(trackId, new ArrayList()); - } - if(!activity.app.getNewCategoryList().get(trackId).contains(CATE)) - activity.app.getNewCategoryList().get(trackId).add(CATE); - } - }else{ - if(isCateQuery){ - if(activity.app.getQueryCategoryList().contains(CATE)) - activity.app.getQueryCategoryList().remove(CATE); - }else{ - - // QLog.getLogger().d(dTAG, " isCateQuery? " +isCateQuery+", CATE is " +CATE ); - - if(activity.app.getNewCategoryList().get(trackId) !=null - &&activity.app.getNewCategoryList().get(trackId).contains(CATE)){ - activity.app.getNewCategoryList().get(trackId).remove(CATE); - }else{ - - if(activity.app.getDelCategoryList().get(trackId) ==null ){ - activity.app.getDelCategoryList().put(trackId, new ArrayList()); - } - if(!activity.app.getDelCategoryList().get(trackId).contains(CATE)){ - activity.app.getDelCategoryList().get(trackId).add(CATE); - } - - } - } - } - - } - - - }); - - return true; - }else if(view.getId()==R.id.txt_cate){ - ((TextView)view).setText(((String)data)); - return true; - } - return false; - } - }); - - - cateLv.setAdapter(adapter); - cateLv.setParentScrollView(textContainer); - cateLv.setMaxHeight(140); - - // adapter.setSelectItem(selectedFoodmarkItem); - // filelv.setSelection(selectedFoodmarkItem); - } - - - - - - - - - - - - - -// ---------------------------------------------------------async http process--------------------- - - - - - - - - void hideWebDialog(){ - if(prgDialog!=null) { - prgDialog.hide(); - } - - if (mSwipeLayout!=null){ - mSwipeLayout.setRefreshing(false); - } - - } - - - - void showWebDialog(){ - try{ - if(this.isAdded()) { - - if (mSwipeLayout!=null){ - mSwipeLayout.setRefreshing(true); - } else { - - prgDialog.show(); - } - } - - - }catch(Exception er){ - - } - } - - - AsyncHttpResponseHandler asyncHttpResponseHandler = new AsyncHttpResponseHandler(){ - - public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable) - { - // QLog.getLogger().d(dTAG, TAG + ", onFailure(int, Header[],byte[], Throwable ) was received"); -// // QLog.getLogger().d(dTAG, TAG + ", response is " + new String(paramAnonymousArrayOfByte)); - - paramAnonymousThrowable.printStackTrace(); - - asynClientOnFailure(paramAnonymousInt, paramAnonymousThrowable.getMessage(), paramAnonymousArrayOfHeader); - } - - public void onSuccess(int statusCode, Header[] header, byte[] paramAnonymousArrayOfByte) - { -// if(prgDialog!=null)prgDialog.hide(); - hideWebDialog(); - // QLog.getLogger().d(dTAG, TAG + ", response is " + new String(paramAnonymousArrayOfByte)); - if (paramAnonymousArrayOfByte != null) { - processTxtOnSuccess(paramAnonymousArrayOfByte); - } - - } - } ; - - void httpsGet(RequestParams params, String strUrl){ - URL url; - URI uri = null ; - try { - url = new URL(strUrl); - uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if(uri==null)return; - // // QLog.getLogger().dLog(dTAG, TAG, "httpsGet url:" +strUrl); - // // QLog.getLogger().dLog(dTAG, TAG, "uri.getRawPath():" + uri.getRawPath()); - // // QLog.getLogger().dLog(dTAG, TAG, "uri:" + uri.toString()); - - /* if (this.prgDialog == null) { - initPrgDialog(); - } - if (isAdded()) { -// this.prgDialog.show(); - }*/ - - try{ - /// We initialize a default Keystore - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - // We load the KeyStore - trustStore.load(null, null); - // We initialize a new SSLSocketFacrory - MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore); - // We set that all host names are allowed in the socket factory - socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - // We initialize the Async Client - AsyncHttpClient client = new AsyncHttpClient(true, 80, 443); - // We set the timeout to 30 seconds - client.setTimeout(30*1000); - // We set the SSL Factory - client.setSSLSocketFactory(socketFactory); - client.get( uri.toString(), params, asyncHttpResponseHandler); - -// AsyncHttpClient asycnHttpClient = new AsyncHttpClient(true, 80, 443); -// asycnHttpClient.get( uri.toString(), params, asyncHttpResponseHandler); - }catch(NoSuchAlgorithmException e){ - e.printStackTrace(); - } catch (CertificateException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (KeyStoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (KeyManagementException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UnrecoverableKeyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - /* - asycnHttpClient.get(uri.getRawPath(), params, new AsyncHttpResponseHandler(){ - String msg = ""; - - public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable) - { - // QLog.getLogger().d(dTAG, TAG + ", onFailure(int, Header[],byte[], Throwable ) was received"); - QiyouFragment.this.asynClientOnFailure(paramAnonymousInt, this.msg, paramAnonymousArrayOfHeader); - } - - public void onSuccess(int statusCode, Header[] header, byte[] paramAnonymousArrayOfByte) - { - QiyouFragment.this.prgDialog.hide(); - // QLog.getLogger().d(dTAG, TAG + ", response is " + new String(paramAnonymousArrayOfByte)); - if (paramAnonymousArrayOfByte != null) { - processTxtOnSuccess(paramAnonymousArrayOfByte); - } - } - });*/ - } - - void getTextW(RequestParams params, String url){ - if(!Utils.isNetworkConnected(activity)){ -// this.showNotes("没有可用的网络连接"); - asynClientOnFailure(0,"",null); - return; - } - hideNotes(); - if (this.prgDialog == null) { - initPrgDialog(); - } - if (isAdded()) { - this.prgDialog.show(); - } - QiYouApplication.getEle(url, params, new AsyncHttpResponseHandler(){ - - String msg = ""; - - public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable) - { - // // QLog.getLogger().d(dTAG, TAG + ", onFailure(int, Header[],byte[], Throwable ) was received"); - QiyouFragment.this.asynClientOnFailure(paramAnonymousInt, this.msg, paramAnonymousArrayOfHeader); - } - - public void onSuccess(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte) - { -// QiyouFragment.this.prgDialog.hide(); - hideWebDialog(); - // // QLog.getLogger().d(dTAG, TAG + ", response is " + new String(paramAnonymousArrayOfByte)); - if (paramAnonymousArrayOfByte != null) { - processTxtOnSuccess(paramAnonymousArrayOfByte); - } - } - }); - } - - - JsonHttpResponseHandler getJsonResponseHandler = new JsonHttpResponseHandler() { - @Override - public void onSuccess(int statusCode, Header[] headers, JSONObject response) { -// prgDialog.hide(); - hideWebDialog(); - // QLog.getLogger().d(dTAG, TAG+", onSuccess(int statusCode, Header[] headers, JSONObject response) was received"); - String method =""; -// if (response != null) { - JSONObject jsonObject= null; - - try { - - try { - jsonObject= response.getJSONObject(QiYouConstant.JSONOBJECT_KEY); - - } catch (JSONException e) { - Utils.logStackTrace(e, TAG);; - } - - method =response.has(QiYouConstant.SIGN_KEY)?response.getString(QiYouConstant.SIGN_KEY):""; - String msg=response.getString(QiYouConstant.MSG_KEY); - - processGetJsonObject( method, jsonObject,msg ); - } catch (JSONException e) { - // TODO Auto-generated catch block - - Utils.logStackTrace(e, TAG); - showNotes("出错了",false); - }catch (NullPointerException e) { - // TODO Auto-generated catch block - - Utils.logStackTrace(e, TAG); - showNotes("出错了",false); - } catch (NoWebObjectException e) { - // TODO Auto-generated catch block - - if(method.equalsIgnoreCase(RestMethods.SECURITY_INVALIDE)) - showNotes("身份验证错误,请登录",true); - else - showNotes("没找到记录,请检查您的输入",true); - } - -// } - } - - @Override - public void onSuccess(int statusCode, Header[] headers, JSONArray response) { -// prgDialog.hide(); - hideWebDialog(); - // QLog.getLogger().d(dTAG, TAG+", onSuccess(int statusCode, Header[] headers, JSONArray response) was received"); - -// if (response != null) { - - processJsonArray(response); - - -// } - } - String msg = ""; - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { - // // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONObject) was received"); - - try { - msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - asynClientOnFailure(statusCode,msg,headers); - } - - @Override - public void onFailure(int statusCode, org.apache.http.Header[] headers, String errorResponse, java.lang.Throwable throwable ) { - // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], String, Throwable) was received" ); - // QLog.getLogger().d(dTAG, TAG+"errorResponse: "+errorResponse); - asynClientOnFailure(statusCode,msg,headers); - - - - - } - - @Override - public void onProgress(int bytesWritten, int totalSize) { - // TODO Auto-generated method stub - super.onProgress(bytesWritten, totalSize); - int count = (int) ((bytesWritten * 1.0 / totalSize) * 100); - // 上传进度显示 - mProgress.setProgress(count); - // QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize); - } - - }; - - - void getJsonWs(RequestParams params,String url,boolean isInsilence){ - - if(!Utils.isNetworkConnected(activity)){ -// this.showNotes("没有可用的网络连接"); - asynClientOnFailure(0,"",null); - return; - } - if(prgDialog==null)initPrgDialog(); -// if(this.isAdded()) prgDialog.show(); - if(!isInsilence) { - showWebDialog(); - } - - hideNotes(); - - QLog.getLogger().d(dTAG, TAG + "requesting----> " +url +"?"+params.toString()); - - -// setCookie(); - QiYouApplication.get(url, params, getJsonResponseHandler); - - - } - - //other url than i7lv - void get3dJsonWs(RequestParams params,String url,boolean isInsilence){ - - if(!Utils.isNetworkConnected(activity)){ -// this.showNotes("没有可用的网络连接"); - asynClientOnFailure(0,"",null); - return; - } - if(prgDialog==null)initPrgDialog(); -// if(this.isAdded()) prgDialog.show(); - if(!isInsilence) - showWebDialog(); - - hideNotes(); - - // QLog.getLogger().d(dTAG, TAG + "requesting----> " +url +"?"+params.toString()); - - QiYouApplication.get3dpart(url, params, new JsonHttpResponseHandler() { - - @Override - public void onSuccess(int statusCode, Header[] headers, JSONObject response) { -// prgDialog.hide(); - hideWebDialog(); - // QLog.getLogger().d(dTAG, TAG+", onSuccess(int statusCode, Header[] headers, JSONObject response) was received"); - // QLog.getLogger().d(dTAG, TAG+", response from qq:" +response.toString()); - try { - process3dpartJson(response); - } catch (JSONException e) { - // TODO Auto-generated catch block - showNotes("认证出错了。。。",true); - } - - } - @Override - public void onFailure(int statusCode, org.apache.http.Header[] headers, String errorResponse, java.lang.Throwable throwable ) { - // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], String, Throwable) was received" ); - // QLog.getLogger().d(dTAG, TAG+"errorResponse: "+errorResponse); - asynClientOnFailure(statusCode,"QQ 用户信息同步错误",headers); - } - - } ); - - - } - - void process3dpartJson(JSONObject response) throws JSONException{ - - } - - - void getJsonWs(RequestParams params,String url){ - getJsonWs(params,url,false); - } - - void processGetJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException,NullPointerException, NoWebObjectException { - if(TextUtils.isEmpty(method) /*|| jsonObject==null*/)return; - - // QLog.getLogger().d(dTAG, " get method is: " +method); - - if(method.equalsIgnoreCase(RestMethods.SECURITY_INVALIDE)){ //to login - this.showNotes(msg,true); - activity.showLogin(); - } - - - - } - - /* - * post json string to server - */ - void postJsonWS(String json,String url) { - if(!Utils.isNetworkConnected(activity)){ -// this.showNotes("没有可用的网络连接"); - asynClientOnFailure(0,"",null); - return; - } -// setCookie(); - showCookies(); - hideNotes(); - // QLog.getLogger().d(dTAG, TAG+" post json is "+json); - // Show Progress Dialog - if(prgDialog==null)initPrgDialog(); - showWebDialog();//if(this.isAdded())prgDialog.show(); - // Make RESTful webservice call using AsyncHttpClient object -// testCookies(); - StringEntity entity =null; - try { - entity = new StringEntity(json,HTTP.UTF_8); - } catch (UnsupportedEncodingException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - if(entity==null)return; - - entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); - -// QiyouRestClient.post(activity,url, entity,"application/json", - QiYouApplication.post(activity.app,url, entity,"application/json", - new JsonHttpResponseHandler(){ - @Override - public void onSuccess(int statusCode, org.apache.http.Header[] headers, JSONObject response){ -// prgDialog.hide(); - hideWebDialog(); - if (response != null) { - try { -// JSONObject jsonObject= response.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ; - JSONObject jsonObject= null; - try { - jsonObject= response.getJSONObject(QiYouConstant.JSONOBJECT_KEY); - - } catch (JSONException e) { - - } - String method =response.has(QiYouConstant.SIGN_KEY)?response.getString(QiYouConstant.SIGN_KEY):""; - String msg=response.getString(QiYouConstant.MSG_KEY); - // QLog.getLogger().d(dTAG, " post sucess,method is: " +method +" msg is " +msg); - processJsonObject(method, jsonObject,msg); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - - } - } - - @Override - public void onSuccess(int statusCode, Header[] headers, JSONArray response) { - // // QLog.getLogger().d(dTAG, TAG+", onSuccess(int, Header[], JSONArray) was received"); - - - } - - - - String msg = ""; - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { - // // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONObject) was received"); - - try { -// JSONObject jsonObject= errorResponse.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ; -// String method =jsonObject.has(QiYouConstant.SIGN_KEY)?jsonObject.getString(QiYouConstant.SIGN_KEY):""; -// String msg=errorResponse.getString(QiYouConstant.MSG_KEY); - msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - asynClientOnFailure(statusCode,msg,headers); - } - - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { - // // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONArray) was received" ); - asynClientOnFailure(statusCode,msg,headers); - } - - - - @Override - public void onFailure(int statusCode, org.apache.http.Header[] headers, String errorResponse, java.lang.Throwable throwable ) { - // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], String, Throwable) was received" ); - // QLog.getLogger().d(dTAG, TAG+"errorResponse: "+errorResponse); - asynClientOnFailure(statusCode,msg,headers); - } - @Override - public void onProgress(int bytesWritten, int totalSize) { - // TODO Auto-generated method stub - super.onProgress(bytesWritten, totalSize); - int count = (int) ((bytesWritten * 1.0 / totalSize) * 100); - // 上传进度显示 - if(mProgress!=null) - mProgress.setProgress(count); - // QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize); - } - }); - - - - } - -// void postBinaryWS(JSONObject mdJson,String svrUrl) throws FileNotFoundException, JSONException { - void postBinaryWS(Media md,String svrUrl) throws FileNotFoundException, JSONException { - if(!Utils.isNetworkConnected(activity)){ -// this.showNotes("没有可用的网络连接"); - asynClientOnFailure(0,"",null); - return; - } -// showCookies(); - // Show Progress Dialog - if(prgDialog==null)initPrgDialog(); - prgDialog.setTitle("正在上传图片"); - // Make RESTful webservice call using AsyncHttpClient object -// testCookies(); - - hideNotes(); - String path=md.getUri();//mdJson.getString("Uri"); - String smallPicPath =getSmallPicName(path); - - - File file = new File(smallPicPath); - if (!file.exists()){ - this.createSmallPic(path, QiYouConstant.WEB_PIC_SIZE,null);//QiYouConstant.MAP_PIC_WATER_MARK_WORDS); - } - - if (file.exists() && file.length() > 0) { - showWebDialog();//if(this.isAdded()) prgDialog.show(); - RequestParams params = new RequestParams(); - params.put("file", file); - // params.put("name", mdJson.getString("name")); - // params.put("mdJson", mdJson); - params.put("md", Utils.getGsonString(md)); -// QiyouRestClient.post(svrUrl, params, - QiYouApplication.post(svrUrl, params, - - new JsonHttpResponseHandler(){ - String msg="《无》"; - @Override - public void onSuccess(int statusCode, org.apache.http.Header[] headers, JSONObject response){ -// prgDialog.hide(); - hideWebDialog(); - mdUploaded=true; - // // QLog.getLogger().dLog(dTAG, TAG+" mdUploading return result ,uploading success,start next... "); - if (response != null) { - try { - // 上传成功后要做的工作 - // Toast.makeText(activity, "上传成功", Toast.LENGTH_LONG).show(); - mProgress.setProgress(100); - /* String jsonString = response.getString(QiYouConstant.JSONOBJECT_KEY); - JSONObject json = new JSONObject(jsonString); - processJsonObject4MdUpload( json);*/ - // QLog.getLogger().d(dTAG, TAG+" 上传成功"); - JSONObject jo=response.getJSONObject(QiYouConstant.JSONOBJECT_KEY); - // QLog.getLogger().d(dTAG, TAG+" onSuccess JSONObject: "+response.toString()); - - uploadMediasOnReturn(jo); - /* if(jo!=null){ - processJsonObject4MdUpload(jo ); - uploadMedias(mTrack); - }*/ - // response.getString(QiYouConstant.JSONOBJECT_KEY); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - - } - } - - /* @Override - public void onFailure(int statusCode, Header[] headers, - byte[] responseBody, Throwable error) { - // 上传失败后要做到工作 - Toast.makeText(activity, "上传失败", Toast.LENGTH_LONG).show(); - String msg=""; - asynClientOnFailure(statusCode,msg,headers); - }*/ - @Override - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { - // // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONObject) was received"); -// prgDialog.hide(); - hideWebDialog(); - mdUploaded=true; - // // QLog.getLogger().dLog(dTAG, TAG+" mdUploading return result ,uploading failure,start next... "); - - try { - msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - asynClientOnFailure(statusCode,msg,headers); - } - - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { - // // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONArray) was received" ); - asynClientOnFailure(statusCode,msg,headers); - uploadMediasOnReturn(null); - - } - - - - @Override - public void onFailure(int statusCode, org.apache.http.Header[] headers, String errorResponse, java.lang.Throwable throwable ) { - // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], String, Throwable) was received" ); - // QLog.getLogger().dLog(dTAG, TAG+"errorResponse: "+errorResponse); - mdUploaded=true; - asynClientOnFailure(statusCode,msg,headers); - uploadMediasOnReturn(null); - } - - - @Override - public void onProgress(int bytesWritten, int totalSize) { - // TODO Auto-generated method stub - super.onProgress(bytesWritten, totalSize); - int count = (int) ((bytesWritten * 1.0 / totalSize) * 100); - // 上传进度显示 - mProgress.setProgress(count); - // QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize); - } - - @Override - public void onRetry(int retryNo) { - // TODO Auto-generated method stub - super.onRetry(retryNo); - // 返回重试次数 - } - - }); - } else { -// Toast.makeText(activity, "文件不存在", Toast.LENGTH_LONG).show(); - showNotes("出错了,文件不存在:"+path); - } - - - - } - - void updateUIOnRequestResonsed(String method){ - - } - - void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){ - // Response failed :( - - /*if(headers!=null) - for (Header h : headers) { - // QLog.getLogger().d(dTAG, TAG+" "+ h.getName() + " " + " " + h.getValue() + ""); - }*/ - - updateUIOnRequestResonsed(""); - - if (mSwipeLayout!=null){ - mSwipeLayout.setRefreshing(false); - } - - QLog.getLogger().d(dTAG, TAG+" failure msg: "+ msg); - QLog.getLogger().d(dTAG, TAG+" failure statusCode: "+ statusCode); - // Hide Progress Dialog -// if(prgDialog!=null) -// prgDialog.hide(); - hideWebDialog(); - // When Http response code is '404' - if (statusCode == 401) { -// Toast.makeText(activity, -// "Requested resource not found" +msg, -// Toast.LENGTH_LONG).show(); - activity.app.user.getUserbean().setExprires(0); - activity.showLogin(); - showNotes("服务器需要验证您的身份, 请登录 ",true); - }if (statusCode == 404) { -// Toast.makeText(activity, -// "Requested resource not found" +msg, -// Toast.LENGTH_LONG).show(); - showNotes("出错了,错误信息:"+msg,false); - } - // When Http response code is '500' - else if (statusCode == 500) { -// Toast.makeText(activity, -// "Something went wrong at server end" +msg, -// Toast.LENGTH_LONG).show(); - showNotes("出错了,错误信息:"+msg,false); - } - // When Http response code is '500' - else if (statusCode == 417) { - - showNotes("出错了,错误信息:"+msg,true); - } - // When Http response code other than 404, 500 - else { -// Toast.makeText( -// activity, -// "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]" +msg, -// Toast.LENGTH_LONG).show(); - showNotes("出错了,无法连接服务器,请检查网络连接.",false); - } - } - - /* - * upload track success,then update mobile info - * upload medias - */ - void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{ - pirntCookies(); - updateUIOnRequestResonsed(method); - if(jsonObject==null)return; - - if(method.equalsIgnoreCase(RestMethods.TRACK_P_IMPORT)){ - onImportTrackSuccess( method, jsonObject, msg); - } - - } - void processJsonArray(JSONArray jsonArrary){} - - boolean isForShare=false; - void shareTrack(Track track){ - isForShare=!isForShare; - if(track.getTrackBean().getSvrNumber()==0){ - if(!isWebRequest) - uploadTrack(track); - if(isForShare) return; - } - - } - /* - * start upload - */ - void uploadTrack(Track track){ - -// if(QiYouConstant.PV_USER_ID==-1){ - if(activity.app.user.getUserbean().getId()<=0){ -// Toast.makeText(activity, -// "请先登录", -// Toast.LENGTH_LONG).show(); - showNotes("请先登录"); - isLoginForShare=true; - activity.showLogin(); - return; - } - if(track.getTrackBean().getDistance()<=10){ - showNotes("运动的距离太短了。。。上传失败"); - return; - } - if(QiYouConstant.DEVELOPER_MODE) - track.getTrackBean().setUserid(activity.app.user.getUserbean().getId());//TODO:to remove - - if(track.getTrackBean().getUserid()<=0){ - track.getTrackBean().setUserid(activity.app.user.getUserbean().getId()); - } - else if(!QiYouConstant.DEVELOPER_MODE && track.getTrackBean().getUserid()>0 && track.getTrackBean().getUserid()!=activity.app.user.getUserbean().getId()){ - Toast.makeText(activity, - "只能上传本人的记录,上传取消", - Toast.LENGTH_LONG).show(); - return; - } - - if( track.getTrackBean().getSvrNumber()<=0){ - track.getTrackBean().setAvStatus(TrackAvStatus.PUBLIC); - } - - track.getTrackBean().setSummary(track.getSummary()); - ArrayList wps =track.getTrackBean().getTrkseg().size() > QiYouConstant.MAX_UPLOAD_WPS_SIZE_PER_KM ? track.getTrackBean().getTrkseg() : null; - track.getTrackBean().setTrksegs(Utils.zipPathPoints(track.getTrackBean(), QiYouConstant.MAX_UPLOAD_WPS_SIZE_PER_KM)); //zip to target size - this.postJsonWS(track.toString(),RestMethods.TRACK_P_IMPORT /*"mb/track/"*/); - if(wps!= null){ - track.getTrackBean().setTrksegs(wps);//set back original - } - -// track.getTrackBean().setUserid(QiYouConstant.PV_USER_ID); -// track.getTrackBean().setTrksegs(null); -// track.getTrackBean().setRoadWps(null) ; -// track.getTrackBean().setStartWp(null); -// track.getTrackBean().setLastWp(null); -// track.getTrackBean().setMaxDistWp(null); - -// track.getTrackBean().setDistance(track.getTrackBean().getDistance()+10000); -// String trackString=track.toString(); - // // QLog.getLogger().dLog(dTAG, trackString); -// // QLog.getLogger().dLog(dTAG, "upload track user id is:" +track.getTrackBean().getUserid()); -// // QLog.getLogger().dLog(dTAG, "upload track distance is:" +track.getTrackBean().getDistance()); -// // QLog.getLogger().dLog(dTAG, track.getTrackBean().getStartWp().toJsonWp()); - - - } - - - void onImportTrackSuccess(String method,JSONObject jsonObject,String msg) throws JSONException{ - int svrNo= jsonObject.getInt("svrNumber"); - if(svrNo<=0)return; - activity.app.user.getUserbean().setScore(jsonObject.getInt("userScore")); - activity.app.updateUserPref(); - if( mTrack.getTrackBean().getSvrNumber()!=svrNo){ - mTrack.getTrackBean().setSvrNumber(svrNo); - HashMap ids = new HashMap(); -// ids.put(jsonObject.getInt("trackId"), jsonObject.getInt("svrNumber")); - ids.put(mTrack.getTrackBean().getTrackId(), jsonObject.getInt("svrNumber")); - activity.app.updateTrackSvrNos(ids); - } -// Toast.makeText(activity, -// "Success", -// Toast.LENGTH_LONG).show(); - showNotes("上传成功!云编号:"+svrNo); - try{ - activity.app.mStatistics.getStatisticsTracks().get(Integer.valueOf(mTrack.getTrackBean().getType().toInt())) - .getSbs().get(Integer.valueOf(mTrack_bean.getTrackId())).setSvrNo(svrNo); - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - } - - activity.app.mStatistics.getExistedSvrNos().add(Integer.valueOf(svrNo)); - activity.app.writeStatiscs(); - -// if(txtNote!=null)txtNote.setVisibility(View.VISIBLE); - //begin to upload medias - uploadedmds = new ArrayList(); - uploadedmdsSuccessed = new ArrayList(); - uploadMedias(mTrack); //TODO: mTrack 是不是合适 - //TODO: update the track's medias,防止重复上载 - - if(isForShare) - shareTrack(mTrack); - } - - - boolean mdUploaded=true; - ArrayList uploadedmds; - void uploadMedias( Track track) throws JSONException{ - // // QLog.getLogger().dLog(dTAG, TAG+" start to upload medias"); - - for(Waypoint_bean wb:track.getTrackBean().getMdWps()){ - if(wb==null ||uploadedmds.contains(wb))continue; - for(Media md:wb.getMedias()){ - if(md==null)continue; - // QLog.getLogger().dLog(dTAG, TAG+" md.getStatus(): "+md.getStatus()); - // QLog.getLogger().dLog(dTAG, TAG+" mediaStatus.UPLOADED: "+mediaStatus.UPLOADED); - if(md.getStatus()!=mediaStatus.UPLOADED && md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){ - md.setTrackId(track.getTrackBean().getTrackId()); - md.setTrackSvrNumber(track.getTrackBean().getSvrNumber()); - - try { - /* while(!mdUploaded){ - // QLog.getLogger().dLog(dTAG, TAG+" mdUploading not return result yet, sleeping... "); - Thread.sleep(200); - } */ - postBinaryWS(md,RestMethods.TRACK_P_UPLOAD_FILE/*"mb/track/file"*/); - uploadedmds.add(wb); - mdUploaded=false; - return; - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } /*catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } */ - } - } - } -// // QLog.getLogger().dLog(dTAG, TAG+" start to building mdstring for update ---------------"); - //to update local database for media changes - boolean isToUpdate=false; - for(JSONObject jo:uploadedmdsSuccessed){ - if(jo==null)continue; - for(Waypoint_bean wb:track.getTrackBean().getMdWps()){ - if(wb==null)continue; - for(Media md:wb.getMedias()){ - if(md==null)continue; - try { - if( md.getTime()==jo.getLong("time")){ -// // QLog.getLogger().dLog(dTAG, TAG+" md.getUri(): "+md.getUri()); - md.setTrackId(jo.getInt("trackId")); - md.setTrackSvrNumber(jo.getInt("trackSvrNumber")); - md.setSvrUri(jo.getString("svrUri")); - md.setStatus(mediaStatus.UPLOADED); - isToUpdate=true; -// // QLog.getLogger().dLog(dTAG, TAG+" md.getSvrUri(): "+md.getSvrUri()); - } - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - if(isToUpdate){ - processJsonObject4MdUpload(track.getTrackBean().getTrackId(), Utils.getGsonString(track.getTrackBean().getMdWps()) ); - uploadedmdsSuccessed.clear(); - uploadedmds.clear(); - } - - /* new Thread(){ - @Override - public void run() { - - }}.run();*/ - - - } - - /* - * upload medias success - * to update local medias by the server info - */ - void processJsonObject4MdUpload(int trackId,String mdsString)throws JSONException{ - // // QLog.getLogger().dLog(dTAG, TAG+" mdsString to update is: "+mdsString); - activity.app.updateTrackMds(trackId,mdsString); - } - - ArrayList uploadedmdsSuccessed; - void uploadMediasOnReturn(JSONObject jo) { - if(jo!=null){ - uploadedmdsSuccessed.add(jo); - } - - try { - uploadMedias(mTrack); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - - - - /* - * to update track status - * - */ - - protected void updateTrackStatus(int svrNumber,TrackAvStatus status){ - Track tr =new Track(); - tr.getTrackBean().setSvrNumber(svrNumber); - tr.getTrackBean().setAvStatus(status); - // // QLog.getLogger().d(dTAG, "Track to update is:"+tr.toString()); - postJsonWS(tr.toString(),RestMethods.TRACK_P_UPDATE_STATUS/*"/mb/track/status"*/); - } - - - - - - - - - - - - - - - protected String buildPicWaterMarkTitle(float dist,long time){ - String title =""; - String format ="%s %s avs %.1f "; - title=String.format(format, - Utils.getFormatedTime(time), - Utils.getFormatedDistance(dist), - mTrack_bean.getAvs() - - ); - - return title; - } - - - - void createSmallPic(final String picName,final int SMALLSIZE,final String title){ - // // QLog.getLogger().d(dTAG, TAG+" start to create small pic for "+picName); -// new Thread(new Runnable(){ -// @Override -// public void run() {? -// com.qiyou.mb.android.utils.ImageLoader IL = new com.qiyou.mb.android.utils.ImageLoader(activity); - -// Bitmap b= IL.getBitmap(picName, SMALLSIZE); - Bitmap b=ImageUtil.getSmallBitmap(picName, SMALLSIZE); -// b= watermarkBitmap(b,null,QiYouConstant.MAP_PIC_WATER_MARK_WORDS); - b= watermarkBitmap(b,null,title); - String smallPicName=getSmallPicName(picName);//picName.substring(0,picName.lastIndexOf(".jpg"))+"_"+SMALLSIZE+".jpg"; - File file = new File(smallPicName); - FileOutputStream out; - try{ - out = new FileOutputStream(file); - if(b.compress(Bitmap.CompressFormat.JPEG, QiYouConstant.SMALLPIC_SIZE_COMPRESS_REATE, out)) - { - out.flush(); - out.close(); - } - // // QLog.getLogger().d(dTAG, TAG+"small pic created as: " +smallPicName); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - } - catch (IOException e) - { - e.printStackTrace(); - } - -// } -// }).start(); - } - - Bitmap watermarkBitmap(Bitmap src, Bitmap watermark, String title) { - if (src == null) { - return null; - } - if (TextUtils.isEmpty(title)){ - return src; - } - int w = src.getWidth(); - int h = src.getHeight(); - //需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了 - Bitmap newb= Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图 - Canvas cv = new Canvas(newb); - cv.drawBitmap(src, 0, 0, null);// 在 0,0坐标开始画入src - - //加入图片 - if (watermark != null) { - Paint paint=new Paint(); - int ww = watermark.getWidth(); - int wh = watermark.getHeight(); - paint.setAlpha(50); - cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, paint);// 在src的右下角画入水印 - } - //加入文字 - if(title!=null) - { - String familyName ="宋体"; - Typeface font = Typeface.create(familyName,Typeface.NORMAL); - TextPaint textPaint=new TextPaint(); - textPaint.setColor(Color.LTGRAY); - textPaint.setTypeface(font); - textPaint.setTextSize(20); - //这里是自动换行的 -// StaticLayout layout = new StaticLayout(title,textPaint,w,Alignment.ALIGN_NORMAL,1.0F,0.0F,true); -// layout.draw(cv); - //文字就加左上角算了 -// cv.drawText(title,w/2-10,h-20,textPaint); - cv.drawText(title,w/4,h-40,textPaint); -// if(!TextUtils.isEmpty(title)) -// cv.drawText(title,w-title.length()*20,h-40,textPaint); - String sign ="by "+QiYouConstant.PV_USER_NAME +" " +QiYouConstant.WATER_MARKER_SIGN; - cv.drawText( sign,w/4,h-10,textPaint); - } - cv.save(Canvas.ALL_SAVE_FLAG);// 保存 - cv.restore();// 存储 - return newb; - } - - String getSmallPicName(String picName){ - String smallName=""; - try{ - String sufix=picName.substring(picName.lastIndexOf("."),picName.length()); - smallName= picName.substring(0,picName.lastIndexOf(sufix))+"_small"+sufix; - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - } - return smallName; - } - - - void initPrgDialog(){ - /* prgDialog. = new ProgressDialog(activity); - // Set Progress Dialog Text - prgDialog.setMessage("正在请求云端数据...请稍候"); - // Set Cancelable as False - prgDialog.setCancelable(false);*/ - - - - - AlertDialog.Builder builder = new Builder(activity); - builder.setTitle(R.string.web_request); - - final LayoutInflater inflater = LayoutInflater.from(activity); - View v = inflater.inflate(R.layout.softupgrade_progress, null); - mProgress = (ProgressBar) v.findViewById(R.id.update_progress); - builder.setView(v); - - /*builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - dialog.dismiss(); - -// cancelUpdate = true; - } - });*/ - - prgDialog = builder.create(); - prgDialog.setCancelable(false); -// prgDialog.show(); - } - - - public void onBack(){ - getFragmentManager().popBackStack(); - /* new Thread(){ - public void run() { - try{ - Instrumentation inst = new Instrumentation(); - inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); - } - catch (Exception e) { - Log.e("Exception when onBack", e.toString()); - } - } - }.start(); -*/ - } - - void showNotes(String notes){ - showNotes(notes,true); - } - public void showNotes(String notes,Boolean showToast){ - if(TextUtils.isEmpty(notes) || notes.equalsIgnoreCase("null"))return; - if(showToast) - Toast.makeText(activity,notes,Toast.LENGTH_SHORT ).show(); - if(vContainer==null)return; - TextView txtNote=(TextView)vContainer.findViewById(R.id.txtNotice); - if(txtNote!=null){ - txtNote.setText(notes); - txtNote.setVisibility(View.VISIBLE); - } - } - void hideNotes(){ - TextView txtNote=(TextView)vContainer.findViewById(R.id.txtNotice); - if(txtNote!=null){ - txtNote.setText(""); - txtNote.setVisibility(View.GONE); - } - } - - - /* void setCookie(){ - PersistentCookieStore myCookieStore = new PersistentCookieStore(activity.app); - - String name = "uk"; - String value = QiYouConstant.PV_ACCESS_TOKEN +"-c-d-x-"+QiYouConstant.PV_USER_ID; - BasicClientCookie clientCookie = new BasicClientCookie(name, value); - clientCookie.setComment(""); - clientCookie.setDomain("i7lv.com"); -// clientCookie.setExpiryDate(""); - clientCookie.setPath("//"); - myCookieStore.clear(); - myCookieStore.addCookie(clientCookie); - -// myCookieStore.clear(); - // QLog.getLogger().d(dTAG," begin to print cookies myCookieStore befor set..............................."); - for(Cookie c:myCookieStore.getCookies()){ - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() ); - } -// QiyouRestClient.setCookieStore(myCookieStore); - QiYouApplication.setCookieStore(myCookieStore); - // QLog.getLogger().d(dTAG," begin to print cookies myCookieStore after set..............................."); - for(Cookie c:myCookieStore.getCookies()){ - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() ); - } - - }*/ - - void showCookies() { - /* PersistentCookieStore mCookieStore = new PersistentCookieStore( - activity); - List cookies = mCookieStore.getCookies(); - for (Cookie c : cookies) { - // QLog.getLogger().d(dTAG, TAG+" cookies:" + c.getName() +"....."+ c.getPath()+"....."+ c.getValue()); - }*/ -// pirntCookies(); - } - - void pirntCookies(){ -// AsyncHttpClient client = new AsyncHttpClient(); - HttpContext httpContext =QiYouApplication.getHttpContext();// QiyouRestClient.getHttpContext(); - - CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);//获取AsyncHttpClient中的CookieStore - // QLog.getLogger().d(dTAG," begin to print cookies..............................."); - if(cookies!=null){ - for(Cookie c:cookies.getCookies()){ - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts()); - // QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() ); - } - }else{ - // QLog.getLogger().d(dTAG,"main before~~,cookies is null"); - } - // QLog.getLogger().d(dTAG," print cookies end ..............................."); - /* //save cookie - PersistentCookieStore myCookieStore = new PersistentCookieStore(context); - QiyouRestClient.setCookieStore(myCookieStore); - - httpContext = QiyouRestClient.getHttpContext(); - cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE); - if(cookies!=null){ - // QLog.getLogger().d(dTAG, "main after~~,cookies is not null"); - for(Cookie c:cookies.getCookies()){ - // QLog.getLogger().d(dTAG,"main after ~~"+c.getName()+","+c.getValue()); - } - }else{ - // QLog.getLogger().d(dTAG, "main after~~,cookies is null"); - } - */ - } - - - - - - - void processTxtOnSuccess(byte[] paramArrayOfByte) { - - // // QLog.getLogger().dLog(dTAG, TAG, " not get result from googleapi for ele."); - -// try { -// String strResult = EntityUtils.toString(response.getEntity()); - String strResult=new String(paramArrayOfByte) ; - - - // // QLog.getLogger().dLog(dTAG, TAG, " get result from googleapi for ele:"+strResult); - GoogleEleResult ger = null; - - Gson gson = new Gson(); - try{ - if(!TextUtils.isEmpty(strResult)){ - ger = gson.fromJson(strResult, GoogleEleResult.class); - } - }catch(Exception e){ - Utils.logStackTrace(e, dTAG); - return; - } - int lasti=0; - Waypoint_bean wb; - for(LocationEle le:ger.getResults()){ - - while(lastiQiYouConstant.MAX_TRACK_RESTORE_TIME){ - handler.sendEmptyMessage(0); - break; - } - } - - handler.sendEmptyMessage(1); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - }).start(); - - - } - - /** - * adjust the listview to show properly in the scrollview - * @param listView - */ - void setListViewHeightBasedOnChildren(ListView listView) { - ListAdapter listAdapter = listView.getAdapter(); - if (listAdapter == null) { - // pre-condition - return; - } - - int totalHeight = 0; - for (int i = 0; i < listAdapter.getCount(); i++) { - View listItem = listAdapter.getView(i, null, listView); - listItem.measure(0, 0); - totalHeight += listItem.getMeasuredHeight(); - } - - ViewGroup.LayoutParams params = listView.getLayoutParams(); - params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); - listView.setLayoutParams(params); - } - - - protected Waypoint mdWp; - protected final int SELECT_PIC_KITKAT=2000; - protected final int SELECT_PIC=3000; - - protected void showPicPicker(){ - Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT - intent.addCategory(Intent.CATEGORY_OPENABLE); - intent.setType("image/jpeg"); - if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){ - startActivityForResult(intent, SELECT_PIC_KITKAT); - }else{ - startActivityForResult(intent, SELECT_PIC); - } - } - - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - - super.onActivityResult(requestCode, resultCode, data); - if(requestCode ==SELECT_PIC_KITKAT ||requestCode ==SELECT_PIC) - if (resultCode == Activity.RESULT_OK) { -// picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH); -// Log.i(TAG, "最终选择的图片="+picPath); -// Bitmap bm = BitmapFactory.decodeFile(picPath); -// imageView.setImageBitmap(bm); - - Uri photoUri = data.getData(); - String path= Utils.getPath(activity,photoUri); - setMD(path,System.currentTimeMillis(),mdWp,mediaType.PIC); - - } - } - - protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){ - - } - - - - protected void logout(){ - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setTitle("确认要退出登录吗?") - .setNegativeButton("取消", null); - builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int which) { - - activity.app.logout(); - Toast.makeText(activity, "您已登出",Toast.LENGTH_SHORT).show(); - activity.isTabHome(); - - } - }); - builder.show(); - - } -} - - - - -//StringEntity entity=null; -//try { -// String trackstring=track.toString(); -// // QLog.getLogger().d(dTAG, TAG+"upload track: "+trackstring); -// entity=new StringEntity(trackstring); -//} catch (UnsupportedEncodingException e) { -// // TODO Auto-generated catch block -// // QLog.getLogger().d(dTAG, TAG+" "+e.getMessage()); -//} -//if(entity!=null) - - - - - - - /*JSONObject json = new JSONObject(); - try { - json.put("name", "android test"); - json.put("gpsSpan", "20000"); -// json.put("cmt", "this is a android test JSONOBJECT"); - json.put("userid", 1); - // QLog.getLogger().d(dTAG, TAG+" test track for uploading1: "+json.toString()); - String jsonString=new JSONStringer().object() - .key("name").value("android test").key("gpsSpan").value("20000").key("cmt").value("this is a android test JSONStringer").key("userid").value("1") - .endObject() - .toString(); - // QLog.getLogger().d(dTAG, TAG+" test track for uploading2: "+jsonString); - - entity = new StringEntity(json.toString() ); - entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));//Reason once you use some entity it will ignore content type given in post and use entity's content -// - if(entity!=null) - this.postJsonWS(entity, "mb/track/"); -// - entity = new StringEntity(jsonString ); - entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));//Reason once you use some entity it will ignore content type given in post and use entity's content - - - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } */ - - - - - /*Thread thread = new Thread(new Runnable(){ - @Override - public void run() { - try { - String url="http://home:8080/qiyouji/mb/track/"; - HttpPost request = new HttpPost(url); - JSONObject param = new JSONObject(); - try { - param.put("name", "android test"); - param.put("gpsSpan", "123456"); - param.put("userid", 1); - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - - JSONObject json = new JSONObject(); - - json.put("name", "android test"); - json.put("gpsSpan", "20000"); - json.put("cmt", "this is a android test HttpPost"); - json.put("userid", 1); - - StringEntity se; - try { - // QLog.getLogger().d(dTAG, TAG+" test track for uploading3: "+json.toString()); - se = new StringEntity(json.toString()); - request.setEntity(se); - request.setHeader("Content-Type", "application/json"); - HttpResponse httpResponse = activity.app.getHttpClient().execute(request); - String retSrc = EntityUtils.toString(httpResponse.getEntity()); - System.out.println(httpResponse.getStatusLine().getReasonPhrase()); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } catch (ClientProtocolException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - thread.start(); - -*/ - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Querybase_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Querybase_fragment.java deleted file mode 100644 index feec8a7..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Querybase_fragment.java +++ /dev/null @@ -1,2744 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.app.AlertDialog; -import android.app.Dialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.database.Cursor; -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.support.v4.app.LoaderManager.LoaderCallbacks; -import android.support.v4.content.CursorLoader; -import android.support.v4.content.Loader; -import android.support.v4.widget.SimpleCursorAdapter; -import android.support.v4.widget.SwipeRefreshLayout; -import android.text.Editable; -import android.text.InputType; -import android.text.SpannableString; -import android.text.Spanned; -import android.text.TextUtils; -import android.text.TextWatcher; -import android.text.method.LinkMovementMethod; -import android.text.style.ClickableSpan; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnTouchListener; -import android.widget.AbsListView; -import android.widget.AbsListView.OnScrollListener; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.DatePicker; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.RadioGroup; -import android.widget.RadioGroup.OnCheckedChangeListener; -import android.widget.ScrollView; -import android.widget.Spinner; -import android.widget.TextView; -import android.widget.TimePicker; -import android.widget.Toast; - -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.CItem; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.Note; -import com.qiyou.mb.android.beans.basic.NoteMessage; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.utils.ImageLoader; -import com.qiyou.mb.android.utils.NoScrollGridView; -import com.qiyou.mb.android.utils.QCursorAdapter; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.exception.NoWebObjectException; -import com.qiyou.mb.android.utils.image.ImageGridAdapter; -import com.qiyou.mb.android.utils.image.QimageView; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; -import com.qiyou.mb.android.utils.server.SharedLocation; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public abstract class Querybase_fragment extends QiyouFragment implements SwipeRefreshLayout.OnRefreshListener, LoaderCallbacks { - - public abstract void doQuery(); - - protected ImageLoader IL; - Button btn_live_list; - ImageView btn_live_query; - EditText edit_act_query; - Button btn_live_refresh; - - EditText etStartTime; - EditText etEndTime; - datePickerListener tl; - long custStartDate=0; - long custEndDate=0; - long startDate=0; - long endDate=0; - boolean firstLoad=false; - boolean isSwitchWebInputOnly = false; - String strStartTime="开始时间"; - String strEndTime="结束时间"; - private Button btnQuery; - LinearLayout llDtRange ; - LinearLayout ll_selection; - int trackType=0; - int webTrackType=0; - List typeLst ; -// protected TabHost tabhost; - ImageView btn_queryCates; - RadioGroup cateQueryRdGroup; - - - - protected List trackIds; - protected int queryType=0;//0,1,2...normal/cates/inactive - protected String lastWebQueryPara=""; - protected String lastActQueryPara=""; - protected String lastMemberQueryPara=""; - protected String lastGrpQueryPara=""; - ScrollView textContainer ; - protected int visibleItemCnt; - protected int visibleLastIndex; -// boolean isLoadMoreIndex=false; //when localTracklist clicked set it to -1; when loadmore,set it to visibleLastIndex - protected int lastIndexOnMore =-1; //when localTracklist clicked set it to -1; when loadmore,set it to visibleLastIndex - protected int BBScate = 0; - protected int BBSSubcate = 0; - protected int BBSSubcateOwner = 0; - protected String BBSsubCateName = ""; - protected ListView lvWeb = null; - protected ImageView imgWebPlus; - protected NoteMessage currentMsg; - protected Note currentNote; - Spinner spTrackType; -// Spinner spTrackTypeWeb; - Spinner spTrackDtRange;//St_SpinnerDateRange; - Spinner spWebInputType; - ArrayAdapter spAdapterWeb; - EditText txt_webinput; -// Map tabSpIndex; - Map> tabSpIndexValue; - private ArrayAdapter spAdapter; - private ArrayAdapter spDateAdapter; -// private ArrayAdapter spAdapterWeb; - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - initialCommonControlls(); - } - - protected void initialCommonControlls(){ -// if (vContainer.findViewById(R.id.swipRefresh) == null ){return;} - mSwipeLayout = (SwipeRefreshLayout)vContainer.findViewById(R.id.swipRefresh); - if (mSwipeLayout!=null){ - -// txt_swip_refrsh = (TextView)vContainer.findViewById(R.id.txt_swip_refrsh); - //设置刷新时动画的颜色,可以设置4个 - mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light); - mSwipeLayout.setOnRefreshListener(this); - - } - - textContainer =(ScrollView)vContainer.findViewById(R.id.td_scrollView); - - if(textContainer!=null) - textContainer.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - - initialWebListView(R.id.tr_listWeb); -// initialLoadingMore(); - - imgWebPlus =(ImageView)vContainer.findViewById(R.id.img_webAdd); - if (imgWebPlus!=null){ - imgWebPlus.setOnClickListener(ButtonOnClickListener); - imgWebPlus.setVisibility(View.GONE); - } - - - } - - void initialWebListView(int viewId){ - - } - - - void webAdd(){ - if(this.isGroupQuery) { - activity.showGroup(null); - }else if(this.isActivityQuery){ - activity.showActvity(null); - }else if(this.isBBSQuery){ - currentNote = new Note(); - currentNote.setUserId(activity.app.user.getUserbean().getId()); - currentNote.setCategory(this.BBScate); - currentNote.setCateOwnerId(BBSSubcateOwner); - currentNote.setSubCate(this.BBSSubcate); - currentNote.setSubCateName(BBSsubCateName); - activity.showNewNote(currentNote); - } - - } - - - protected void initialView(){ - - isCateQuery =true; - firstLoad=true; - btnQuery=(Button) vContainer.findViewById(R.id.st_btn_query); - - btn_queryCates=(ImageView) vContainer.findViewById(R.id.btn_CateQuery); - if(btn_queryCates!=null) - btn_queryCates.setOnClickListener(ButtonOnClickListener); - btnQuery.setOnClickListener(ButtonOnClickListener); - initTrackDateRangeSpin(); - etStartTime = (EditText)vContainer.findViewById(R.id.st_date_start); - etEndTime = (EditText) vContainer.findViewById(R.id.st_date_end); - tl = new datePickerListener(); - etStartTime.setOnTouchListener(tl); - etEndTime.setOnTouchListener(tl); - llDtRange =(LinearLayout)vContainer.findViewById(R.id.st_ll_custom); - ll_selection =(LinearLayout)vContainer.findViewById(R.id.ll_selection); - initQueryTrackTypeSpin(); -// initQueryTrackTypeSpinWeb(); - initialTabhost(); - cateLv = (com.qiyou.mb.android.ui.fragments.InnerGridView) vContainer.findViewById(R.id.cate_list); - if(cateLv!=null) - cateLv. setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - cateQueryRdGroup = (RadioGroup)vContainer.findViewById(R.id.catesQuery_rdGroup); - if(cateQueryRdGroup!=null) - cateQueryRdGroup.setOnCheckedChangeListener(rdgChanged); - doQuery(); - - } - OnCheckedChangeListener rdgChanged = new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(RadioGroup arg0, int arg1) { - // TODO Auto-generated method stub - //获取变更后的选中项的ID - int radioButtonId = arg0.getCheckedRadioButtonId(); - //根据ID获取RadioButton的实例 -// RadioButton rb = (RadioButton)activity.findViewById(radioButtonId); - - if(radioButtonId ==R.id.catesQuery_b){ - - cateQueryType=0; - }else if(radioButtonId ==R.id.catesQuery_j){ - - cateQueryType=1; - } - - } - }; - protected OnClickListener ButtonOnClickListener = new OnClickListener() { - @Override - public void onClick(View view) { - switch (view.getId() ){ - case R.id.st_btn_query: { - - // QLog.getLogger().d(dTAG, TAG+ " -------------------OnClickListener Get StatTrack. -------------" ); - doQuery() ; - break; - } - case R.id.btn_CateQuery: { - - doQuery(); - break; - } - case R.id.img_webAdd: { webAdd(); break; } - /*case R.id.btn_WebQuery: { //move to baisc fragment -// lastWebQueryPara=""; -// doQuery(); - initialWebQuery(); - break; - } - case R.id.btn_webpageup: { - - webPageup(); - break; - } - case R.id.btn_webpagedown: { -// lastWebQueryPara=""; - webPagedown(); - break; - }*/ - - } - } - }; - - -// void webPageup(){} -// void webPagedown(){} - void loadingMore(){} - void initialWebQuery(){} - protected void doCatesQuery(){ - buildIds(); - doQuery() ; - whereCates=""; - trackIds=null; - } - - -/* protected void doInactiveQuery(){ -// whereCates = " ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")="+TrackAvStatus.INACTIVE; - whereCates = TrackProvider.KEY_TRACK_AVSTATUS +"=="+TrackAvStatus.INACTIVE; - doQuery(); - }*/ - - protected void doRouteQuery(){ -// whereCates = " ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")="+TrackAvStatus.INACTIVE; - whereCates = TrackProvider.KEY_TRACK_TYPE +"=="+TrackType.GPX; - doQuery(); - } - - - - String whereCates=""; - int cateQueryType=0;//0,1..并集,交集 - /* - * build trackIds from Cates selected. - */ - protected void buildIds(){ - ArrayList ids =new ArrayList(); - // QLog.getLogger().d(dTAG, " cateQueryType? " +cateQueryType ); - whereCates="-1,"; - if(cateQueryType==0){ - for(String cate: activity.app.getQueryCategoryList()){ - // // QLog.getLogger().d(dTAG, " cate? " +cate ); - if(activity.app.mStatistics.getCategoryList().keySet().contains(cate)){ - ids.addAll(activity.app.mStatistics.getCategoryList().get(cate)); - // // QLog.getLogger().d(dTAG, " exits in activity.app.getQueryCategoryList(), add all ids of "+cate ); - // // QLog.getLogger().d(dTAG, " added ids is? "+activity.app.mStatistics.getCategoryList().get(cate) ); - } - } - - - }else - if(cateQueryType==1){ - String lastCate=""; - for(String cate: activity.app.getQueryCategoryList()){ - if(!activity.app.mStatistics.getCategoryList().keySet().contains(cate)){//not exist at all. - // // QLog.getLogger().d(dTAG, cate +" not exits in activity.app.getQueryCategoryList(),break.. " ); - ids.clear(); - break; - } - ArrayList cates =(ArrayList) activity.app.mStatistics.getCategoryList().get(cate).clone();//to avoid the retainAll removing the trackId .. - cates.remove(Integer.valueOf(0)); - if(cates.size()==0){ - ids.clear(); - break; - } - // // QLog.getLogger().d(dTAG, "lastCate ?"+lastCate); - // // QLog.getLogger().d(dTAG, "Cate ?"+cate); - // // QLog.getLogger().d(dTAG, "Cates ?"+cates); - if(!TextUtils.isEmpty(lastCate)) { - - ArrayList lastCates =activity.app.mStatistics.getCategoryList().get(lastCate); - cates.retainAll(lastCates); - if(cates.size()==0){ - ids.clear(); - break; - } - ids.retainAll(cates); - }else - ids.addAll(cates); - - if(ids.size()==0) break; - -// ids.addAll(cates); - lastCate=cate; - - } - - - - } - - getTrackIds().clear(); - - for(Integer i:ids){ - if(!getTrackIds().contains(i))getTrackIds().add(i); - } - for(Integer i:getTrackIds()){ - - whereCates+=i+"," ; - // // QLog.getLogger().d(dTAG, "whereCates ?"+whereCates); - } - if( whereCates.lastIndexOf(",")>1){ - whereCates=whereCates.substring(0,whereCates.lastIndexOf(",")); - } - whereCates =" _id in ("+whereCates+")"; - // // QLog.getLogger().d(dTAG, "whereCates ?"+whereCates); - } - - - - class datePickerListener implements View.OnTouchListener{ - - @Override - public boolean onTouch(View v, MotionEvent event) { - // TODO Auto-generated method stub - if (event.getAction() == MotionEvent.ACTION_DOWN) { - AlertDialog.Builder albuilder = new AlertDialog.Builder(activity); - -// dtview.getParent()getView(). -// if( dtview.getParent()!=null) -// ((ViewGroup) dtview.getParent()).removeView(dtview); //java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. - - - - LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - View dtview = inflater.inflate( R.layout.date_picker,null); - albuilder.setView(dtview); - - final DatePicker datePicker = (DatePicker) dtview.findViewById(R.id.date_picker); - - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(System.currentTimeMillis()); - datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); - /* new OnDateChangedListener() { - - public void onDateChanged(DatePicker view, int year, int monthOfYear, - int dayOfMonth) { - // TODO Auto-generated method stub - if (year>MAX) { - view.updateDate(MAX, monthOfYear, dayOfMonth); - }else if (yearSystem.currentTimeMillis()){ - cal = Calendar.getInstance(); - year =cal.get(Calendar.YEAR); - month =cal.get(Calendar.MONTH); - day =cal.get(Calendar.DAY_OF_MONTH); - cal.clear(); - cal.set(year, month, day); - } - custStartDate = cal.getTimeInMillis(); - etStartTime.setText(String.format("%d-%02d-%02d",year,month+1,day)); - etStartTime.setText(Utils.getShortFormatedTime(custStartDate)); - cal=null; - isFilterChanged =true; - if(custEndDate>0 && custEndDate < custStartDate){ - custEndDate = custStartDate; - - etEndTime.setText(etStartTime.getText()); -// etEndTime.setText( Utils.getShortFormatedTime(custStartDate)); - } -// datePicker.setMinDate(custStartDate); - } - }); - - } else if (v.getId() == R.id.st_date_end) { - int inType = etEndTime.getInputType(); - etEndTime.setInputType(InputType.TYPE_NULL); - etEndTime.onTouchEvent(event); - etEndTime.setInputType(inType); - etEndTime.setSelection(etEndTime.getText().length()); - - albuilder.setTitle("选取结束时间"); - albuilder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - - Calendar cal = Calendar.getInstance(); - cal.clear(); - cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); - int year =cal.get(Calendar.YEAR); - int month =cal.get(Calendar.MONTH); - int day =cal.get(Calendar.DAY_OF_MONTH); - - dialog.cancel(); - - if(cal.getTimeInMillis()>System.currentTimeMillis()){ - cal = Calendar.getInstance(); - year =cal.get(Calendar.YEAR); - month =cal.get(Calendar.MONTH); - day =cal.get(Calendar.DAY_OF_MONTH); - cal.clear(); - cal.set(year, month, day); - } - custEndDate = cal.getTimeInMillis(); -// etEndTime.setText(String.format("%d-%02d-%02d",year,month + 1,day)); - etEndTime.setText(Utils.getShortFormatedTime(custEndDate)); - cal=null; - isFilterChanged =true; - if(custEndDate < custStartDate){ - custStartDate=custEndDate; - etStartTime.setText(etEndTime.getText()); -// etStartTime.setText( Utils.getShortFormatedTime(custEndDate)); - } -// datePicker.setMaxDate(custEndDate); - } - }); - }else{ - - final TextView timeView =(TextView)vContainer.findViewById(v.getId()); - final int inType = timeView.getInputType(); - timeView.setInputType(InputType.TYPE_NULL); - timeView.onTouchEvent(event); - timeView.setInputType(inType); - - albuilder.setTitle("选取日期"); - albuilder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - - Calendar cal = Calendar.getInstance(); - cal.clear(); - cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); -// int year =cal.get(Calendar.YEAR); -// int month =cal.get(Calendar.MONTH); -// int day =cal.get(Calendar.DAY_OF_MONTH); - timeView.setText(Utils.getShortFormatedTime(cal.getTimeInMillis())); - dialog.cancel(); - - /* if(cal.getTimeInMillis()>System.currentTimeMillis()){ - cal = Calendar.getInstance(); - year =cal.get(Calendar.YEAR); - month =cal.get(Calendar.MONTH); - day =cal.get(Calendar.DAY_OF_MONTH); - cal.clear(); - cal.set(year, month, day); - }*/ - - /* custEndDate = cal.getTimeInMillis(); -// etEndTime.setText(String.format("%d-%02d-%02d",year,month + 1,day)); - etEndTime.setText(Utils.getShortFormatedTime(custEndDate)); - cal=null; - isFilterChanged =true; - if(custEndDate < custStartDate){ - custStartDate=custEndDate; - etStartTime.setText(etEndTime.getText()); -// etStartTime.setText( Utils.getShortFormatedTime(custEndDate)); - }*/ -// datePicker.setMaxDate(custEndDate); - } - }); - - - - } - - - Dialog dialog = albuilder.create(); - dialog.show(); - } - - return true; - } - - } - - int mHour; - int mMinute; -// long timePicked; - - class timePickerListener implements View.OnTouchListener{ - - @Override - public boolean onTouch(View v, MotionEvent event) { - // TODO Auto-generated method stub - if (event.getAction() == MotionEvent.ACTION_DOWN) { - AlertDialog.Builder albuilder = new AlertDialog.Builder(activity); - -// dtview.getParent()getView(). -// if( dtview.getParent()!=null) -// ((ViewGroup) dtview.getParent()).removeView(dtview); //java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. - - - - LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - View dtview = inflater.inflate( R.layout.time_picker,null); - albuilder.setView(dtview); - - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(System.currentTimeMillis()); - - final TimePicker timePicker = (TimePicker) dtview.findViewById(R.id.time_picker); - //初始化时间 - timePicker.setIs24HourView(true); - timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); - timePicker.setCurrentMinute(Calendar.MINUTE); - - final TextView timeView =(TextView)vContainer.findViewById(v.getId()); - -// if (v.getId() == R.id.act_edit_starttime) { - - final int inType = timeView.getInputType(); - timeView.setInputType(InputType.TYPE_NULL); - timeView.onTouchEvent(event); - timeView.setInputType(inType); -// timeView.setSelection(timeView.getText().length()); - - albuilder.setTitle("选取时间"); - albuilder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - - - mHour = timePicker.getCurrentHour(); - mMinute = timePicker.getCurrentMinute(); - //时间小于10的数字 前面补0 如01:12:00 - - timeView.setText(new StringBuilder().append(mHour < 10 ? 0 + mHour : mHour).append(":") - .append(mMinute < 10 ? 0 + mMinute : mMinute).append(":00") ); - - - dialog.cancel(); - - - - } - }); - - Dialog dialog = albuilder.create(); - dialog.show(); - } - - return true; - } - - } - - - class dateTimePickerListener implements View.OnTouchListener{ - - @Override - public boolean onTouch(View v, MotionEvent event) { - // TODO Auto-generated method stub - if (event.getAction() == MotionEvent.ACTION_DOWN) { - AlertDialog.Builder albuilder = new AlertDialog.Builder(activity); - -// dtview.getParent()getView(). -// if( dtview.getParent()!=null) -// ((ViewGroup) dtview.getParent()).removeView(dtview); //java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. - - - - LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - View dtview = inflater.inflate( R.layout.time_picker,null); - albuilder.setView(dtview); - - - - - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(System.currentTimeMillis()); - - final DatePicker datePicker = (DatePicker) dtview.findViewById(R.id.date_picker); - - datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); - - - - final TimePicker timePicker = (TimePicker) dtview.findViewById(R.id.time_picker); - //初始化时间 - timePicker.setIs24HourView(true); - timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); - timePicker.setCurrentMinute(Calendar.MINUTE); - - final TextView timeView =(TextView)vContainer.findViewById(v.getId()); - final int viewId=v.getId() ; -// if (v.getId() == R.id.act_edit_starttime) { - - final int inType = timeView.getInputType(); - timeView.setInputType(InputType.TYPE_NULL); - timeView.onTouchEvent(event); - timeView.setInputType(inType); - /* timeView.getLayoutParams().width=LayoutParams.WRAP_CONTENT; - LayoutParams lp = timeView.getLayoutParams(); - lp.width=LayoutParams.WRAP_CONTENT; - timeView.setLayoutParams(lp);*/ -// timeView.setSelection(timeView.getText().length()); - - albuilder.setTitle("选取日期和时间"); - albuilder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - - - Calendar cal = Calendar.getInstance(); - cal.clear(); - cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); -// cal.set(year, month, day, hourOfDay, minute) -// int year =cal.get(Calendar.YEAR); -// int month =cal.get(Calendar.MONTH); -// int day =cal.get(Calendar.DAY_OF_MONTH); -// timeView.setText(Utils.getShortFormatedTime(cal.getTimeInMillis())); - - -// mHour = timePicker.getCurrentHour(); -// mMinute = timePicker.getCurrentMinute(); - //时间小于10的数字 前面补0 如01:12:00 - cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),timePicker.getCurrentHour(), timePicker.getCurrentMinute()); - -// timeView.setText(new StringBuilder().append(mHour < 10 ? 0 + mHour : mHour).append(":") -// .append(mMinute < 10 ? 0 + mMinute : mMinute).append(":00") ); -// timeView.setText(Utils.getFormatedTime("yy/mm/dd HH:mm",cal.getTimeInMillis())); -// timeView.setText(Utils.getShortFormatedTime(cal.getTimeInMillis())); - - timeView.setText(Utils.getFormatedTime(cal.getTimeInMillis())); - - onTimePicked(viewId ,cal.getTimeInMillis()); - - dialog.cancel(); - - - - } - }); - - Dialog dialog = albuilder.create(); - dialog.show(); - } - - return true; - } - - } - - void onTimePicked(int viewId,long timePicked){ - - } - - - - - - void initQueryTrackTypeSpin(){ - - spTrackType = (Spinner)vContainer.findViewById(R.id.St_SpinnerTrackType); - // QLog.getLogger().d(dTAG,TAG+" 1 initTrackTypeSpin() lastTypeId,lastTypePos: "+ lastTypeId+","+lastTypePos); - - if(activity.app.mStatistics!=null && activity.app.mStatistics.getTypeUsedLst().size()>0){ - ArrayAdapter Adapter = new ArrayAdapter(getActivity(), - R.layout.myspinner, activity.app.mStatistics.getTypeUsedLst()); - Adapter.setDropDownViewResource(R.layout.spinner_item); - - spTrackType.setAdapter(Adapter); - // QLog.getLogger().d(dTAG,TAG+" 2 initTrackTypeSpin() lastTypeId,lastTypePos: "+ lastTypeId+","+lastTypePos); - - - - if(lastTypeId>0 && lastTypePos>0){ - spTrackType.setSelection(lastTypePos); - } else { - int type = activity.app.getLastTracktype(); - String t = TrackType.values()[type].toCHString(); - int pos = 0; - for(int i=0;i< activity.app.mStatistics.getTypeUsedLst().size();i++){ - if( activity.app.mStatistics.getTypeUsedLst().get(i).getValue().equalsIgnoreCase(t)){ - pos = i; - break; - } - } - - spTrackType.setSelection(pos); - - - } - } - else{ - int type_array=Utils.getTrackType();// R.array.trackType; -// if(QiYouConstant.DEVELOPER_MODE) -// type_array =R.array.trackType_develop_use; - //将可选内容与ArrayAdapter连接起来 - spAdapter = ArrayAdapter.createFromResource( activity,type_array, R.layout.myspinner); - - //设置下拉列表的风格 - spAdapter.setDropDownViewResource(R.layout.spinner_item); - - //将adapter2 添加到spinner中 - spTrackType.setAdapter(spAdapter); - } - -// lastTypeId=-1; -// lastTypePos=-1; - //将可选内容与ArrayAdapter连接起来 -/* spAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.trackType, R.layout.myspinner); - - //设置下拉列表的风格 - spAdapter.setDropDownViewResource(R.layout.spinner_item); - - //将adapter2 添加到spinner中 - spTrackType.setAdapter(spAdapter); -*/ - //添加事件Spinner事件监听 - spTrackType.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); - - //设置默认值 -// spTrackType.setVisibility(View.VISIBLE); -/* if(activity.app.mStatisticsTracks!=null) - for(int i=0; i-1 || lastTypePos>-1 ) { -// doQuery(); -// return; -// } - - spTrackDtRange = (Spinner)vContainer.findViewById(R.id.St_SpinnerDateRange); - - //将可选内容与ArrayAdapter连接起来 - spDateAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.trackDateRanger, R.layout.myspinner); - - //设置下拉列表的风格 - spDateAdapter.setDropDownViewResource(R.layout.spinner_item); - - //将adapter2 添加到spinner中 - spTrackDtRange.setAdapter(spDateAdapter); - - if(lastDtRangeId>-1 ){ - spTrackDtRange.setSelection(lastDtRangeId); - } -// lastDtRangeId =-1; - //添加事件Spinner事件监听 - spTrackDtRange.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); - - - //设置默认值 -// spTrackDtRange.setVisibility(View.VISIBLE); - - } - - /*void initQueryTrackTypeSpinWeb(){ - - spTrackTypeWeb = (Spinner)vContainer.findViewById(R.id.St_SpinnerTrackTypeWeb); - if(spTrackTypeWeb==null)return; - // QLog.getLogger().d(dTAG,TAG+" 1 initTrackTypeSpin() lastTypeId,lastTypePos: "+ lastTypeId+","+lastTypePos); - - int type_array=Utils.getTrackType();// R.array.trackType; - - //将可选内容与ArrayAdapter连接起来 - spAdapterWeb = ArrayAdapter.createFromResource( activity,type_array, R.layout.myspinner); - - //设置下拉列表的风格 - spAdapterWeb.setDropDownViewResource(R.layout.spinner_item); - - //将adapter2 添加到spinner中 - spTrackTypeWeb.setAdapter(spAdapterWeb); - int type = activity.app.getLastTracktype(); //设置首选 - spTrackTypeWeb.setSelection(type); - - spTrackTypeWeb.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); - - }*/ - -// void initWebQueryTypeSpinWeb(){ - - /* - tabSpIndex = new HashMap(); - tabSpIndex.put(0, 0); - tabSpIndex.put(1, 4); - tabSpIndex.put(2, 4); - tabSpIndex.put(3, 4); - - tabSpIndexValue = new HashMap>(); - HashMap tmp =new HashMap(); - tmp.put(0, ""); - tabSpIndexValue.put(0, tmp); - - tmp =new HashMap(); - tmp.put(4, ""); - tabSpIndexValue.put(1, tmp ); - - tmp =new HashMap(); - tmp.put(4, ""); - tabSpIndexValue.put(2, tmp); - - tmp =new HashMap(); - tmp.put(4, ""); - tabSpIndexValue.put(3, tmp); - - */ - - /*txt_webinput.setVisibility(View.VISIBLE); - txt_webinput.setHint("例如:"+QiYouConstant.PV_LAST_CITY); - txt_webinput.setText(QiYouConstant.PV_LAST_CITY); - txt_webinput.setInputType(InputType.TYPE_CLASS_TEXT);*/ - - -// } - - int lastDtRangeId=-1; - int lastTypeId=-1; - - int lastTypePos=-1; - int webLastTypePos=-1; - int webLastTypeId=-1; - boolean isFilterChanged=false; - //使用XML形式操作 - class SpinnerXMLSelectedListener implements OnItemSelectedListener{ - @Override - public void onItemSelected(AdapterView spinner, View textView, int spID, - long arg3) { -// view2.setText("你使用什么样的手机:"+adapter2.getItem(arg2)); - String cust ="自定义"; - switch (spinner.getId() ){ - case R.id.St_SpinnerDateRange: { - buildDateFilter(spID); - if(cust.equalsIgnoreCase(spDateAdapter.getItem(spID).toString())){ - llDtRange.setVisibility(View.VISIBLE); - custStartDate =0; - custEndDate=0; - etStartTime.setText(strStartTime); - etEndTime.setText(strEndTime); - - }else{ - llDtRange.setVisibility(View.GONE); - custStartDate =0; - custEndDate=0; - isFilterChanged =spID!=lastDtRangeId; - - if(isFilterChanged){ -// lastTypeId=spID; - lastDtRangeId=spID; - // QLog.getLogger().d(dTAG, TAG+ " -------------------R.id.St_SpinnerDateRange isFilterChanged Get StatTrack. -------------" ); - if(firstLoad){ - firstLoad=false; - }else - doQuery(); -// if(!firstLoad)doQuery(); - - } - } - - break; - } - case R.id.St_SpinnerTrackType: { -// trackType =spID; -// trackType =Integer.valueOf(((CItem)spTrackType.getSelectedItem()).GetID()); -// if(spTrackType.getSelectedItem() instanceof CItem && ((CItem)spTrackType.getSelectedItem()).GetID()!=null) - if(spTrackType.getSelectedItem() instanceof CItem && !TextUtils.isEmpty(((CItem)spTrackType.getSelectedItem()).getId()) ) - trackType =Integer.valueOf(((CItem)spTrackType.getSelectedItem()).getId()); - else - trackType=spID; - lastTypePos =spID; - isFilterChanged =trackType!=lastTypeId; - // QLog.getLogger().d(dTAG, TAG+ " spID is: " +spID +", last"); - firstLoad=false; - if(isFilterChanged){ -// lastDtRangeId=spID; - lastTypeId=trackType; - // QLog.getLogger().d(dTAG, TAG+ " -------------------R.id.St_SpinnerTrackType isFilterChanged Get StatTrack. -------------" ); - - if(firstLoad){ - firstLoad=false; -// return; - } -// if(!firstLoad) - doQuery(); - } - - break; - } - /*case R.id.St_SpinnerTrackTypeWeb:{ - webTrackType =spID; -// trackType =Integer.valueOf(((CItem)spTrackType.getSelectedItem()).GetID()); - if(spTrackTypeWeb.getSelectedItem() instanceof CItem && ((CItem)spTrackTypeWeb.getSelectedItem()).getId()!=null) - webTrackType =Integer.valueOf(((CItem)spTrackTypeWeb.getSelectedItem()).getId()); - else - webTrackType=spID; - lastTypePos =spID; - isFilterChanged =webTrackType!=webLastTypeId; - // QLog.getLogger().d(dTAG, TAG+ " spID is: " +spID +", last"); - firstLoad=false; - if(isFilterChanged){ -// lastDtRangeId=spID; - webLastTypeId=webTrackType; - // QLog.getLogger().d(dTAG, TAG+ " -------------------R.id.St_SpinnerTrackType isFilterChanged Get StatTrack. -------------" ); - - if(firstLoad){ - firstLoad=false; - return; - } -// if(!firstLoad) - doQuery(); - } - break; - }*/ - - } - - } - @Override - public void onNothingSelected(AdapterView arg0) { - - } - - } - - void webSpinnerSelected(int spID){ - - - } - - /* int MAX=2014; - int MIN=1990; - class DateChangeListener implements OnDateChangedListener{ - - public void onDateChanged(DatePicker view, int year, int monthOfYear, - int dayOfMonth) { - // TODO Auto-generated method stub - if (year>MAX) { - view.updateDate(MAX, monthOfYear, dayOfMonth); - }else if (year0?System.currentTimeMillis():0; - } - - protected void initialTabhost(){ - - } - - - //-----------------------------------track list -------query------begin--------------------------------------------------------------- - - boolean isWebTrackQuery; - boolean isByCatesQuery =false; -// boolean isInactiveQuery =false; - boolean isRouteQuery =false; - boolean isNormalQuery=false; - boolean isActivityQuery=false; - boolean isMemberQuery=false; - boolean isGroupQuery=false; - boolean isBBSQuery=false; - boolean isLiveQuery =false; - - int trackSvrNumber; - int svrTrackType; - long lastupdated; -// int actPageNo=1; -// int memberPageNo=1; - - int pageNo=1; - int pageSize=10; - -// int actSvrNumber; - int actType; - long actLastupdated; - - -// int grpSvrNumber; -// int grpPageNo=1; - - - - List> liveData; - Map> liveDataMap; - - void requestTrackFromWeb(int svrNumber){ - RequestParams params = new RequestParams(); - params.add("id", String.valueOf( svrNumber)); - params.add("swidth", String.valueOf(QiYouConstant.PV_INT_SCREEN_WIDTH)); - params.add("sheight", String.valueOf(QiYouConstant.PV_INT_SCREEN_HEIGHT)); - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params, RestMethods.TRACK_G_FIND_BY_ID/*"mb/track/"*/); -// long l1 = System.currentTimeMillis(); -// // QLog.getLogger().d("com.qiyou", TAG + " start Click item to show track detail, time is:" + l1); -// getJsonWs(null, "mb/track/" + this.svrNumber); -// /long l2 = System.currentTimeMillis() - l1; -// // QLog.getLogger().d("com.qiyou", TAG + " get data from web cost:" + l2); - } - - - - boolean checkJsonArray(JSONObject jsonObject) throws JSONException{ - - if(jsonObject==null || jsonObject.has("content") && jsonObject.has("first") - &&( jsonObject.getJSONArray("content") ==null ||jsonObject.getJSONArray("content").length()==0)){ -// showNotes("没有数据"); -// actData=null; - showNoRecText(true); -// return false; - } - - return true; - } - void showNoRecText(boolean isNoRec){ - - } - - - @Override - void processGetJsonObject(String method,JSONObject jsonObject,String msg) throws JSONException,NullPointerException, NoWebObjectException { - - super.processGetJsonObject(method, jsonObject, msg); - QLog.getLogger().d(dTAG, TAG+"------ge web query data back --------- method is " + method); -// if(this.isActivityQuery){ - - if(jsonObject==null){ - throw new NoWebObjectException(); - } - - - if(method.equalsIgnoreCase(RestMethods.ACT_G_LIST) - /*||method.equalsIgnoreCase(RestMethods.ACT_G_NEARBY_LIST)*/ ){ - if(checkJsonArray(jsonObject)){ - - processActPageInfo(jsonObject ); - // QLog.getLogger().d(dTAG, TAG+"------get act web query data--------- "); - // QLog.getLogger().d(dTAG, TAG+" activities : "+jsonObject.toString()); - - } - - } //its a single act. - else if(method.equalsIgnoreCase(RestMethods.ACT_G_FIND_BY_ID)){ - Activity_bean localAct_bean = (Activity_bean)Utils.getGsonObject(jsonObject.toString(), Activity_bean.class); - writeActivitiesCache(localAct_bean ); - showActivity(localAct_bean); - - return; - } - else if(method.equalsIgnoreCase(RestMethods.USER_G_LIST)){ -// if(jsonObject.has(QiYouConstant.JSONOBJECT_KEY)){// its a page - - // QLog.getLogger().d(dTAG, TAG+"------get member web query data--------- "); - if(checkJsonArray(jsonObject)){ -// // QLog.getLogger().d(dTAG, TAG+" members : "+jsonObject==null?null:jsonObject.toString()); - - processUserPageInfo(jsonObject ); - } - - } - //its a single data. - else if(method.equalsIgnoreCase(RestMethods.USER_G_FIND_BY_ID)){ -// if(jsonObject.has(QiYouConstant.JSONOBJECT_KEY)){ - User_bean user = (User_bean)Utils.getGsonObject(jsonObject.toString(), User_bean.class); - // writeActivitiesCache(String.valueOf(svrNumber) + this.actLastupdated, jsonObject); - // showWebTrack(new Track(localTrack_bean)); - showMember(user); -// activity.showUserDetails(user/*,0*/); - - - return; - } - - else if(method.equalsIgnoreCase(RestMethods.TRACK_G_LIST) - /* ||method.equalsIgnoreCase(RestMethods.TRACK_G_FIND_BY_ACT_GRP)*/ ){ - - - // QLog.getLogger().d(dTAG, TAG+"------get web query data--------- "); - if(checkJsonArray(jsonObject)){ - - processTrackPageInfo(jsonObject ); - } - - } else if(method.equalsIgnoreCase(RestMethods.TRACK_G_FIND_BY_ID)){ - //its a single track. - - Track_bean localTrack_bean = (Track_bean)Utils.getGsonObject(jsonObject.toString(), Track_bean.class); - writeWebTrackCache(String.valueOf(localTrack_bean.getSvrNumber()) + localTrack_bean.getLastdbTime(), jsonObject); - showWebTrack(new Track(localTrack_bean)); - - } else if(method.equalsIgnoreCase(RestMethods.LIVE_G_SHARE_LIST)){ - - // QLog.getLogger().d(dTAG, TAG+"------get live query data--------- "); - - // QLog.getLogger().d(dTAG, TAG+" shared locations: "+jsonObject==null?"null":jsonObject.toString()); - processLiveData(jsonObject.getJSONArray("list") ); - /*if( btn_live_refresh !=null){ - btn_live_refresh .setEnabled(true); - }*/ - } else if(method.equalsIgnoreCase(RestMethods.GRP_G_LIST)){ - if(checkJsonArray(jsonObject)){ - // QLog.getLogger().d(dTAG, TAG+"------get group web query data--------- "); - // QLog.getLogger().d(dTAG, TAG+" groups : "+jsonObject.toString()); - - processGrpPageInfo(jsonObject ); - } - } - else if(method.equalsIgnoreCase(RestMethods.GRP_G_FIND_BY_ID)){ //show a single group - - Group_bean grp_bean = (Group_bean)Utils.getGsonObject(jsonObject.toString(), Group_bean.class); -// writeActivitiesCache(String.valueOf(svrNumber) + this.actLastupdated, jsonObject); -// showWebTrack(new Track(localTrack_bean)); - showGroup(grp_bean); - - return; - }else if(method.equalsIgnoreCase(RestMethods.NOTE_G_LIST) ||method.equalsIgnoreCase(RestMethods.NOTEMSG_G_LIST) ) { - - if(checkJsonArray(jsonObject)){ - - - QLog.getLogger().d(dTAG, TAG+"------get notes web query data--------- "); - QLog.getLogger().d(dTAG, TAG+" notes : "+jsonObject.toString()); - - processNotesPageInfo(jsonObject ); - - } - - }else if(method.equalsIgnoreCase(RestMethods.NOTE_G_FIND_BY_ID) ) { - - activity.showNoteDetail( (Note)Utils.getGsonObject(jsonObject.toString(), Note.class),null); - - } - - } - - boolean isBBSLastPage; - void processNotesPageInfo(JSONObject jo) throws JSONException{ - if(jo==null){ - - return; - } - isBBSLastPage =jo.getBoolean("last"); -// isGrpFirstPage =jo.getBoolean("first"); - QLog.getLogger().d(dTAG, TAG+" isNoteLastPage--- " + isBBSLastPage); - - processNotesJsonArray(jo.getJSONArray("content")); - } - - -// boolean isFirstPage; - boolean isTrackLastPage; - void processTrackPageInfo(JSONObject jo) throws JSONException{ - if(jo==null){ - processTrackJsonArray(null); - return; - } -// jo.getInt("totalPages"); - isTrackLastPage =jo.getBoolean("last"); -// isFirstPage =jo.getBoolean("first"); -// jo.get("size");//pagesize -// jo.get("totalElements"); //总数 -// jo.get("numberOfElements");//返回个数 -// jo.get("number"); - -// this.btn_pagedown.setEnabled(!isLastPage); -// this.btn_pageup.setEnabled(!isFirstPage); - processTrackJsonArray(jo.getJSONArray("content")); - } -// boolean isActFirstPage; - boolean isActLastPage; - void processActPageInfo(JSONObject jo) throws JSONException{ - if(jo==null){ - processActJsonArray(null); - return; - } -// jo.getInt("totalPages"); -// isActLastPage =jo.getBoolean("last"); - isActLastPage =jo.getBoolean("last"); -// isActFirstPage =jo.getBoolean("first"); -// jo.get("size");//pagesize -// jo.get("totalElements"); //总数 -// jo.get("numberOfElements");//返回个数 -// jo.get("number"); - -// this.btn_pagedown.setEnabled(!isLastPage); -// this.btn_pageup.setEnabled(!isFirstPage); - processActJsonArray(jo.getJSONArray("content")); - } - -// boolean isGrpFirstPage; - boolean isGrpLastPage; - void processGrpPageInfo(JSONObject jo) throws JSONException{ - if(jo==null){ - processGrpJsonArray(null); - return; - } - isGrpLastPage =jo.getBoolean("last"); -// isGrpFirstPage =jo.getBoolean("first"); - // QLog.getLogger().d(dTAG, TAG+" isGrpLastPage--- " +isGrpLastPage); - - processGrpJsonArray(jo.getJSONArray("content")); - } - - boolean isMemberFirstPage; - boolean isMemberLastPage; - void processUserPageInfo(JSONObject jo) throws JSONException{ - if(jo==null){ - processUserJsonArray(null); - return; - } -// jo.getInt("totalPages"); -// isMemberFirstPage =jo.getBoolean("last"); - isMemberLastPage =jo.getBoolean("last"); -// isMemberLastPage =jo.getBoolean("first"); -// jo.get("size");//pagesize -// jo.get("totalElements"); //总数 -// jo.get("numberOfElements");//返回个数 -// jo.get("number"); - -// this.btn_pagedown.setEnabled(!isLastPage); -// this.btn_pageup.setEnabled(!isFirstPage); - processUserJsonArray(jo.getJSONArray("content")); - } - - - - void processNotesJsonArray(JSONArray jsonArrary){ - - } - - void processTrackJsonArray(JSONArray jsonArrary){ - - } - - void processUserJsonArray(JSONArray jsonArrary){ - - } - - void processActJsonArray(JSONArray jsonArrary){ - - } - - - - void showActivity(Activity_bean act) { - activity.showActvityHome(act); - } - - - void showWebTrack(Track tr){ - - } - void showGroup(Group_bean group) { - activity.showGroupHome(group); - } - - void showMember(User_bean user){ - activity.showUserHome(user/*,0*/); - } - - //--------------------end track act query list -------------------------- - - - - - //-------------------------------live query begin--------------------- - - long lastMaxLiveTime; // latest time stamp of received shared location - String lastLiveQueryPara=""; - int selectedLiveItem=-1; - ListView liveLv; - void doLiveQuery(){ - - Utils.hideSoftKeyboard(activity); -// noRec.setVisibility(View.GONE); -// this.isActShareQuery=true; - liveLv.setVisibility(View.VISIBLE); -// localTracklist.setVisibility(View.GONE); - // QLog.getLogger().d(dTAG, TAG+"------begin live query--------- "); - -// getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo); -// lastWebQueryPara - - /*if(this.firstLoad&&!TextUtils.isEmpty(lastLiveQueryPara)){ - // QLog.getLogger().d(dTAG, String.format("isfirstload%s last query para %s" , firstLoad,lastLiveQueryPara)); - return; - }*/ - RequestParams param=buildLiveQueryParames(); - if(param!=null /*&& !lastLiveQueryPara.equalsIgnoreCase(param.toString())*/ ){ - - // QLog.getLogger().d(dTAG, lastLiveQueryPara); - // QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param,RestMethods.LIVE_G_SHARE_LIST/*"mb/sharelocation/list"*/); - lastLiveQueryPara =param.toString(); - selectedLiveItem =-1; - /*if(btn_live_refresh!=null){ - btn_live_refresh.setEnabled(false); - }*/ - - } - - } - - - RequestParams buildLiveQueryParames(){ - return null; - } - - void processLiveData(JSONArray jsonArrary ) throws JSONException{ - if(jsonArrary==null){//no data - return; - } - -// JSONArray jsonArrary = jsonObject.getJSONArray(QiYouConstant.JSONOBJECT_KEY); - - - liveDataMap =liveDataMap==null? new HashMap>():liveDataMap; - - - - JSONObject jo = null; - SharedLocation sl; - ArrayList deltaList = new ArrayList(); - if(jsonArrary!=null) - for(int i=0;i " +jo.toString()); - sl=(SharedLocation) Utils.getGsonObject(jo.toString(), SharedLocation.class); - QLog.getLogger().d(dTAG, " sharedlocation data" +Utils.getGsonString(sl)); - deltaList.add(sl); - }catch( JsonSyntaxException je){ - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - - if(sl!=null){ -// tr= new Track(tb); - Map t = new HashMap(); -// t.put("abulm", sl.getName()); - t.put("username", sl.getName()); - t.put("userid", String.valueOf(sl.getId())); -// t.put("dist",Utils.getFormatedDistance(sl.getDist())); -// t.put("speed", String.format("%.0fkm/h", sl.getSpeed()*3.6)); -// t.put("time", Utils.getTimeCnt( java.lang.System.currentTimeMillis() - sl.getTime() )); -// t.put("time", Utils.getFormatedTime("hh:mm:ss", sl.getTime())); - t.put("sort", String.valueOf( sl.getTime())); - t.put("msg",sl.getMsg()); - t.put("lat", String.valueOf(sl.getLat())); - t.put("lon", String.valueOf(sl.getLon())); - - /* t.put("dist", String.format("%s", Utils.getFormatedDistance( - (float) Utils.getDistanceFromXtoY( sl.getLat(), sl.getLon(), - QiYouConstant.PV_LAST_LAT, QiYouConstant.PV_LAST_LON) )) );*/ - t.put("dist", sl.getLat()>0 &&QiYouConstant.PV_LAST_LAT>0? Utils.getFormatedDistance( - (float) Utils.getDistanceFromXtoY( sl.getLat(), sl.getLon(), - QiYouConstant.PV_LAST_LAT, QiYouConstant.PV_LAST_LON) ) - :"--"); - - String sportData =String.format("d%.0f s%.0f t%s", sl.getDist()/1000 - ,sl.getSpeed()*3.6 - ,Utils.getFormatedTime("HH:mm", sl.getTime()) - ); - t.put("sportdata",sportData); - // QLog.getLogger().d(dTAG, " share sport data is " + sportData); - lastMaxLiveTime =lastMaxLiveTime>sl.getTime()?lastMaxLiveTime:sl.getTime(); - liveDataMap.put(sl.getId(), t); - } - - - - } -// liveData = new ArrayList>() ; - if ( liveData != null ) { - liveData.clear(); - } else { - liveData = new ArrayList>() ; - } - liveData.addAll( liveDataMap.values()); - - -// for( Map map : liveData){ -// // QLog.getLogger().d(dTAG, " print befor sort.." + map.get("sort")); -// } - - Collections.sort(liveData, new SortByTime(SortByTime.DESC,"sort")); - -// for( Map map : liveData){ -// // QLog.getLogger().d(dTAG, " print after sort.." + map.get("sort")); -// } - - - showLiveData(); - - showLiveMap(deltaList); -// showLiveMap(liveDataMap.values()); - - }; - - - void showLiveMap(ArrayList deltaList) { }//draw shared locations on map - - - - QSimpleAdapter qsimpleAdapter; - int currentActRow=0; - protected void showLiveData( ){ - - - qsimpleAdapter = new QSimpleAdapter(activity,liveData,R.layout.live_list_detail, - new String[]{ - "abulm", - "username", - "dist", - /*"avspeed",*/ - "sportdata", - /*"time",*/ - /*"loc",*/ - "msg" - - }, - new int[]{ - R.id.share_photo, - R.id.share_name, - R.id.share_dist, - /* R.id.share_avspeed,*/ - R.id.share_sportdata, - /* R.id.share_time,*/ - /* R.id.share_loc,*/ - R.id.share_msg - - }); - - - - /* String toFind= this.edit_act_query.getText().toString().trim(); - if(!TextUtils.isEmpty(toFind)){ - - qsimpleAdapter.getFilter().filter(toFind); - } */ - -// qsimpleAdapter.getFilter().filter("a"); why filter not work.... - liveLv.setAdapter(qsimpleAdapter); - qsimpleAdapter.setSelectItem(selectedLiveItem); - liveLv.setSelection(selectedLiveItem); -// bindListView(qsimpleAdapter,liveLv,selectedLiveItem,true); - -// adapter.setSelectItem(selectedFoodmarkItem); -// localTracklist.setSelection(selectedFoodmarkItem); - -// localTracklist.smoothScrollToPosition(selectedFoodmarkItem); -// localTracklist.smoothScrollToPositionFromTop(selectedFoodmarkItem, 50); - } - - - - OnItemClickListener shareListItemListener = new OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - - selectedLiveItem =position; - - showSharePointOnMap(position); - - } - }; - - - void showSharePointOnMap(int position){ - - qsimpleAdapter.setSelectItem(position); - qsimpleAdapter.notifyDataSetInvalidated(); - liveLv.setSelection(position); - if(position<0)return; - HashMap localHashMap = (HashMap)this.qsimpleAdapter.getItem(position); - /* this.svrNumber = Integer.parseInt(localHashMap.get("userid")) ; - this.svrTrackType = Integer.parseInt(localHashMap.get("type")) ; - this.lastupdated = Long.parseLong(localHashMap.get("lastupdated")) ; - SharedLocation loc = new SharedLocation();*/ - - - showSharePaoPao(this.liveDataMap.get(Integer.valueOf( localHashMap.get("userid") ))); - } - - protected void showSharePaoPao(Map sharedLocation){ - - } - - - - void showShareListOnMap(){ - LinearLayout ll_list =(LinearLayout)vContainer.findViewById(R.id.share_ll_list); - if(ll_list==null) return; - - if(ll_list.getVisibility()==View.VISIBLE){ - ll_list.setVisibility(View.GONE); - btn_live_list.setText(R.string.share_show_list); - }else{ - ll_list.setVisibility(View.VISIBLE); - btn_live_list.setText(R.string.share_hide_list); - } - - } - void queryFromShareList(){ - - this.hideNotes(); - if(edit_act_query==null){ - return; - } - showSharePointOnMap(-1); - String toFind= this.edit_act_query.getText().toString().trim(); - if(TextUtils.isEmpty(toFind)){ - edit_act_query.setHintTextColor(Color.RED); - edit_act_query.setSelected(true); - this.showNotes("请输入查找的驴友名称"); - return;} - int position=0; - for(Map map:liveData){ - - if(map.get("username")!=null - && (map.get("username").equalsIgnoreCase(toFind) || map.get("username").contains(toFind))){ - - selectedLiveItem =position; - showSharePointOnMap(position); - return; -// break; - - } - - position++; - - } - this.showNotes("没找到 "+toFind); - -// qsimpleAdapter.getFilter().filter(toFind); -// liveLv.setAdapter(qsimpleAdapter); -// qsimpleAdapter.setSelectItem(-1); -// liveLv.setSelection(-1); -// qsimpleAdapter.notifyDataSetInvalidated(); - - } - - void onNameFindChange(){ - String toFind= this.edit_act_query.getText().toString().trim(); - if(TextUtils.isEmpty(toFind)){ - return; - }else{ -// showLiveData(); - try{ - - qsimpleAdapter.getFilter().filter(toFind); - }catch (NullPointerException e){ - - } -// qsimpleAdapter.setSelectItem(-1); -// liveLv.setSelection(-1); -// qsimpleAdapter.notifyDataSetInvalidated(); - } - } - - - TextWatcher watcher = new TextWatcher() { - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - // TODO Auto-generated method stub - - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, - int after) { - // TODO Auto-generated method stub - - } - - - @Override - public void afterTextChanged(Editable s) { - // TODO Auto-generated method stub - onNameFindChange(); - } - }; - - - //-----------------------------live list end --------------------------- - - - public List getTrackIds() { - if(trackIds==null)trackIds =new ArrayList(); - return trackIds; - } - - public void setTrackIds(List trackIds) { - this.trackIds = trackIds; - } - - - void requestUserFromWeb(int userId){ - if(userId<=0) return; - RequestParams params = new RequestParams(); -// params.add("id", String.valueOf( userId)); - -// // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); -// getJsonWs(params, "mb/user/"); - getJsonWs(params, RestMethods.USER_G_FIND_BY_ID/*"mb/user/"*/+userId); - - - - - } - void processGrpJsonArray(JSONArray jsonArrary) { - // TODO Auto-generated method stub - - } - - - // - - boolean isLoadingMore=false;//more button in the view clicked - protected TextView loadingMore; - protected ImageView loadingImg; - boolean canLoadingMore =false; - protected View ll_loadmore; - - - void initialLoadingMore(){ - ll_loadmore = activity.getLayoutInflater().inflate(R.layout.load_more, null); -// btn_loadMore=(Button)ll_loadmore.findViewById(R.id.loadMoreButton); -// btn_loadMore.setOnClickListener(ButtonOnClickListener); - loadingMore =(TextView)ll_loadmore.findViewById(R.id.loadMoreLable); - loadingImg =(ImageView)ll_loadmore.findViewById(R.id.img_loadMore); - } - private List> initialListData(List> listData ){ - if(listData==null ||/* !isLoadingMore ||*/ pageNo == 1){ //初始化,或者新查询 - QLog.getLogger().d(TAG, "isLoadingMore? "+ isLoadingMore +" ,pageNo: "+ pageNo); - listData= new ArrayList>() ; - } - isLoadingMore =false; - return listData; - } - - List> getListData(List> listData ,List> dataValue ){ - - - listData =initialListData(listData); - listData.addAll(dataValue); - - return listData; - } - - - - void bindListView(QSimpleAdapter qsimpleAdapter,ListView listView,int selectItem,boolean isLastPage){ - selectItem =lastIndexOnMore>0? - visibleLastIndex=pageSize){ - listView.addFooterView(ll_loadmore); -// } - listView.setAdapter( qsimpleAdapter); - if (visibleItemCnt > 0){ - selectItem -= visibleItemCnt -1 -1; - } - selectItem = selectItem <0 ? -1 : selectItem; - QLog.getLogger().d(dTAG, "------ can loading more visibleItemCnt: " + visibleItemCnt +",selectItem :"+selectItem); - - - if(lastIndexOnMore<=0){ - qsimpleAdapter.setSelectItem(selectItem); - } - listView.setSelection(selectItem); - listView.setDividerHeight(0); - listView.setVisibility(View.VISIBLE); - if (mSwipeLayout!=null){ - mSwipeLayout.setRefreshing(false); - } - - setNote(); - - } - - void setNote() {} - - class ListviewOnScroll implements OnScrollListener{ - - /** - * 滑动时被调用 - */ - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - visibleItemCnt = visibleItemCount; - visibleLastIndex = firstVisibleItem + visibleItemCount - 1; - } - - /** - * 滑动状态改变时被调用 - */ - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - int itemsLastIndex = view.getAdapter().getCount() - 1; //数据集最后一项的索引 - int lastIndex = itemsLastIndex;// + 1; //加上底部的loadMoreView项 - // QLog.getLogger().d("com.qiyou",String.format("lastIndex is %s,visiblelastIndex is %s", lastIndex,visibleLastIndex)); - if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { - //如果是自动加载,可以在这里放置异步加载数据的代码 - if(!canLoadingMore){ - return; - } - loadingMore(); - // QLog.getLogger().d("com.qiyou"," LOADMORE loading..."); - } - } - - - } - - - - @Override - public void onRefresh() { - // TODO Auto-generated method stub - QLog.getLogger().d(dTAG, "refreshing....."); - this.doQuery(); -// this.initialWebQuery(); - - - } - - - - //------------ lcoal for track list - - protected Cursor cursor = null; - protected QCursorAdapter adapter; - - protected ProgressDialog progressDialog ; - - protected ListView localTracklist = null; - - protected String whereClause=null; - protected int selectedTrackItem=-1; - protected CheckBox chk_show_map; - protected TextView txtNote; - protected CheckBox chk_show_pic; - /** - * {@inheritDoc} - * This loader will return the ID, Reference, Name, and Distance of all the venues - * currently stored in the {@link PlacesContentProvider}. - */ - @Override - public Loader onCreateLoader(int id, Bundle args) { - String[] projection = new String[] {TrackProvider.KEY_ID,TrackProvider.KEY_TRACK_START_TIME, - TrackProvider.KEY_TRACK_DISTANCE,TrackProvider.KEY_TRACK_SPORT_TIME,TrackProvider.KEY_TRACK_CAL_BURNING, - TrackProvider.KEY_TRACK_COMMENT,TrackProvider.KEY_TRACK_NAME,TrackProvider.KEY_TRACK_DESC, - TrackProvider.KEY_TRACK_MDWPS,TrackProvider.KEY_TRACK_CREATOR,TrackProvider.KEY_TRACK_END_TIME, - TrackProvider.KEY_TRACK_STATUS,TrackProvider.KEY_LAST_UPDATE_TIME,TrackProvider.KEY_SVR_NUMBER, - TrackProvider.KEY_TRACK_ROAD_BEARS}; - -// String orderby =(lastTypeId==TrackType.GPX.toInt())?TrackProvider.KEY_TRACK_STATUS+","+TrackProvider.KEY_ID +" DESC":TrackProvider.KEY_ID +" DESC"; -// String orderby =( TrackProvider.KEY_LAST_UPDATE_TIME +" DESC"); - String orderby =( TrackProvider.KEY_ID +" DESC"); - return new CursorLoader(activity, TrackProvider.TRACKS_URI, - projection, whereClause, null, orderby); - } - - /* Loader getCursor() { - String[] projection = new String[] {TrackProvider.KEY_ID,TrackProvider.KEY_TRACK_START_TIME, - TrackProvider.KEY_TRACK_DISTANCE,TrackProvider.KEY_TRACK_SPORT_TIME, - TrackProvider.KEY_TRACK_COMMENT,TrackProvider.KEY_TRACK_NAME,TrackProvider.KEY_TRACK_DESC, - TrackProvider.KEY_TRACK_MDWPS}; - - return new CursorLoader(activity, TrackProvider.TRACKS_URI, - projection, whereClause, null, TrackProvider.KEY_ID +" DESC"); - }*/ - - @Override - public void onLoadFinished(Loader arg0, Cursor arg1) { - // TODO Auto-generated method stub - if(this.isWebTrackQuery)return; - if(this.isActivityQuery)return; - if(progressDialog!=null) - progressDialog.dismiss(); - if(adapter ==null) return; - adapter.swapCursor(arg1); - showNoRecText(adapter.getCount()==0); - - if(!isFilterChanged){ - adapter.setSelectItem(selectedTrackItem); - localTracklist.setSelection(selectedTrackItem); - QLog.getLogger().d(dTAG, TAG+" selectedTrackItem:"+selectedTrackItem); - } - - - } - - - - @Override - public void onLoaderReset(Loader arg0) { - // TODO Auto-generated method stub - if(adapter==null)return; - adapter.swapCursor(null); - - } - - - - - public void doTrackQuery(){ - /* - isByCatesQuery =queryType ==2; -// isInactiveQuery =queryType ==2; - isRouteQuery =queryType ==1; - isNormalQuery =queryType ==0;*/ - final boolean isGpx =(lastTypeId==TrackType.GPX.toInt()) ||isRouteQuery; -// final Track tr = new Track(); - - final ArrayList showingGpxIds =activity.app.getGpxShowingTracks(); - if(isByCatesQuery /*|| isRouteQuery ||isInactiveQuery*/){//by cates - buildIds() ; - whereClause = whereCates; - }else if( isRouteQuery){ - whereClause = whereCates; - } else - /* if(isNormalQuery)*/{ - - endDate=System.currentTimeMillis(); - - if(custStartDate>0||custEndDate>0){ - startDate =custStartDate; - endDate =custEndDate; - endDate=endDate==0?System.currentTimeMillis():endDate; - } -// endDate=endDate==0?System.currentTimeMillis():endDate; - - - -// String timeCol= trackType==TrackType.GPX.toInt()? TrackProvider.KEY_TRACK_CREATE_TIME: TrackProvider.KEY_TRACK_START_TIME; - String timeCol= TrackProvider.KEY_TRACK_CREATE_TIME; - String timeColOld= TrackProvider.KEY_TRACK_START_TIME; - - whereClause = String.format("(%s >=%s and %s <= %s or %s >=%s and %s <= %s )", timeCol,startDate,timeCol,endDate, - timeColOld,startDate,timeColOld,endDate); - - whereClause += " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " = " + trackType; - -// whereClause = timeCol + " >= "+ startDate + " and " -// + timeCol + " <= "+ endDate -// + " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " = " + trackType; - } - - whereClause=TextUtils.isEmpty(whereClause)?"1=1 ":whereClause; -// if(!isInactiveQuery) -// whereClause+= " and ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")=="+TrackAvStatus.ACTIVE; -// whereClause+=" and ( ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")!=" +TrackAvStatus.DELETED + -// " OR " + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")"; - - whereClause+=" and ( " + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")"; - - - QLog.getLogger().d(dTAG, TAG+" query tracklist whereClause: "+whereClause); - - adapter = new QCursorAdapter( - activity, -// android.R.layout.two_line_list_item, - isGpx? R.layout.gpx_list_detail: R.layout.track_list_detail, - cursor, //null, // 什么时候初始化的?.......................... onLoadFinished adapter.swapCursor(data); - new String[] {TrackProvider.KEY_TRACK_START_TIME, TrackProvider.KEY_TRACK_DISTANCE, - TrackProvider.KEY_TRACK_SPORT_TIME, TrackProvider.KEY_TRACK_CAL_BURNING, - TrackProvider.KEY_TRACK_COMMENT, - TrackProvider.KEY_TRACK_DESC, TrackProvider.KEY_TRACK_NAME - ,TrackProvider.KEY_TRACK_MDWPS,TrackProvider.KEY_TRACK_CREATOR, - TrackProvider.KEY_TRACK_END_TIME, TrackProvider.KEY_TRACK_STATUS, - TrackProvider.KEY_TRACK_STATUS,TrackProvider.KEY_SVR_NUMBER, - TrackProvider.KEY_TRACK_ROAD_BEARS}, -// new int[] {android.R.id.text1, android.R.id.text2}, - new int[] {R.id.trakList_tv_starttime, R.id.trakList_tv_dist,R.id.trakList_tv_avs,R.id.trakList_tv_burn, - R.id.trakList_tv_comment,R.id.trakList_tv_sportTime,R.id.trakList_tv_desc,R.id.trakList_tv_name - ,R.id.trakList_gridView,R.id.trakList_tv_creator, R.id.trakList_tv_svrNo,R.id.trakList_tv_showGpx,R.id.trakList_staticMap,R.id.trakList_staticMap}, - 0); - // Allocate the adapter to the List displayed within this fragment. - - - adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { - - @Override - public boolean setViewValue(View view, Cursor cursor, int columnIndex) { - -// if(columnIndex == 1) { -// -// TextView text = (TextView) view; // get your View -// -// text.setText(Utils.getFormatedTime(cursor.getLong(1) )); //set some data -// -// return true; -// -// } - - TextView text ; // get your View - String unvailable="--"; - switch (view.getId() ){ - case R.id.trakList_tv_name: { - String name =cursor.getString(6); - if(TextUtils.isEmpty(name)) - name ="No."+cursor.getString(0); - text = (TextView) view; - text.setText( Utils.getShortString(name,10)); //set some data - return true; - } - case R.id.trakList_tv_creator: { - text = (TextView) view; - String creator = Utils.getShortString( cursor.getString(9),20 ) ; - if(!TextUtils.isEmpty(creator)){ - text.setText( creator) ; - text.setVisibility(View.VISIBLE); - } - return true; - } - case R.id.trakList_tv_svrNo: { - text = (TextView) view; - - int svrNumber =cursor.getInt(13) ; - if(svrNumber>0){ - text.setText( "云编号:" + svrNumber) ; -// text.setVisibility(View.VISIBLE); - }else - text.setText( "未上传") ; - return true; - } - - - case R.id.trakList_tv_starttime: { - text = (TextView) view; - text.setText(" "+Utils.getFormatedTimeMonthDay(cursor.getLong(1) )); //set some data - return true; - } - case R.id.trakList_tv_dist: { -// TextView text = (TextView) view; // get your View - text = (TextView) view; - text.setText( String.format("%.2f",cursor.getFloat(2)/1000.0 ) ); //set some data - return true; - } - case R.id.trakList_tv_avs: { -// TextView text = (TextView) view; // get your View - text = (TextView) view; - /*float f=cursor.getLong(3)>0? 3600*cursor.getFloat(2)/cursor.getLong(3):0; - if(isGpx){ - f=cursor.getLong(10)-cursor.getLong(1)>0? 3600*cursor.getFloat(2)/(cursor.getLong(10)-cursor.getLong(1)):0; - }*/ - float f=cursor.getLong(10)-cursor.getLong(1)>0? 3600*cursor.getFloat(2)/(cursor.getLong(10)-cursor.getLong(1)):0; //tavs - if(f>0) - text.setText(String.format("%.2f",f) ); //set some data - else - text.setText(unvailable); //set some data - return true; - } - - case R.id.trakList_tv_showGpx: { -// CheckBox cb = (CheckBox) view; -// ((CheckBox) view).setChecked(cursor.getInt(11)==TrackStatus.ACTIVE.toInt()); - -// String v =(cursor.getInt(11)==TrackStatus.ACTIVE.toInt())?"是":"否"; - boolean isShowing=(showingGpxIds.contains(cursor.getInt(0))); -// String v =(activity.app.getGpxShowingTracks().contains(cursor.getInt(0)))?"是":"否"; - text = (TextView) view; - text.setText(isShowing?"是":"否"); - if(isShowing) - text.setTextColor(Color.RED); - else - text.setTextColor(Color.GRAY); - return true; - } - case R.id.trakList_tv_burn: { -// TextView text = (TextView) view; // get your View - text = (TextView) view; - float b=cursor.getFloat(4); - if(b>0) - text.setText(String.format("%.0f",b) ); //set some data - else - text.setText(unvailable ); //set some data - return true; - } - - case R.id.trakList_tv_comment: { -// TextView text = (TextView) view; // get your View - text = (TextView) view; - String str=Utils.getShortString( cursor.getString(5),20 ) ; - if(TextUtils.isEmpty(str)) - text.setVisibility(View.GONE); - else{ - text.setText( str ); //set some data - text.setVisibility(View.VISIBLE); - } - - return true; - } - case R.id.trakList_tv_sportTime: { -// TextView text = (TextView) view; // get your View - text = (TextView) view; - /*long b=cursor.getLong(3); - if(isGpx){ - b=cursor.getLong(10)-cursor.getLong(1) ; - }*/ - long b=cursor.getLong(10)-cursor.getLong(1) ; //total time - if(b>0) - text.setText( Utils.getTimeCnt(b)); //set some data - else - text.setText(unvailable ); //set some dat - - return true; - } - case R.id.trakList_tv_desc: { -// TextView text = (TextView) view; // get your View - text = (TextView) view; - String str=Utils.getShortString( cursor.getString(7),20 ) ; - if(TextUtils.isEmpty(str)) - text.setVisibility(View.GONE); - else{ - text.setText( str ); //set some data - text.setVisibility(View.VISIBLE); - } - return true; - } - - case R.id.trakList_staticMap: { - if(chk_show_map !=null && !chk_show_map.isChecked()) - return true; -// TextView text = (TextView) view; // get your View - QimageView imgv = (QimageView) view; -// tr.getTrackBean().setTrackId( cursor.getInt(0)); - - /*if(!Utils.isNetworkConnected(activity)){ - if(tr.isStaticMapExist()){ -// IL.DisplayImage(tr.getStaticMap(),imgv); Utils.getBaiduStaticMapUrl(tr); - - imgv.setVisibility(View.VISIBLE); - } - else - imgv.setVisibility(View.GONE); - - return true; - }*/ - asyncImageLoad(imgv,cursor.getInt(0),cursor.getLong(10) ); - /* Track tr;//=new Track(cursor.getInt(0),null,null,cursor.getString(14),null); -// tr=new Track(cursor.getInt(0), true,null,null); - tr=new Track(); - tr.getTrackBean().setTrackId(cursor.getInt(0)); - tr.assemblyContent(); - -// if(tr.getTrackBean().getRoadWps().size()>1){ - if(tr.getTrackBean().getTrkseg().size()>1){ - tr.setStartWp(new Waypoint()); - tr.setLastWp(new Waypoint()); - tr.setMaxDistWp(new Waypoint()); - tr.getLastWp().setWb(tr.getTrackBean().getRoadWps().get(tr.getTrackBean().getRoadWps().size()-1)); - tr.getStartWp().setWb(tr.getTrackBean().getRoadWps().get(0)); - tr.getMaxDistWp().setWb(tr.getLastWp().getWb()); - String staticUrl= Utils.getBaiduStaticMapUrl(tr); - if(TextUtils.isEmpty(staticUrl)){ - imgv.setVisibility(View.GONE); - }else{ - imgv.setVisibility(View.VISIBLE); - IL.DisplayImage(staticUrl,imgv); - } - }*/ - - return true; - } - - - case R.id.trakList_gridView: { -// TextView text = (TextView) view; // get your View - if(chk_show_pic !=null && !chk_show_pic.isChecked()) - return true; - int picCnt=4; - String[] Urls=getImages(cursor.getString(8),picCnt,cursor.getInt(13)); //pic cnt = screen.width/80 - NoScrollGridView gridView =(NoScrollGridView) view; - if(Urls!=null && Urls.length>0){ - - /* if(Urls.length<4){ - String[] newUrls =new String[4]; - for(int i=0;i parent, View view, int position, long id) { -// imageBrower(position,Urls); -// localTracklist.callOnClick(); -// picGridClickedPosition =adapter.getCursor().getPosition(); -// localTracklist.performItemClick(gridView, position, id) - - int mpos = ((NoScrollGridView)parent).cursorPosition; -// localTracklist.requestFocusFromTouch(); -// localTracklist.setSelection(mpos); -// adapter.setSelectItem(mpos); - localTracklist.performItemClick(localTracklist.getAdapter().getView(mpos, null, null), mpos, mpos); - - } - }); - - } - else{ - gridView.setVisibility(View.GONE); - } - - -// NoScrollGridView gridView =(NoScrollGridView) view; - - - - return true; - } - - - } - - - return false; - - } - - }); - - - - localTracklist.setAdapter(adapter); - getLoaderManager().restartLoader(0, null, this); - - - if(ll_loadmore==null){ - initialLoadingMore(); - loadingMore.setText( R.string.loadmore_complete ); - loadingImg.setBackgroundResource( R.drawable.icon_stop ); - } - localTracklist.removeFooterView(ll_loadmore); - localTracklist.addFooterView(ll_loadmore); - - // Populate the adapter / list using a Cursor Loader. - - - - -// progressDiaQLog.getLogger().dismiss(); -// activity.app.playBack=false; //TODO: review if it can be here. - /* if(adapter.getCount()>0) -// if(adapter.getCursor().getCount()>0) -// if(adapter.getCursor().getCount()>0) - noRec.setVisibility(View.GONE); - else - noRec.setVisibility(View.VISIBLE);*/ - - } - - - void asyncImageLoad(QimageView imageView,int trackId,long endTime) { - AsyncImageTask asyncImageTask = new AsyncImageTask(imageView,trackId,endTime); - asyncImageTask.execute(); - - } - - - - String[] getImages(String mdJson,int cnt,int svrNumber){ - - Track tr = new Track(null,null,null,mdJson); - tr.getTrackBean().setSvrNumber(svrNumber); - return tr.getPicList(cnt); - - - } - - /** - * 使用AsyncTask异步加载图片 - * - * @author Administrator - * - */ - private final class AsyncImageTask extends AsyncTask { - private QimageView imageView; - private int trackId=0; - private long endTime=0; - public AsyncImageTask(QimageView imageView,int trackId,long endTime) { - this.imageView = imageView; - this.trackId=trackId; - this.endTime=endTime; - } - - /*protected Uri doInBackground(String... params) {// 子线程中执行的 - try { - return ContactService.getImage(params[0], cache); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - }*/ - - - @Override - protected void onPostExecute(String staticUrl) {// 运行在主线程 - if (!TextUtils.isEmpty(staticUrl) && imageView != null) - if(TextUtils.isEmpty(staticUrl)){ - imageView.setVisibility(View.GONE); - }else{ - imageView.setVisibility(View.VISIBLE); -// QLog.getLogger().d(dTAG, "imageloader to DisplayImage url is:"+staticUrl); - if(IL!=null) - IL.DisplayImage(staticUrl,imageView); - } - } - - @Override - protected String doInBackground(String... params) { - - Track tr =new Track(); - tr.getTrackBean().setTrackId(trackId); - tr.getTrackBean().setEndTime(endTime); - return tr.getStaticMap(); - - } - - - } - - boolean canclick =true; - Handler handler; - - OnItemClickListener trackListItemListener = new OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - - if(!canclick)return; - canclick =false; - - selectedTrackItem =position; - - - if(adapter==null){ - return; - } - Cursor c = adapter.getCursor(); - if(c==null || c.getCount()==0 || c.getCount() == position ){ - QLog.getLogger().d(dTAG, TAG+ " No record, return........ " ); - - return; - } - - adapter.setSelectItem(position); - adapter.notifyDataSetInvalidated(); - selectedTrackItem =position; - - - final long startClicktime=System.currentTimeMillis(); - QLog.getLogger().d(dTAG, - TAG+" start Click item to show track detail, time is:"+startClicktime); - -// if(progressDialog==null) - progressDialog = ProgressDialog.show(activity, "请稍等...", "正在读取记录数据...", true); - progressDialog.setCancelable(true); - progressDialog.setCanceledOnTouchOutside(true); - - final long afterDialog =System.currentTimeMillis()-startClicktime; - - QLog.getLogger().d(dTAG, - TAG+" show progressDialog cost:"+afterDialog); - final int mPosition= position; - - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog - - - if(msg.what==1){ - Toast.makeText(activity, "查询超时...",Toast.LENGTH_SHORT).show(); - } - else if(msg.what==0){ - showDetailTrack(trackId); - } - - progressDialog.dismiss(); - canclick =true; - - QLog.getLogger().d(dTAG, - TAG+ " progressdialog dismissed:"+(System.currentTimeMillis()-afterDialog-startClicktime)); - }}; - - new Thread(){ - - @Override - public void run() { - //需要花时间计算的方法 - Cursor c = adapter.getCursor(); - if(c==null || c.getCount()==0 || c.getCount() == mPosition ){ - QLog.getLogger().d(dTAG, TAG+ " No record, return........ " ); - - return; - } - c.moveToPosition(mPosition); -// final String trackId = c.getString(c.getColumnIndex(TrackProvider.KEY_ID)); -// int trackId = c.getInt(c.getColumnIndex(TrackProvider.KEY_ID)); - trackId = c.getInt(c.getColumnIndex(TrackProvider.KEY_ID)); - QLog.getLogger().d(dTAG, TAG+ "start request for track of id "+ trackId ); - - int topWaiting=0; -// String[] ids = new String[]{String.valueOf(Integer.valueOf(trackId) -1),trackId}; -// String[] ids = new String[]{ "-1" ,trackId}; -// QLog.getLogger().d(dTAG, TAG+ "..................Start to get ids............. "+ System.currentTimeMillis() ); -// activity.app.getTracks(ids); - if(activity.app.recordingTrack!=null - &&activity.app.recordingTrack.getTrackBean().getTrackId()==trackId - &&(activity.app.currentTrack==null ||activity.app.currentTrack.getTrackBean().getTrackId()!=trackId) - ){ - if(activity.app.mStatistics!=null){ - activity.app.mStatistics.mergeTrack( activity.app.recordingTrack); - } - activity.app.currentTrack=activity.app.recordingTrack; - QLog.getLogger().d(dTAG, TAG+" set currentTrack to recordingTrack "); - - }else{ - activity.app.getTrack( trackId); - QLog.getLogger().d(dTAG, TAG+" start to load track from db: "+trackId); - - } - QLog.getLogger().d(dTAG, TAG+" app.getCurrentTrack().getTrackBean().getTrackId() is:" +activity.app.getCurrentTrack().getTrackBean().getTrackId()+" trackId is,"+trackId); - -// Statics_bean sb; -// if(activity.app.mStatistics!=null -// &&activity.app.mStatistics.getStatisticsTracks().get(lastTypeId)!=null){ -// sb=activity.app.mStatistics.getStatisticsTracks().get(lastTypeId).getSbs().get(trackId); -// } - - - while( activity.app.mStatistics==null - ||( - isNormalQuery && ( - activity.app.mStatistics.getStatisticsTracks().get(lastTypeId)==null - || activity.app.mStatistics.getStatisticsTracks().get(lastTypeId).getSbs().get(new Integer(trackId))==null - ) - ||/*(isByCatesQuery || isRouteQuery ||isInactiveQuery) &&*/ activity.app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId) - ) - ) - -// while( activity.app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId) -//// ||app.getStatTrack().getType()!=app.getCurrentTrack().getTrackBean().getType().toInt() -// ) - { - - try { - Thread.sleep(50); - topWaiting+=50; - QLog.getLogger().d(dTAG, TAG+" topWaiting:"+topWaiting); - - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB/2 ) - { - QLog.getLogger().d(dTAG, TAG+" topWaiting:"+topWaiting+",limit is:"+QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB ); - if(activity.app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId)) - { - handler.sendEmptyMessage(1); - - } else - handler.sendEmptyMessage(0); - -// showDetailTrack(trackId); - return; - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - QLog.getLogger().d(dTAG, TAG+" to show track detail...."); - -// showDetailTrack(trackId); - handler.sendEmptyMessage(0); - }}.start(); - - - - } - - - }; - - - - void showDetailTrack(int trackId){ - - } - - - protected void setUserLinkSpanTxt(TextView txt,final int userId,String name){ - txt.setText(getUserLinkSpanTxt(userId,name)); - txt.setMovementMethod(LinkMovementMethod.getInstance()); - } - - - protected SpannableString getUserLinkSpanTxt(final int userId,String name){ - SpannableString spannableString1 = new SpannableString(name); - spannableString1.setSpan(new ClickableSpan() { - @Override - public void onClick(View view) { - - final int cate = BBSCate.USER.toInt(); - String cacheKey = cate + "-" + userId; - String restMethod = ""; - Boolean isCached = activity.app.getWebObjcache().containsKey(cacheKey); - - if (isCached) { - User_bean obj = (User_bean) activity.app.getWebObjcache() - .get(cacheKey); - showMember(obj); - - } else { - restMethod = RestMethods.USER_G_FIND_BY_ID; - } - - - if (!TextUtils.isEmpty(restMethod)){ - RequestParams params = new RequestParams(); - params.add("id", String.valueOf( userId)); - QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params,restMethod ); - } - - } - - }, - 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - - return spannableString1; - } - - - - - - - - void doMemberOperation(int svrId, String svrName,int ownerId,int userId,String userName,final String restMethod){ - - if(userId<=0||svrId<=0){ - return; - } - - final JSONObject json = new JSONObject(); - try { - json.put("svrId", String.valueOf(svrId)); - json.put("userId", String.valueOf( userId)); - json.put("ownerId", String.valueOf( ownerId)); - json.put("userName", userName); - json.put("svrName", svrName); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - if(restMethod.equalsIgnoreCase(RestMethods.ACT_P_DEL_MEMBER) - || restMethod.equalsIgnoreCase(RestMethods.GRP_P_DEL_MEMBER)) { - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setMessage("确认继续此退出操作?"); - builder.setTitle("提示"); - builder.setCancelable(false); - builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - - postJsonWS(json.toString(), restMethod); - - - } - }); - builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - }); - builder.create().show(); - }else - postJsonWS(json.toString(), restMethod); - - - - - - - /*if(btn_actJoin.getText().toString().equalsIgnoreCase(getResources().getString(R.string.act_join))) - postJsonWS(json.toString(), RestMethods.ACT_P_ADD_MEMBER"mb/activity/addmember"); - else - postJsonWS(json.toString(),RestMethods.ACT_P_DEL_MEMBER "mb/activity/delmember");*/ - - - } - - } - - -class SortByTime implements Comparator> { - - public static int ASC=1; - public static int DESC =-1; - // public static String sortByTime="time"; - // public static String sortByDist="dist"; - // public static String sortByRange=4; - - private int direction; - private String column; - public SortByTime(int sortDirection, String sortColumn){ - direction = sortDirection; - column = sortColumn; - } - - @Override - public int compare(Map map1, Map map2) { - // TODO Auto-generated method stub - - if(Long.valueOf(map1.get("sort"))>Long.valueOf(map2.get("sort"))){ - return -1; - } - - return 1; - } - - - - } - - - - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/RegistFragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/RegistFragment.java deleted file mode 100644 index 4991473..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/RegistFragment.java +++ /dev/null @@ -1,302 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.io.UnsupportedEncodingException; - -import org.apache.http.Header; -import org.apache.http.client.CookieStore; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.cookie.Cookie; -import org.apache.http.entity.StringEntity; -import org.apache.http.protocol.HttpContext; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.app.ProgressDialog; -import android.content.Context; -import android.database.Cursor; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnClickListener; -import android.view.View.OnTouchListener; -import android.widget.Button; -import android.widget.EditText; -import android.widget.TextView; -import android.widget.Toast; - -import com.loopj.android.http.AsyncHttpClient; -import com.loopj.android.http.AsyncHttpResponseHandler; -import com.loopj.android.http.JsonHttpResponseHandler; -import com.loopj.android.http.PersistentCookieStore; -import com.loopj.android.http.RequestParams; -import com.loopj.android.http.TextHttpResponseHandler; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.utils.QiyouRestClient; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; - -public class RegistFragment extends LoginFragment/*QiyouFragment*/ { - - @Override - public void setFTag() { - TAG = "com.qiyou.RegistFragment"; - } - - public static String getFTag() { - return "com.qiyou.RegistFragment"; - } - - @Override - public String getCurrentTag() { - return "com.qiyou.RegistFragment"; - } - - public static RegistFragment newInstance() { - RegistFragment f = new RegistFragment(); - return f; - } - - - // Error Msg TextView Object - TextView errorMsg; - // Name Edit View Object - EditText nameET; - // Email Edit View Object - EditText emailET; - // Passwprd Edit View Object - EditText pwdET; - String password ; - private Button btnRegister; - private Button btnLinkToLoginScreen; - Context context; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - if(!activity.is4Login)onBack(); - activity.updateActionBarTitle(R.string.frg_regist); - context=activity.getApplicationContext(); - // activity=(MainActivity)getActivity(); - // activity.app.currentActiveFragment =TAG; - vContainer = inflater.inflate(R.layout.register, container, false); - initialView(); - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - } - - void initialView() { - - errorMsg = (TextView)vContainer.findViewById(R.id.register_error); - // Find Name Edit View control by ID - nameET = (EditText)vContainer.findViewById(R.id.registerName); - // Find Email Edit View control by ID - emailET = (EditText)vContainer.findViewById(R.id.registerEmail); - // Find Password Edit View control by ID - pwdET = (EditText)vContainer.findViewById(R.id.registerPassword); - // Instantiate Progress Dialog object - prgDialog = new ProgressDialog(activity); - - btnRegister = (Button) vContainer.findViewById(R.id.btnRegister); - btnRegister.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - try { - registNewUser(); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }); - btnLinkToLoginScreen = (Button) vContainer.findViewById(R.id.btnLinkToLoginScreen); - btnLinkToLoginScreen.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - activity.showLogin(); - } - }); - - - } - - /** - * Method gets triggered when Login button is clicked - * - * @param view - * @throws JSONException - * @throws UnsupportedEncodingException - */ - public void registNewUser() throws JSONException, UnsupportedEncodingException { - // Get Email Edit View Value - // Get NAme ET control value - String name = nameET.getText().toString(); - // Get Email ET control value - String email = emailET.getText().toString(); - // Get Password ET control value - password = pwdET.getText().toString(); - // Instantiate Http Request Param Object -// name="guangyu3"; -// email="1.qq@com"; -// password="123456"; - - // When Email Edit View and Password Edit View have values other than - // Null - if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(name)) { - - if(TextUtils.indexOf(name, " ")>0){ - Toast.makeText(activity, "账户名不能有空格", - Toast.LENGTH_LONG).show(); - }else - if(name.length()<2){ - Toast.makeText(activity, "账户名太短了", - Toast.LENGTH_LONG).show(); - }else - - // When Email entered is Valid - if (QiYouConstant.DEVELOPER_MODE||Utils.validate(email)) { - // Put Http parameter username with value of Email Edit View - // control - /*JSONObject json = new JSONObject(); - json.put("account", name); - json.put("email", email); - json.put("passwd", Utils.getMD5Str(password)); - postJsonWS(json.toString(),RestMethods.USER_P_SUBMIT"mb/user/"); - QLog.getLogger().d(dTAG, "注册 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"); - QLog.getLogger().d(dTAG, json.toString());*/ -// StringEntity entity = new StringEntity(json.toString()); -// invokeWS(entity); -// postJsonWS(entity,"mb/user/login"); -// params.put("json", strparams); - -// params.put("username", email); - // Put Http parameter password with value of Password Edit Value - // control -// params.put("password", password); - // Invoke RESTful Web Service with Http parameters -// invokeWS(params); - - User_bean u = new User_bean(); - u.setPassword(Utils.getMD5Str(password)); - u.setMail(email); - u.setAccount(name); - u.setUserName(name); - u.setLat(QiYouConstant.PV_LAST_LAT); - u.setLon(QiYouConstant.PV_LAST_LON); - u.setPhoneId(activity.app.getPhoneId()); - QLog.getLogger().d(dTAG, Utils.getGsonString(u)); - u.setLoginType(0); - postJsonWS(Utils.getGsonString(u),RestMethods.USER_P_REGIST); - - - - } - // When Email is invalid - else { - Toast.makeText(activity, "请输入正确的邮箱", - Toast.LENGTH_LONG).show(); - } - } - // When any of the Edit View control left blank - else { - Toast.makeText(activity, - "请输入完整的注册信息", - Toast.LENGTH_LONG).show(); - } - - } - - @Override - void processJsonObject(String method,JSONObject response,String msg)throws JSONException{ - - User_bean ub =(User_bean) Utils.getGsonObject(response.toString(), User_bean.class); - QLog.getLogger().d(dTAG,"注册成功" ); - QLog.getLogger().d(dTAG, response.toString() ); - Toast.makeText(activity, - "注册成功!", - Toast.LENGTH_LONG).show(); - - activity.app.updateUserPref(ub); - activity.app.setAuth(); -// getFragmentManager().popBackStack(); -// onBack(); -// onBack(); - updatePushAlias(); - activity.isTabHome(); -// activity.app.updateUserPref(response.getInt("id"), -// response.getString("mail"), -// response.getString("account"), -// password -// ); - } - - -/* void testCookies(){ -// AsyncHttpClient client = new AsyncHttpClient(); - HttpContext httpContext = QiyouRestClient.getHttpContext(); - - CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);//获取AsyncHttpClient中的CookieStore - if(cookies!=null){ - for(Cookie c:cookies.getCookies()){ - QLog.getLogger().d(dTAG,"main before ~~"+c.getName()+","+c.getValue()); - } - }else{ - QLog.getLogger().d(dTAG,"main before~~,cookies is null"); - } - - //save cookie - PersistentCookieStore myCookieStore = new PersistentCookieStore(context); - QiyouRestClient.setCookieStore(myCookieStore); - - httpContext = QiyouRestClient.getHttpContext(); - cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE); - if(cookies!=null){ - QLog.getLogger().d(dTAG, "main after~~,cookies is not null"); - for(Cookie c:cookies.getCookies()){ - QLog.getLogger().d(dTAG,"main after ~~"+c.getName()+","+c.getValue()); - } - }else{ - QLog.getLogger().d(dTAG, "main after~~,cookies is null"); - } - - }*/ - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } - //http://blog.csdn.net/zhaoyazhi2129/article/details/26983145 - @Override - public void showNotes(String notes,Boolean showToast){ - if(TextUtils.isEmpty(notes))return; - - Toast.makeText(activity,notes,Toast.LENGTH_SHORT ).show(); - - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Route_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Route_fragment.java deleted file mode 100644 index 96eaa01..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Route_fragment.java +++ /dev/null @@ -1,3066 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.annotation.SuppressLint; -import android.app.ProgressDialog; -import android.content.Context; -import android.graphics.Color; -import android.location.Location; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.RadioGroup; -import android.widget.RadioGroup.OnCheckedChangeListener; -import android.widget.SimpleAdapter.ViewBinder; -import android.widget.Spinner; -import android.widget.TabHost; -import android.widget.TabHost.OnTabChangeListener; -import android.widget.TextView; -import android.widget.Toast; - -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.overlayutil.OverlayManager; -import com.baidu.mapapi.overlayutil.PoiOverlay; -import com.baidu.mapapi.search.core.PoiInfo; -import com.baidu.mapapi.search.core.RouteLine; -import com.baidu.mapapi.search.core.SearchResult; -import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener; -import com.baidu.mapapi.search.poi.PoiCitySearchOption; -import com.baidu.mapapi.search.poi.PoiDetailResult; -import com.baidu.mapapi.search.poi.PoiDetailSearchOption; -import com.baidu.mapapi.search.poi.PoiIndoorResult; -import com.baidu.mapapi.search.poi.PoiResult; -import com.baidu.mapapi.search.poi.PoiSearch; -import com.baidu.mapapi.search.route.BikingRouteLine.BikingStep; -import com.baidu.mapapi.search.route.BikingRoutePlanOption; -import com.baidu.mapapi.search.route.BikingRouteResult; -import com.baidu.mapapi.search.route.DrivingRouteLine.DrivingStep; -import com.baidu.mapapi.search.route.DrivingRoutePlanOption; -import com.baidu.mapapi.search.route.DrivingRouteResult; -import com.baidu.mapapi.search.route.IndoorRouteResult; -import com.baidu.mapapi.search.route.MassTransitRouteResult; -import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener; -import com.baidu.mapapi.search.route.PlanNode; -import com.baidu.mapapi.search.route.RoutePlanSearch; -import com.baidu.mapapi.search.route.TransitRouteResult; -import com.baidu.mapapi.search.route.WalkingRouteLine.WalkingStep; -import com.baidu.mapapi.search.route.WalkingRoutePlanOption; -import com.baidu.mapapi.search.route.WalkingRouteResult; -import com.mobeta.android.dslv.DragSortListView; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.FileScan; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.WorkingTrackType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@SuppressLint("NewApi") -public class Route_fragment extends TrackTabs_fragment implements IlocationFragment - { -// public static final String TAG ="com.qiyou.track_fragment"; -// public static final String dTAG ="com.qiyou"; - @Override - public void setFTag(){ - TAG="com.qiyou.Route_fragment"; - } - public static String getFTag(){ - return "com.qiyou.Route_fragment"; - } - @Override - public String getCurrentTag(){ - -// //// QLog.getLogger().e(dTAG,TAG+" Track_fragment, app.currentActiveFragment: "+activity.app.currentActiveFragment); - return "com.qiyou.Route_fragment"; - - } - - public Route_fragment() { - // TODO Auto-generated constructor stub - workingTrackType= WorkingTrackType.ROUTE; - } - - - - private ImageButton btnRouteStart; - private ImageButton btnRouteWps; - private ImageButton btnRouteTent; - private ImageButton btnRouteCheck; - private ImageButton btnRouteHand; -// rt_btnTent -// rt_btnRest - private ImageButton btnRouteRest; - private ImageButton btnRouteEnd; - private Button btnRouteSearch; - private Button btnRouteReset; - private Button btnRouteSave; - private HashMap oldComments ; - protected ImageView rt_cross; - private TextView txtNote; - private EditText cityNameView ; - private ImageButton btnSearch; - private EditText rt_txt_target ; - - protected RoutePlanSearch mSearch = null; - PoiSearch mPoiSearch = null; // 搜索模块,也可去掉地图模块独立使用 - - - private int geoType=-1; //0,1,2..start,wps,end - private LatLng startPt=null; - private LatLng endPt=null; - private int custWpNumber=-1; - private wpFlag currentWpFlag; - private int custWpMarkNumber=0; -// private int custTentMarkNumber=0; - - -// List pts = new ArrayList(); -// private final String WAYPIONTS="路点"; - - private TrackOverlay mGpOverlay = null; //start,end,cust - private RouteOverlay routeOverlay =null; // track route -// private /*OverlayItem*/ MarkerOptions mCurItem = null; - - private MyPoiOverlay poiOverlay ; - /* private CopyOnWriteArrayList roadWbs = new CopyOnWriteArrayList();*/ - private ArrayList roadWbs = new ArrayList(); -// private ArrayList mdWbs = new ArrayList(); - private float avSpeed=20f/3600f;//米/毫秒 - private Track gpxTrack=null; -// private ArrayAdapter adapter; -// private ArrayAdapter drableAdapter; - private overLayItemListAdapter OverLayItemAdapter; - private DragSortListView lv; -// private final String INPUT_TARGET="查询地址"; - - private int icon_start=R.drawable.icon_st; - private int icon_end=R.drawable.icon_en; - - private ListView filelv; - private Button mbtn_import; - private Button mbtn_refresh; - private TextView txt_importNote; - private List> gpxFileList ; - private final String exchangeTab ="导入"; - private final String historyTab = "历史"; -// private CheckBox chck_mainRoad; -// private boolean isAllowMainRoad=false; - - - protected RoadOverlay gpxStartOverlay =null; - protected RoadOverlay gpxEndOverlay =null; - - MarkerOptions startItem=null; -// Marker startMarker; - MarkerOptions endItem=null; -// Marker endMarker; - /*TrackOverlay*/ List wpItems =null; - /*TrackOverlay*/ List wpNumItems =null; -// List wpItems =new ArrayList(); -// List wpNumItems =new ArrayList(); - - public static Route_fragment newInstance(int trackId) - { - - Route_fragment f = new Route_fragment(); - Bundle args = new Bundle(); - args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId); - f.setArguments(args); - return f; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if(activity!=null &&activity.app!=null) - activity.app.playBack=false; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - vContainer = inflater.inflate(R.layout.route_fragment, container, false); - activity.updateActionBarTitle(R.string.frg_route); - if (trackId<=0 && getArguments() != null) { - trackId =getArguments().getInt(QiYouConstant.EXTRA_KEY_ID); - - } - if(trackId<=0 && activity.app.isNaving && activity.app.naviTrackId>0){ - trackId=activity.app.naviTrackId; - } - - initialGpxTrack(); - - super. onCreateView( inflater, container, savedInstanceState); - - -// mTrack =activity.app.getRecordingTrack(); -// vContainer = inflater.inflate(R.layout.track_fragment, container, false); -// initialViews(); -// initialTabhost(); -// initialFootmark(); - - if(chk_showChats!=null) - chk_showChats.setVisibility(View.GONE); - if(btnCamera!=null) - btnCamera.setVisibility(View.GONE); - -// setWorkingTrack(); - - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - -// myLocationOverlay.enableCompass(); -// mMapController.setCompassMargin(100, 230); - - routeInitial(); - - } - - @Override - void getExtrArgs(){ - - } - - protected void routeInitial(){ - avSpeed=activity.app.getRAVS(); - // QLog.getLogger().d(dTAG, " routeInitial to load track...loadFromTrack()" ); - loadFromTrack( ); - getWaypointListData(); - isSilence=false; - routeReset(); - if(!activity.app.playBack) - drawGpx(); - } - - @Override - protected void initialViews(){ - super.initialViews(); - initalFinderViews(); -// chck_mainRoad=(CheckBox)vContainer.findViewById(R.id.chck_mainRoad); -// chck_mainRoad.setOnCheckedChangeListener(CheckboxListener); - - - -// GridLayout grid_top_txt =(GridLayout)vContainer.findViewById(R.id.grid_top_txt); -// grid_top_txt.setVisibility( View.GONE ); - vContainer.findViewById(R.id.grid_top_txt).setVisibility( View.GONE ); - - localTracklist =(ListView)vContainer.findViewById(R.id.tr_list); - localTracklist.setOnItemClickListener(trackListItemListener); - - LinearLayout topBtns =(LinearLayout)vContainer.findViewById(R.id.rt_ll_topButttons); - topBtns.setVisibility( View.VISIBLE ); - - btnRouteStart=(ImageButton) vContainer.findViewById(R.id.rt_btnStart); - btnRouteWps=(ImageButton) vContainer.findViewById(R.id.rt_btnWps);// - btnRouteEnd=(ImageButton) vContainer.findViewById(R.id.rt_btnEnd);// - btnRouteTent =(ImageButton) vContainer.findViewById(R.id.rt_btnTent);// - btnRouteRest =(ImageButton) vContainer.findViewById(R.id.rt_btnRest);// - btnRouteCheck =(ImageButton) vContainer.findViewById(R.id.rt_btnCheck);// - btnRouteHand =(ImageButton) vContainer.findViewById(R.id.rt_btnHand);// - - - btnRouteSearch=(Button) vContainer.findViewById(R.id.rt_btnCalculate); - btnRouteReset=(Button) vContainer.findViewById(R.id.rt_btnReset);// - btnRouteSave=(Button) vContainer.findViewById(R.id.rt_btnSave);// - btnNavi=(Button) vContainer.findViewById(R.id.rt_btnNav);// - - btnReverse=(Button) vContainer.findViewById(R.id.rt_btnReverse); - btnReverse.setOnClickListener( ButtonOnClickListener); - btnNavi.setOnClickListener( ButtonOnClickListener); - btnNavi.setEnabled(trackId>0 &&!activity.app.isNaving); - btnSNav=(Button) vContainer.findViewById(R.id.rt_btnSNav);// - btnSNav.setOnClickListener( ButtonOnClickListener); - btnSNav.setEnabled(trackId>0 &&!activity.app.isNaving); - btnSaveScreen=(ImageButton) vContainer.findViewById(R.id.tm_btnSaveScreen); - btnSearch=(ImageButton) vContainer.findViewById(R.id.rt_search);// - btnLocation =(ImageButton) vContainer.findViewById(R.id.tm_btnLocaiton); - if(this.btnLocation!=null){ - btnLocation.setOnClickListener(ButtonOnClickListener); - btnLocation.setVisibility(View.VISIBLE); - } - - btnRouteCheck.setVisibility(View.VISIBLE); - btnRouteHand.setVisibility(View.VISIBLE); - btnRouteStart.setVisibility(View.VISIBLE); - btnRouteWps.setVisibility(View.VISIBLE); - btnRouteEnd.setVisibility(View.VISIBLE); - btnRouteTent.setVisibility(View.VISIBLE); - btnRouteRest.setVisibility(View.VISIBLE); - - btnRouteStart.getBackground().setAlpha(alpha); - btnRouteWps.getBackground().setAlpha(alpha); - btnRouteEnd.getBackground().setAlpha(alpha); - btnRouteTent.getBackground().setAlpha(alpha); - btnRouteRest.getBackground().setAlpha(alpha); - btnRouteHand.getBackground().setAlpha(alpha); - btnRouteCheck.getBackground().setAlpha(alpha); - - - btnRouteCheck.setOnClickListener( ButtonOnClickListener); - btnRouteRest.setOnClickListener( ButtonOnClickListener); - btnRouteTent.setOnClickListener( ButtonOnClickListener); - btnRouteStart.setOnClickListener( ButtonOnClickListener); - btnRouteWps.setOnClickListener( ButtonOnClickListener); - btnRouteEnd.setOnClickListener( ButtonOnClickListener); - btnRouteSearch.setOnClickListener( ButtonOnClickListener); - btnRouteReset.setOnClickListener( ButtonOnClickListener); - btnRouteSave.setOnClickListener( ButtonOnClickListener); - btnSaveScreen.setOnClickListener( ButtonOnClickListener); - btnRouteHand.setOnClickListener( ButtonOnClickListener); - btnSearch.setOnClickListener( new OnClickListener() { - @Override - public void onClick(View view) { - txtNote.setText(null); - searchButtonProcess(); - } - } - ); - btnNavi.setOnClickListener( new OnClickListener() { - @Override - public void onClick(View view) { - startNavi(false); - } - } - ); - btnRouteSave.setEnabled(false); -// btnRouteSave.setVisibility(View.GONE); -// CrossIcon rt_cross =(CrossIcon) vContainer.findViewById(R.id.rt_cross); -// rt_cross.setVisibility(View.VISIBLE); -// - rt_cross =(ImageView) vContainer.findViewById(R.id.rt_cross); - rt_cross.setVisibility(View.VISIBLE); -// txtNote =(TextView) vContainer.findViewById(R.id.rt_notice); - - - txtNote.setVisibility(View.VISIBLE); - -// CrossIcon mi = new CrossIcon(activity); -// activity.getWindow().addContentView(mi,new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); - - if(!Utils.isNetworkConnected(activity)){ - txtNote.setText(null); - showMsg("制作路书需要链接互联网,请检查网络链接。"); - } - - initialGpxViews(); -// canLocationMap=true; -// updateUI(activity.app.lastLocation, false); -// locationInMap(null); - - - - /* wpItems =new TrackOverlay(mBaiduMap); - wpNumItems =new TrackOverlay(mBaiduMap);*/ - - wpItems =new ArrayList(); - wpNumItems = new ArrayList(); - routeOverlay = new RouteOverlay(mBaiduMap); - } - - - void initalFinderViews(){ - cityNameView = (EditText)vContainer.findViewById(R.id.rt_txt_city); - cityNameView.setText(QiYouConstant.PV_LAST_CITY); - - rt_txt_target= (EditText)vContainer.findViewById(R.id.rt_txt_target); - rt_txt_target.setSelectAllOnFocus(true); - txtNote =(TextView) vContainer.findViewById(R.id.rt_notice); - btnSearch=(ImageButton) vContainer.findViewById(R.id.rt_search);// - btnSearch.setOnClickListener( new OnClickListener() { - @Override - public void onClick(View view) { - txtNote.setText(null); - searchButtonProcess(); - } - } - ); - btnLocation =(ImageButton) vContainer.findViewById(R.id.tm_btnLocaiton); - if(this.btnLocation!=null) btnLocation.setOnClickListener(ButtonOnClickListener); - } - - /* protected CheckBox.OnCheckedChangeListener CheckboxListener =new CheckBox.OnCheckedChangeListener(){ - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { -// // QLog.getLogger().d(dTAG, "gpx_checkbox checked?" +chck_mainRoad.isChecked()); - isAllowMainRoad =isChecked; - txtNote.setText(null); - showMsg(isAllowMainRoad?"路线规划将优先采用机动车道,请注意避免逆行":"路线规划将优先采用非机动车道"); - - } - - };*/ - - - @Override - protected void initViewMap(){ - initialMapview(); - -// mMapView.getOverlays().clear(); -// mGpOverlay = new MyOverlay(getResources().getDrawable(R.drawable.empty_photo),mMapView); - mGpOverlay = new TrackOverlay(mBaiduMap); -// bearStartOverlay =getItemizedOverlay(R.drawable.icon_bstart); -// bearEndOverlay =getItemizedOverlay(R.drawable.icon_bend); - -// mMapView.getOverlays().add(mGpOverlay); -// gpxOverlay =new GraphicsOverlay(mMapView); -// mMapView.getOverlays().add(gpxOverlay); -// gpxStartOverlay =getItemizedOverlay(R.drawable.icon_bstart); -// gpxEndOverlay=getItemizedOverlay(R.drawable.icon_bend); - //创建 弹出泡泡图层 -// createPaopao(); - - //地图点击事件处理 - - initialMkSearch(); - - initialPoiSearch(); - - - - } - - void initialPoiSearch(){ - - mPoiSearch = PoiSearch.newInstance(); - - mPoiSearch.setOnGetPoiSearchResultListener( - - new OnGetPoiSearchResultListener(){ - - - public void onGetPoiResult(PoiResult result) { - processAddress(result); - } - - public void onGetPoiDetailResult(PoiDetailResult result) { - if (result.error != SearchResult.ERRORNO.NO_ERROR) { - - showMsg("抱歉,未找到结果"); - - } else { - Toast.makeText(activity, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT) - .show(); - - } - } - - @Override - public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) { - - } - - } - - ); - - } - - void processAddress(PoiResult result ){ - if (result == null - || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) { - - showMsg( "未找到结果"); - - return; - } - if (result.error == SearchResult.ERRORNO.NO_ERROR) { -// mBaiduMap.clear(); - if(poiOverlay==null){ - poiOverlay = new MyPoiOverlay(mBaiduMap); - } - mBaiduMap.setOnMarkerClickListener(poiOverlay); - poiOverlay.setData(result); - poiOverlay.addToMap(); - poiOverlay.zoomToSpan(); - - showMsg( "找到 "+result.getTotalPoiNum() +"个 相关地点"); - - return; - } - /*if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) { - - // 当输入关键字在本市没有找到,但在其他城市找到时,返回包含该关键字信息的城市列表 - String strInfo = "在"; - for (CityInfo cityInfo : result.getSuggestCityList()) { - strInfo += cityInfo.city; - strInfo += ","; - } - strInfo += "找到结果"; - showMsg(strInfo); - - }*/ - } - - private int directionRate = 1; - - - void initialMkSearch(){ - - - // 初始化搜索模块,注册事件监听 - mSearch = RoutePlanSearch.newInstance(); - - mSearch.setOnGetRoutePlanResultListener( - - new OnGetRoutePlanResultListener(){ - - String instructions=""; - String exitInstruction=""; - String entranceInstruction; - - String lastDist=""; - String roadBook=""; - int index=-1; - wpFlag flag; - wpFlag lastflag = null; - String lastRoadbook=""; - - - - void onGetRouteResult(SearchResult result){ - - } - - - - Boolean isCustPoint(int index){ - return roadWbs.size() > 1 &&!TextUtils.isEmpty(instructions) &&( index==0 || instructions.indexOf("从起点")>0 || instructions.indexOf("方向出发")>0); - } - - void cleanRoadInfo(){ - - instructions = instructions.replaceAll("","").replaceAll("",""); - exitInstruction = exitInstruction.replaceAll("","").replaceAll("",""); - entranceInstruction = entranceInstruction.replaceAll("","").replaceAll("",""); - - } - - String getRidOfHtmlCharacters(String in){ - int fontIndex = in.indexOf("0){ - in = in.substring(0,fontIndex); - } - - return in.replaceAll("","").replaceAll("","").replaceAll("
",""); - } - - @Override - public void onGetBikingRouteResult(BikingRouteResult result) { - - setRouteGot(true); - // QLog.getLogger().d(dTAG, " Got biking result......................................."); - - //起点或终点有歧义,需要选择具体的城市列表或地址列表 - if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) { - showMsg("抱歉,路径规划有点问题"); - return; - } - if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) { - // 起终点或途经点地址有岐义,通过以下接口获取建议查询信息 - // result.getSuggestAddrInfo() - return; - } - - if (result.error != SearchResult.ERRORNO.NO_ERROR) { - showMsg("很抱歉,路径规划有点问题"); - return; - } - - if(isSilence)return; - -// MKRoute singleRroute=res.getPlan(0).getRoute(0); - RouteLine singleRroute = result.getRouteLines().get(0); - -// int sDistance=singleRroute.getDistance(); - routeDistance+=singleRroute.getDistance(); - /*String lastDist=""; - String roadBook=""; - int index=-1; - wpFlag flag; - wpFlag lastflag = null; - String lastRoadbook="";*/ - BikingStep step; - for(int i=0;i0){ - exitInstruction=exitInstruction.substring(index+1); - } - - flag= exitInstruction.startsWith(wpFlag.TURNLEFT.toCHString())?wpFlag.TURNLEFT - :exitInstruction.startsWith(wpFlag.TURNRIGHT.toCHString())?wpFlag.TURNRIGHT:wpFlag.NORMAL; - -// QLog.getLogger().d(dTAG, exitInstruction +", cust turn flag is:" +flag +", chinese words:" +flag.toCHString()); - - if(lastflag!=null){ - wb.setTurnFlag(lastflag); - } -// wb.setTurnFlag(flag); - - if (isCustPoint(i)){ -// if(!roadWbs.isEmpty() &&!TextUtils.isEmpty(instructions) &&( i==0 || instructions.indexOf("从起点")>0) ){ - - String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点" - :currentWpFlag==wpFlag.REST?" 到达预设休息用餐点" - :currentWpFlag==wpFlag.CHECK?" 到达打卡点" - :""; - - instructions=instructions.replace("从起点",String.format("到达【途经点%s】 \n", custWpNumber+addon )); -// wb.setTurnFlag(wpFlag.CUST); - wb.setName(String.valueOf(custWpNumber)); - - if(trackId>0 &&oldComments!=null) - wb.setComment(oldComments.get(Integer.valueOf(custWpNumber))); - - // QLog.getLogger().d(dTAG, TAG+ " oldComments.get(i): "+i+","+ wb.getComment()); - -// QLog.getLogger().d(dTAG, String.format("instructions: %s ", instructions)); -// QLog.getLogger().d(dTAG, String.format("currentWpFlag: %s ", currentWpFlag)); -// wb.setTurnFlag(wpFlag.CUST); - wb.setTurnFlag(currentWpFlag); - - custGeos.add(step.getWayPoints().get(0)); - } - - if( instructions.indexOf(",到达终点")>0){ -// instructions=instructions.replace(",到达终点",String.format("到达【途经点%s】 \n", custWpNumber+addon )); - instructions=instructions.substring(0,instructions.indexOf(",到达终点")); - } - - - index=instructions.lastIndexOf(","); //沿星湖街骑行1.5公里,过人行道,到路口斜对面,左转进入崇文路 - if(index==-1){ - index=instructions.lastIndexOf(",") ; - } - -// roadBook =index>1?existInstruction.substring(0,index):""; - roadBook =index>1?instructions.substring(0,index):""; - roadBook=roadBook.length()==2&&roadBook.startsWith("走")?"":roadBook; - roadBook=roadBook.replace("出发", ""); - roadBook=roadBook.replace("行驶", ""); -// roadBook=roadBook.replace("靠左", ""); - - index=exitInstruction.lastIndexOf("-"); - /* String stepDist= index>1?exitInstruction.substring(index+2):""; - int dist =pareseDriveDist(stepDist); - wb.setDistance(dist); - wb.setBearDist(dist); */ - - - // QLog.getLogger().d(dTAG, "routeDistance is" + routeDistance); -// wb.setSumDist(routeDistance); - if(i>0 && index>0 &&index+10) - lastDist="继续前行"; - else - lastDist="出发"; - } - - - - instructions = instructions.replaceAll(",", ",然后");//replaceFirst(",", ",然后"); - - lastRoadbook=routeDistance==0?"":/* roadBook*/ instructions /*String.format("\"%s%s" ,roadBook ,lastDist )*/; - - wb.setRoadBook(lastRoadbook); -// wb.setComment(content); -// QLog.getLogger().d(dTAG, String.format(" roadbook is %s , turnflag is %s ", lastRoadbook,wb.getTurnFlag().toCHString() )); -// wb.setTurnFlag(wpFlag.CUST); - roadWbs.add(wb); -// starttime+=timestep; - -// custGeos.add(getLatLng(wb) ); - custGeos.addAll(step.getWayPoints()); - - lastflag =flag!=wpFlag.NORMAL?flag:null; - } - // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size()); - } - - @Override - public void onGetDrivingRouteResult(DrivingRouteResult result) { - - setRouteGot(true); - // QLog.getLogger().d(dTAG, " Got driving result......................................."); - - //起点或终点有歧义,需要选择具体的城市列表或地址列表 - if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) { - showMsg("抱歉,路径规划有点问题"); - return; - } - if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) { - // 起终点或途经点地址有岐义,通过以下接口获取建议查询信息 - // result.getSuggestAddrInfo() - return; - } - - if (result.error != SearchResult.ERRORNO.NO_ERROR) { - showMsg("很抱歉,路径规划有点问题"); - return; - } - - if(isSilence)return; - - RouteLine singleRroute = result.getRouteLines().get(0); - - routeDistance+=singleRroute.getDistance(); - - wpFlag flag; - for(int i=0;i0 ||*/ instructions.indexOf("方向出发")>0 ) ){ - -// QLog.getLogger().d(dTAG, " get cust poiont..............."); - - String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点" - :currentWpFlag==wpFlag.REST?" 到达预设休息用餐点" - :currentWpFlag==wpFlag.CHECK?" 到达打卡点" - :""; - - - entranceInstruction/*lastRoadbook*/= String.format("到达【途经点%s】 \n", custWpNumber+addon ) +instructions;//.substring(index+1) ; - - wb.setName(String.valueOf(custWpNumber)); - if(trackId>0 &&oldComments!=null) - wb.setComment(oldComments.get(Integer.valueOf(custWpNumber))); - // QLog.getLogger().d(dTAG, TAG+ " oldComments.get(i): "+i+","+ wb.getComment()); - - // QLog.getLogger().d(dTAG, TAG+ instructions); - // QLog.getLogger().d(dTAG, TAG+ currentWpFlag); - wb.setTurnFlag(currentWpFlag); - - custGeos.add(step.getWayPoints().get(0)); - } - - /* index=entranceInstruction.lastIndexOf("-"); - - if( instructions.indexOf(",到达终点")>0){ - instructions=instructions.substring(0,instructions.indexOf(",到达终点")); - }*/ - - index =entranceInstruction.indexOf("-"); - if(index>0){ - entranceInstruction =entranceInstruction.substring(0,index); - roadBook =entranceInstruction +",然后前行" +Utils.getFormatedDistance(step.getDistance()); - }else - roadBook =entranceInstruction; -// roadBook = entranceInstruction.replace("-", ",然后前行")/*.replaceAll(",", ",然后")*/; - roadBook = TextUtils.isEmpty(roadBook) ? instructions : roadBook; - - if( roadBook.indexOf(",到达终点")>0){ -// instructions=instructions.replace(",到达终点",String.format("到达【途经点%s】 \n", custWpNumber+addon )); - roadBook=roadBook.substring(0,roadBook.indexOf(",到达终点")); - } - wb.setRoadBook(roadBook); - - // QLog.getLogger().d(dTAG, String.format(" roadbook is %s \n, turnflag is %s ", roadBook,wb.getTurnFlag().toCHString() )); - - roadWbs.add(wb); - // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size()); - - - custGeos.addAll(step.getWayPoints()); - lastflag =flag!=wpFlag.NORMAL?flag:null; - } - /* - for(Waypoint_bean wb:roadWbs){ - // QLog.getLogger().d(dTAG, " road Wbs turn flag is: " +wb.getTurnFlag().toCHString() ); - } - - ArrayList> gps =singleRroute.get; - for(ArrayList gp:gps){ - custGeos.addAll(gp); - } - */ - - } - - @Override - public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) { - - } - - @Override - public void onGetTransitRouteResult(TransitRouteResult arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) { - - } - - @Override - public void onGetWalkingRouteResult(WalkingRouteResult result) { //same logic with biking - setRouteGot(true); - // QLog.getLogger().d(dTAG, " Got walking result......................................."); - - //起点或终点有歧义,需要选择具体的城市列表或地址列表 - if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) { - showMsg("抱歉,路径规划有点问题"); - return; - } - if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) { - // 起终点或途经点地址有岐义,通过以下接口获取建议查询信息 - // result.getSuggestAddrInfo() - return; - } - - if (result.error != SearchResult.ERRORNO.NO_ERROR) { - showMsg("很抱歉,路径规划有点问题"); - return; - } - - if(isSilence)return; - -// MKRoute singleRroute=res.getPlan(0).getRoute(0); - RouteLine singleRroute = result.getRouteLines().get(0); - -// int sDistance=singleRroute.getDistance(); - routeDistance+=singleRroute.getDistance(); - /*String lastDist=""; - String roadBook=""; - int index=-1; - wpFlag flag; - wpFlag lastflag = null; - String lastRoadbook="";*/ - WalkingStep step; - for(int i=0;i0){ - exitInstruction=exitInstruction.substring(index+1); - } - - flag= exitInstruction.startsWith(wpFlag.TURNLEFT.toCHString())?wpFlag.TURNLEFT - :exitInstruction.startsWith(wpFlag.TURNRIGHT.toCHString())?wpFlag.TURNRIGHT:wpFlag.NORMAL; - - // QLog.getLogger().d(dTAG, exitInstruction +", cust turn flag is:" +flag +", chinese words:" +flag.toCHString()); - - if(lastflag!=null){ - wb.setTurnFlag(lastflag); - } -// wb.setTurnFlag(flag); -// // QLog.getLogger().d(dTAG, String.format("routedistance is %s, road content is:%s",wb.getDistance(),content)); - if (isCustPoint(i)){ -// if(!roadWbs.isEmpty() &&!TextUtils.isEmpty(instructions) &&( i==0 || instructions.indexOf("从起点")>0) ){ - -// String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点":currentWpFlag==wpFlag.REST?" 到达预设休息用餐点":""; - - String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点" - :currentWpFlag==wpFlag.REST?" 到达预设休息用餐点" - :currentWpFlag==wpFlag.CHECK?" 到达打卡点" - :""; - - - instructions=instructions.replace("从起点",String.format("到达【途经点%s】 \n", custWpNumber+addon )); -// wb.setTurnFlag(wpFlag.CUST); - wb.setName(String.valueOf(custWpNumber)); - - if(trackId>0 &&oldComments!=null) - wb.setComment(oldComments.get(Integer.valueOf(custWpNumber))); - - // QLog.getLogger().d(dTAG, TAG+ " oldComments.get(i): "+i+","+ wb.getComment()); - - // QLog.getLogger().d(dTAG, String.format("instructions: %s ", instructions)); - // QLog.getLogger().d(dTAG, String.format("currentWpFlag: %s ", currentWpFlag)); -// wb.setTurnFlag(wpFlag.CUST); - wb.setTurnFlag(currentWpFlag); - - custGeos.add(step.getWayPoints().get(0)); - } - - if( instructions.indexOf(",到达终点")>0){ -// instructions=instructions.replace(",到达终点",String.format("到达【途经点%s】 \n", custWpNumber+addon )); - instructions=instructions.substring(0,instructions.indexOf(",到达终点")); - } - - - index=instructions.lastIndexOf(","); //沿星湖街骑行1.5公里,过人行道,到路口斜对面,左转进入崇文路 - if(index==-1){ - index=instructions.lastIndexOf(",") ; - } - -// roadBook =index>1?existInstruction.substring(0,index):""; - roadBook =index>1?instructions.substring(0,index):""; - roadBook=roadBook.length()==2&&roadBook.startsWith("走")?"":roadBook; - roadBook=roadBook.replace("出发", ""); - roadBook=roadBook.replace("行驶", ""); -// roadBook=roadBook.replace("靠左", ""); - - index=exitInstruction.lastIndexOf("-"); - /* String stepDist= index>1?exitInstruction.substring(index+2):""; - int dist =pareseDriveDist(stepDist); - wb.setDistance(dist); - wb.setBearDist(dist); */ - - -// // QLog.getLogger().d(dTAG, "routeDistance is" + routeDistance); -// wb.setSumDist(routeDistance); - if(i>0 && index>0 &&index+10) - lastDist="继续前行"; - else - lastDist="出发"; - } - - - -// instructions = instructions.replaceFirst(",", ",然后"); - instructions = instructions.replaceAll(",", ",然后"); - lastRoadbook=routeDistance==0?"":/* roadBook*/ instructions /*String.format("\"%s%s" ,roadBook ,lastDist )*/; - - wb.setRoadBook(lastRoadbook); -// wb.setComment(content); - // QLog.getLogger().d(dTAG, String.format(" roadbook is %s , turnflag is %s ",lastRoadbook,wb.getTurnFlag().toCHString() )); -// wb.setTurnFlag(wpFlag.CUST); - roadWbs.add(wb); -// starttime+=timestep; - -// custGeos.add(getLatLng(wb) ); - custGeos.addAll(step.getWayPoints()); - - lastflag =flag!=wpFlag.NORMAL?flag:null; - } - // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size()); - } - - } - - ); - -// poiOverlay = new MyPoiOverlay(activity, mMapView, mSearch); - } - - - - - //按键点击事件 - OnClickListener clickListener = new OnClickListener(){ - public void onClick(View v) { - //发起搜索 - SearchButtonProcess(v); - } - }; - - - int pareseDriveDist(String distStr){ - - if(TextUtils.isEmpty(distStr))return 0; - - int mIndex =distStr.indexOf("米"); - if(mIndex>0){ - return Integer.parseInt(distStr.substring(0,mIndex)); - } - int kmIndex =distStr.indexOf("公里"); - if(kmIndex>0){ - return (int) (Float.parseFloat(distStr.substring(0,kmIndex))*1000); - } - return 0; - - - } - - - void showMsg(String msg){ - if(isSilence)return; - Toast.makeText(activity, msg, Toast.LENGTH_LONG).show(); -// txtNote.setText(msg); - txtNote.setText(TextUtils.isEmpty(txtNote.getText())?msg:txtNote.getText()+"\n"+msg); - } - boolean canNavi(){ - return trackId>0 &&!activity.app.isNaving; - } - private boolean isRouteGot=false; - private ArrayList custGeos =new ArrayList(); - private int routeDistance=0; - private boolean isSilence=false; - private int routeType =0; - Handler handler; - - /** - * 发起路线规划搜索示例 - * @param v - */ - void SearchButtonProcess(View v) { - - custWpNumber=-1; - currentWpFlag=wpFlag.CUST; -// custWpMarkNumber=0; - isSilence=false; - txtNote.setText(null); - btnNavi.setEnabled(canNavi()); - btnSNav.setEnabled(canNavi()); - if(!Utils.isNetworkConnected(activity)){ - showMsg("制作路书需要连接互联网,请检查网络链接。"); - return; - } - if(this.startPt==null || this.endPt==null ){ - showMsg("请设置路线的始起点和终点。"); - return; - } - btnRouteReset.setEnabled(false); - btnRouteSave.setEnabled(false); - btnRouteSearch.setEnabled(false); - btnNavi.setEnabled(false); - btnSNav.setEnabled(false); - btnReverse.setEnabled(false); -// showMsg("正努力计算路线,请稍等。。。"); - - routeType =spRouteType.getSelectedItemPosition(); - spRouteType.setEnabled(false); - if(routeType==0){ //bike - showMsg( "正努力进行骑行路线规划,请稍等。。。"); - }else if(routeType==1) { //walk - showMsg( "正努力进行步行路线规划,请稍等。。。"); - }else if(routeType==2){//drive - showMsg( "正努力进行机动路线规划,请稍等。。。"); - } - custGeos.clear(); - - routeDistance=0; - geoType=-1; - roadWbs.clear(); - - if(!wpItems/*.getOverlayOptions()*/.contains(startItem)) - wpItems/*.getOverlayOptions()*/.add(0, startItem); - if(!wpItems/*.getOverlayOptions()*/.contains(endItem)) - wpItems/*.getOverlayOptions()*/.add(endItem); - - - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog -// progressDialog.dismiss(); - - //更新UI -// switchButtonStatus(); - - if(msg.what==0){ - // QLog.getLogger().d(dTAG,"before assembly the track..............................."); - showRoutes(false); - isSilence=true; - btnRouteSave.setEnabled(false); - -// btnRouteSave.setVisibility(View.VISIBLE); - }else if(msg.what==1){ - // QLog.getLogger().d(dTAG,"after assembly the track..............................."); - showFootmarkData(true); - /* for(Waypoint_bean wb1:gpxTrack.getTrackBean().getRoadWps()){ - - // // QLog.getLogger().d(dTAG, "31 cust wp turn flag" + wb1.getTurnFlag().toCHString()); - } */ - btnRouteSave.setEnabled(true); - btnRouteReset.setEnabled(true); - - } - spRouteType.setEnabled(true); - btnRouteSearch.setEnabled(true); - btnReverse.setEnabled(true); - }}; - - - new Thread(){ - @Override - public void run() { -// MKPlanNode stNode = new MKPlanNode(); -// MKPlanNode enNode = new MKPlanNode(); - - PlanNode stNode = null; - PlanNode enNode = null; - - /* if(isAllowMainRoad) - mSearch.setDrivingPolicy(RoutePlanSearch.ECAR_FEE_FIRST);*/ - - routeOverlay.removeFromMap(); - Bundle bd=null; - MarkerOptions mo ; - - for(int i=0;i0 && i-1 0){ //start point, to check the first cust num is hand or not - j = i; - - Waypoint_bean wb = getWb(stNode.getLocation()); - wb.setTurnFlag(wpFlag.START); - roadWbs.add(wb); - custGeos.add(stNode.getLocation()); - - } else if (i == wpItems.size()-2 && wpNumItems.size() > 0){ // check if the last 2 is the hand flag - j = i; - - } - - if (j > -1){ - mo = (MarkerOptions)wpNumItems.get(j); - bd = mo.getExtraInfo(); - custWpNumber=Integer.valueOf( bd.getInt(RoadOverlay.EXTR_KEY_INDEX)/*.getTitle()*/); - - if( bd.getInt(RoadOverlay.EXTR_KEY_FLAG,-10)!=-10/*wpNumItems.get(i-1).getSnippet()*/){ - currentWpFlag = wpFlag.valueOf(bd.getInt(RoadOverlay.EXTR_KEY_FLAG)); - - if (currentWpFlag == wpFlag.HAND){ - - if (i == 0 && wpNumItems.size() > 0){ //start point, to check the first cust num is hand or not - - Waypoint_bean wb = getWb(stNode.getLocation()); - wb.setTurnFlag(wpFlag.START); - roadWbs.add(wb); - custGeos.add(stNode.getLocation()); - - } - - - - Waypoint_bean wb = getWb(mo.getPosition()); - wb.setTurnFlag(currentWpFlag); - wb.setName(String.valueOf(custWpNumber)); - wb.setRoadBook("手绘点 " +custWpNumber); - roadWbs.add(wb); - custGeos.add(mo.getPosition()); - - custWpNumber=-1; - currentWpFlag=wpFlag.CUST; - - - if (i == wpItems.size()-2 && wpNumItems.size() > 0){ // check if the last 2 is the hand flag - - Waypoint_bean wb1 = getWb(enNode.getLocation()); - wb1.setTurnFlag(wpFlag.END); - roadWbs.add(wb1); - custGeos.add(enNode.getLocation()); - } - - - continue; - } - } - } - - - - -// if(wpItems.get(i).getTitle().length()>0)continue; - - isRouteGot=false; - // QLog.getLogger().d(dTAG, String.format("from %s to %s, pt(%s,%s) to pt(%s,%s)", i,i+1,stNode.getLocation().latitude,stNode.getLocation().longitude, enNode.getLocation().latitude,enNode.getLocation().longitude)); - - if(routeType==0){ //bike - mSearch.bikingSearch((new BikingRoutePlanOption()).from(stNode).to(enNode)); -// showMsg( "正在进行骑行路线规划"); - }else if(routeType==1) { //walk - mSearch.walkingSearch((new WalkingRoutePlanOption()) .from(stNode).to(enNode)); -// showMsg( "正在进行步行路线规划"); - }else if(routeType==2){//drive - mSearch.drivingSearch((new DrivingRoutePlanOption()) .from(stNode).to(enNode)); -// showMsg( "正在进行机动路线规划"); - } - -// Bundle bd=null; -// if(i>0 && i-15000 ){ - break; - - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); -// handler.sendEmptyMessage(0); - - } - } - } - - try { - Thread.sleep(2000); -// Thread.sleep(500); - - } - catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - - } - assemblyTrack(); - handler.sendEmptyMessage(0); -// assemblyTrack(); -// Message msg= Message.obtain(handler);// .obtain(handler, 1); -// Bundle bd =new Bundle(); -//// bd.putString("exportgpx", gpx); -// msg.setData(bd); -// handler.sendMessage(msg); - - handler.sendEmptyMessage(1); - }}.start(); - - - - /* - stNode.pt=this.startPt; -// enNode.name = editEn.getText().toString(); - enNode.pt=this.endPt; - // 实际使用中请对起点终点城市进行正确的设定 - mSearch.setDrivingPolicy(MKSearch.ECAR_DIS_FIRST); - - mSearch.walkingSearch(null, stNode, null, enNode);*/ - - - - /*if (mBtnDrive.equals(v)) { - mSearch.drivingSearch("北京", stNode, "北京", enNode); - } else if (mBtnTransit.equals(v)) { - mSearch.transitSearch("北京", stNode, enNode); - } else if (mBtnWalk.equals(v)) { - mSearch.walkingSearch("北京", stNode, "北京", enNode); - } */ - } - - private void showRoutes(final boolean isLoadFromTrack){ -// searchType = 2; -// int plans=res.getNumPlan(); -// for(int i=0;i0?routeDistance/1000:Utils.getDistanceFromXtoY(getWb(startItem.getPosition()).getLatitude(), getWb(startItem.getPosition()).getLongitude(), - getWb(endItem.getPosition()).getLatitude(), getWb(endItem.getPosition()).getLongitude())/1000; - - // // QLog.getLogger().d(dTAG," distance from start to end is:" +dist); - if(dist>200 &&( wpNumItems/*.getOverlayOptions()*/.size()==0 ||dist/wpNumItems/*.getOverlayOptions()*/.size()>100) - ){ - showMsg("长途路书规划请适当增加加途经点数量"); - } - - return; - } - - //remove the start,end point on the map -// mMapView.getOverlays().clear(); -// mMapView.getOverlays().remove(this.mGpOverlay); - wpItems/*.getOverlayOptions()*/.remove(startItem); - wpItems/*.getOverlayOptions()*/.remove(this.endItem); -// mGpOverlay.removeAll(); -// mGpOverlay.addItem(wpItems); -// mGpOverlay.addItem(wpNumItems); -// mMapView.getOverlays().add(mGpOverlay); - - - - routeOverlay.removeFromMap(); /*mMapView.getOverlays().remove(routeOverlay);*/ - - -// final MKRoute custRoute = new MKRoute(); - - -// LatLng[] GPS= (LatLng[]) custGeos.toArray(new LatLng[custGeos.size()]); -// -// custRoute.customizeRoute(startPt, endPt, GPS); - - final Handler handler2 = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - if(msg.what==2){ - // // QLog.getLogger().d(dTAG,"after assembly the track..............................."); - setRouteSuceedMsg(); - } - - - }}; - - // 此处仅展示一个方案作为示例 - - //清除其他图层 - /*int plans=res.getNumPlan(); - for(int i=0;i0){ - - gpxTrack =activity.app.getTrackCache().get(Integer.valueOf(trackId)); - - activity.updateActionBarTitle( getResources().getString(R.string.frg_route)+ " 编号"+trackId); - }else{ - gpxTrack=new Track(); -// gpxTrack.getTrackBean().setUserid(QiYouConstant.PV_USER_ID); - - } - setWorkingTrack(); - } - @Override - protected void routeSave(){ - -// txtNote.setText(null); - isSilence=false; - if(custGeos.isEmpty()){ - showMsg("没有路书需要保存"); - return; - } - - btnRouteSave.setEnabled(false); - - if(trackId<=0 || gpxTrack.getTrackBean().getUserid()!=activity.app.user.getUserbean().getId()){ //new route - - - - - gpxTrack.getTrackBean().setUserid(activity.app.user.getUserbean().getId()); - activity.app.initialImportedGpx(); - activity.app.getImportedGpx().add(gpxTrack); - activity.app.impGpx(); - - -// for(Waypoint_bean wb1:gpxTrack.getTrackBean().getRoadWps()){ -// // QLog.getLogger().d(dTAG, " saved road Wbs turn flag is: " +wb1.getTurnFlag().toCHString() ); -// } - - - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog -// progressDialog.dismiss(); - - //更新UI -// switchButtonStatus(); - - if(msg.what==0){ - showMsg("已保存,新增路书编号:" +trackId+",可以从我的-->更多-->我的记录-->路书分类中找到该路书。"); - activity.updateActionBarTitle( getResources().getString(R.string.frg_route)+ " 编号"+trackId); - activity.app.getTrackCache().put(trackId, gpxTrack); - setWorkingTrack(); - btnNavi.setEnabled(canNavi()); - btnSNav.setEnabled(canNavi()); - btnReverse.setEnabled(true); - activity.app.setCurrentTrack(gpxTrack); - activity.app.worksOnLine(trackId); - - - - }else if(msg.what==1){ - showMsg("保存过程遇到错误"); - } - - - - }}; - - new Thread(){ - @Override - public void run() { - - int topWaiting=0; - while( gpxTrack.getTrackBean().getTrackId()==0){ - try { - Thread.sleep(100); - topWaiting+=100; - if(topWaiting>5000 ){ - handler.sendEmptyMessage(1); - break; - - } - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); -// handler.sendEmptyMessage(0); - - } - } - - trackId=gpxTrack.getTrackBean().getTrackId(); - handler.sendEmptyMessage(0); - isSilence=false; - }}.start(); - - - - - - - - - - - }else{ //edit exist route - gpxTrack.getTrackBean().setTrackId(trackId); - gpxTrack.saveContent(false); - activity.app.getTrackCache().put(trackId, gpxTrack); - if(activity.app.currentTrack==null||activity.app.currentTrack.getTrackBean().getTrackId()==trackId){ - activity.app.currentTrack=gpxTrack; - } - doSave(); - showMsg("已保存"+(trackId>0?"":",你可以从我的-->更多-->我的记录-->路书分类中找到该路书")); - btnNavi.setEnabled(true); - btnSNav.setEnabled(true); - } - - custGeos.clear(); - - isSilence=true; - - } - - void assemblyTrack(){ - if(custGeos.isEmpty())return; - - // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size()); - if(QiYouConstant.DEVELOPER_MODE) - for(Waypoint_bean wb:roadWbs){ - - // QLog.getLogger().d(dTAG, " check cust wp turn flag" + wb.getTurnFlag().toCHString()); - // QLog.getLogger().d(dTAG, " check road book " + wb.getRoadBook()); - - } - - - if(gpxTrack==null){ - gpxTrack = new Track(); - String creator=activity.app.user.getUserbean().getUserName()/*.getAccount()*/; - creator=TextUtils.isEmpty(creator)?"爱骑驴路书":creator; - gpxTrack.getTrackBean().setCreatTime(System.currentTimeMillis()); - gpxTrack.getTrackBean().setType(TrackType.GPX); -// gpxTrack.getTrackBean().setCreator("爱骑驴路书"); - gpxTrack.getTrackBean().setCreator(creator); - - } - else{ -// gpxTrack.getTrackBean().getRoadWps().clear(); -// gpxTrack.getTrackBean().getTrkseg().clear(); -// gpxTrack.setRdWpsJson(new StringBuffer());// -// gpxTrack.getTrackBean().setStartWp(null); -// gpxTrack.getTrackBean().setLastWp(null); -// gpxTrack.setStartWp(null); -// - Track tmp = new Track(); - tmp.getTrackBean().setTrackId(gpxTrack.getTrackBean().getTrackId()); - tmp.getTrackBean().setName(gpxTrack.getTrackBean().getName()); - tmp.getTrackBean().setComment(gpxTrack.getTrackBean().getComment()); - tmp.getTrackBean().setDescription(gpxTrack.getTrackBean().getDescription()); -// tmp.getTrackBean().setCreatTime(gpxTrack.getTrackBean().getCreatTime()); -// tmp.getTrackBean().setType(gpxTrack.getTrackBean().getType()); -// tmp.getTrackBean().setCreator(gpxTrack.getTrackBean().getCreator()); - tmp.getTrackBean().setCreatTime(System.currentTimeMillis()); - tmp.getTrackBean().setType(TrackType.GPX); - tmp.getTrackBean().setCreator("爱骑驴路书"); - tmp.getTrackBean().setUserid(gpxTrack.getTrackBean().getUserid()); - tmp.getTrackBean().setMdWps(gpxTrack.getTrackBean().getMdWps()); - tmp.getTrackBean().setSvrNumber(gpxTrack.getTrackBean().getSvrNumber()); - gpxTrack=tmp; - if(!TextUtils.isEmpty(reverseComment)) - gpxTrack.getTrackBean().setDescription(reverseComment ); - - if(!TextUtils.isEmpty(reverseName)) - gpxTrack.getTrackBean().setName(reverseName ); - - - } - - - - -// btnRouteSave.setEnabled(false); -// btnRouteSave.setVisibility(View.GONE); - - -// long totalTime=(long) (routeDistance/avSpeed); - long startTime=System.currentTimeMillis(); - long esp=0l;//(long)(routeDistance/avSpeed/custGeos.size()); - long sptime=0;; - float speed=avSpeed*3600; -// int sdist=routeDistance/custGeos.size(); - float sdist; - int sumDist=0; - gpxTrack.getTrackBean().setSportTime((long) (routeDistance/avSpeed)); - // // QLog.getLogger().d(dTAG, String.format("routeDistance:%s,avSpeed %s,custGeos.size %s", routeDistance,avSpeed,custGeos.size())); - // // QLog.getLogger().d(dTAG, " esp: " + esp); - - // Waypoint startWp = new Waypoint(); -// startWp.getWb().setTime(startTime); -// startWp.getWb().setLongitude((float)(startPt.getLongitudeE6()/1e6)); -// startWp.getWb().setLatitude((float)(startPt.getLatitudeE6()/1e6)); -// startWp.getWb().setSpeed(avSpeed); -// track.setLastWp(startWp); - -// ArrayList wbs= track.getTrackBean().getTrkseg(); - int num=0; - boolean isRoadBear; - Waypoint wp; - Waypoint lastwp = null; - Waypoint prewp =null; - Waypoint nextWp =null; - ArrayList tmpGeos =new ArrayList(); - synchronized(custGeos) { - for(LatLng gp :custGeos){ -// sptime+=esp; - wp = new Waypoint(); - wp.setWb(getWb(gp)); - wp.getWb().setSpeed(speed); - wp.getWb().setTime(startTime); - - -// wp.getWb().setDistance(sptime*avSpeed); - sdist =lastwp==null?0: (float) Utils.getDistanceFromXtoY(lastwp.getWb().getLatitude(),lastwp.getWb().getLongitude(),wp.getWb().getLatitude(),wp.getWb().getLongitude()); - sumDist+=sdist; - esp=(long)(sdist/avSpeed); - sptime+=esp; - wp.getWb().setDistance(sdist); - wp.getWb().setSumDist(sumDist); - wp.getWb().setSportTime(sptime); - int i=0; - prewp = lastwp; - nextWp =wp; - if/* while*/(sdist>500){ - i++; - prewp =lastwp; - sdist =sdist/2; - Waypoint mwp = new Waypoint(); - Waypoint_bean wb = new Waypoint_bean(); - wb.setLatitude((prewp.getWb().getLatitude()+nextWp.getWb().getLatitude())/2); - wb.setLongitude( (prewp.getWb().getLongitude()+nextWp.getWb().getLongitude())/2); - mwp.setWb(wb); - mwp.getWb().setSpeed(speed); - mwp.getWb().setTime(/*gpxTrack.getTrackBean().getLastWp().getWb().getTime()+1*/ startTime -(long)(sdist/avSpeed) ); - mwp.getWb().setSumDist(sumDist-sdist); - mwp.getWb().setSportTime(sptime-100/*(long)(sdist/avSpeed)*/); - // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" gpxTrack wps size %s",gpxTrack.getTrackBean().getTrkseg().size())); - QLog.getLogger().d(dTAG,String.format(" to add new wp, current time %s - last time %s = %s ", mwp.getWb().getTime(),gpxTrack.getTrackBean().getLastWp().getWb().getTime(), mwp.getWb().getTime() -gpxTrack.getTrackBean().getLastWp().getWb().getTime())); - gpxTrack.setLastWp(mwp); - // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" add middle waypoint, new sdist is %s",sdist)); - // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" mwp.getWb().getSumDist %s ,mwp.getWb().getTime %s",mwp.getWb().getSumDist(),mwp.getWb().getTime())); - - // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" new gpxTrack wps size %s",gpxTrack.getTrackBean().getTrkseg().size())); -// tmpGeos.add(gp); -// prewp =; -// nextWp =mwp; - - wp.getWb().setDistance(sdist/2); - } - - -// wbs.add(wb); -// wp.getWb().setTurnFlag(wpFlag.TURNLEFT); -// // QLog.getLogger().d(dTAG, "wp.getWb().getTurnFlag()" +wp.getWb().getTurnFlag()+""); - -// startTime+=esp; - - isRoadBear=false; - for(Waypoint_bean wb:roadWbs){ -// // QLog.getLogger().d(dTAG, " 1 check time " + wb.getTime()); -// // QLog.getLogger().d(dTAG, " 1 check road book " + wb.getRoadBook()); - if(wb.getTime()==0 && wp.getWb().getLatitude()==wb.getLatitude() && wp.getWb().getLongitude()==wb.getLongitude()) { -// // QLog.getLogger().d(dTAG, " wb.getTime()" + wb.getTime()); -// // QLog.getLogger().d(dTAG, " cust wp set starttime" + startTime); -// // QLog.getLogger().d(dTAG, " cust wp turn flag" + wb.getTurnFlag().toCHString()); -// // QLog.getLogger().d(dTAG, " 2 check road book " + wb.getRoadBook()); - - wb.setTime(startTime); - wb.setSpeed(speed); -// wb.setDistance(wp.getWb().getDistance()); - wb.setSumDist(sumDist); - wb.setSportTime(sptime); - wp.getWb().setTurnFlag(wb.getTurnFlag()); - isRoadBear=true; - break; - } - } - -// if(isRoadBear ||custGeos.size()<=2000 ||custGeos.size()>2000 && num % 2 == 0) - if(isRoadBear || sumDist< 50000 ||sumDist<100000 && num % 2 == 0 ||sumDist>100000 && sumDist<300000 && num % 5 == 0 ||num % 10 == 0 ){ -// QLog.getLogger().d(dTAG," to insert new wp" ); - - gpxTrack.setLastWp(wp); - tmpGeos.add(gp); - } - startTime+=esp+1; - num++; -// startTime+=esp; - lastwp=wp; -// sdist =lastwp==null?0: (float) Utils.getDistanceFromXtoY(lastwp.getWb().getLatitude(),lastwp.getWb().getLongitude(),wp.getWb().getLatitude(),wp.getWb().getLongitude()); -// sumDist+=sdist; - - } - } - - custGeos=tmpGeos; - Waypoint_bean wb; - Waypoint_bean lastWb; - for(int i=roadWbs.size()-1;i>0;i--){ - wb = roadWbs.get(i); - lastWb=roadWbs.get(i-1); - if(wb==null ||lastWb==null)continue; -// wb.setRoadBook(lastWb.getRoadBook()); -// wb.setDistance(lastWb.getDistance()); -// wb.setBearDist(lastWb.getBearDist()); -// wb.setBearDist((float) Utils.getDistanceFromXtoY(wb.getLatitude(),wb.getLongitude(),lastWb.getLatitude(),lastWb.getLongitude())); - wb.setBearDist(wb.getSumDist() - lastWb.getSumDist()); - wb.setDistance(wb.getBearDist()); - if(wb.getSumDist()==0 &&lastWb.getSumDist()>0){ - wb.setSumDist(lastWb.getSumDist()+wb.getDistance() ); - } -// wb.setTurnFlag(lastWb.getTurnFlag()); - } - - -// Waypoint endWp = new Waypoint(); -// endWp.getWb().setTime(startTime); -// endWp.getWb().setLongitude((float)(endPt.getLongitudeE6()/1e6)); -// endWp.getWb().setLatitude((float)(endPt.getLatitudeE6()/1e6)); -// endWp.getWb().setSpeed(avSpeed); -// track.setLastWp(endWp); - - if(gpxTrack.getTrackBean().getTrkseg().size()>5000){ - /*CopyOnWriteArrayList wbs = new CopyOnWriteArrayList();*/ - ArrayList wbs = new ArrayList(); -// wbs.addAll(5000, gpxTrack.getTrackBean().getTrkseg());// gpxTrack.getTrackBean().getTrkseg().subList(0, 5000); - wbs.addAll(gpxTrack.getTrackBean().getTrkseg().subList(0, 5000)); - float dist=0; - for(int i=wbs.size()-1;i>0;i--){ - if(wbs.get(i)!=null){ - dist=wbs.get(i).getSumDist(); - break; - } - } - - - for(Waypoint_bean wb1:roadWbs){ - if(wb1==null)continue; - if(wb1.getSumDist()>dist) - wbs.add(wb1); - } - gpxTrack.getJsonWps().append(gpxTrack.wps2json(wbs)); - gpxTrack.getTrackBean().setTrksegs(wbs); - }else - gpxTrack.getJsonWps().append(gpxTrack.wps2json(gpxTrack.getTrackBean().getTrkseg())); - - - gpxTrack.getTrackBean().setDistance(sumDist); - - - long lasttime=0;//=System.currentTimeMillis(); - for(int i=0;i 0.8f) { - // Traverse all views in a millisecond - return ((float) OverLayItemAdapter.getCount()) / 0.001f; - } else { - return 10.0f * w; - } - } - }; - - - - - private class overLayItemListAdapter extends ArrayAdapter { - - public overLayItemListAdapter(Context context, int resource,int textViewResourceId, List objects) { - super(context,resource, textViewResourceId, objects); - - } - - @Override - public View getView(int position, View convertView, ViewGroup parent){ - MarkerOptions item = getItem(position); - View v = super.getView(position, convertView, parent); - /* ImageView imgMarker = (ImageView)v.findViewById(R.id.route_marker); - imgMarker.setBackground(item.getIcon() );*/ -// imgMarker.setImageDrawable(item.getMarker()); - TextView tv =(TextView)v.findViewById(R.id.text_waypoint); - tv.setText(String.format("途经点%s",item.getExtraInfo().getInt(RoadOverlay.EXTR_KEY_INDEX)/*item.getTitle()*/)); -// tv.setText("途经点"); - return v; - - } - } - - - - public void loadFromTrack(){ - - if(trackId<=0){ - if( activity.app.isNaving && activity.app.naviTrackId>0){ - trackId=activity.app.naviTrackId; - } else - return; - } - txtNote.setText(null); - oldComments=new HashMap(); -// custGeos - for(Waypoint_bean wb:mTrack.getTrackBean().getTrkseg()){ - if(wb==null)continue; - custGeos.add(getLatLng(wb)); - - } - - //build 途经点 - int i=0; - custWpMarkNumber=0; - for(Waypoint_bean wb:mTrack.getTrackBean().getRoadWps()){ - -// // QLog.getLogger().d(dTAG, TAG+ " road wb name is:"+wb.getName() + " road wb roadbook is:"+wb.getRoadBook() ); -// // QLog.getLogger().d(dTAG, " load from track: road Wbs turn flag is: " +wb.getTurnFlag().toCHString() ); -// // QLog.getLogger().d(dTAG, TAG +" road wb isCustWaypoint(wb)?" +isCustWaypoint(wb)); - -// if(TextUtils.isEmpty(wb.getName())&&wb.getRoadBook().indexOf("到达【途经点")<0)continue; - - // // // QLog.getLogger().d(dTAG, " load from track: road Wbs turn flag is: " +wb.getTurnFlag().toCHString() ); - - if(!isCustWaypoint(wb))continue; //to check why not work here?? - - // QLog.getLogger().d(dTAG, TAG+ " got cust waypoint, road wb name is: "+wb.getName()); - LatLng gp =getLatLng(wb); - - try{ - i=Integer.parseInt(wb.getName()) ;//custWpMarkNumber -// wpNumItems.add( getCustWpNum(gp,i,wpFlag.CUST)); -// wpNumItems/*.getOverlayOptions()*/.add( getCustWpNum(gp,i,wb.getTurnFlag())); - }catch(NumberFormatException er){ -// wpNumItems.add( getCustWpNum(getLatLng(wb),++i,wpFlag.CUST)); -// wpNumItems/*.getOverlayOptions()*/.add( getCustWpNum(getLatLng(wb),++i,wb.getTurnFlag())); - ++i; - } - custWpMarkNumber=custWpMarkNumber errorGpxfiles= new ArrayList(); - private void pareseGPX(){ - -// progressDialog = ProgressDialog.show(activity, "请稍等...", "正在导入GPX...", true); - - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog - if(progressDialog!=null)progressDialog.dismiss(); - if(msg.what==1){ - progressDialog = ProgressDialog.show(activity, "请稍等...", "正在导入 \n"+msg.getData().getString("file"), true); - progressDialog.setCancelable(true); - progressDialog.setCanceledOnTouchOutside(false); - mbtn_import.setEnabled(false); - } - else - if(msg.what==0){ - //更新UI - mbtn_import.setEnabled(true); - progressDialog.dismiss(); - showGpxFileList(); - - } - - }}; - - new Thread(){ - - @Override - public void run() { - - ArrayList srcs = activity.app.getImportedGpxFileList(); - - boolean succeed; -// HashMap gpxFiles =FileScan.getFiles(new File(QiYouConstant.IMP_PATH)); - - activity.app.initialImportedGpx(); - - for(Map gpxFile:gpxFileList){ - -// for(String fileName :gpxFile.keySet()) { - String gpxFullfileName= gpxFile.get("fileName"); - // // QLog.getLogger().d(TAG," srcs.contains " + gpxFullfileName+"?" +srcs.contains(gpxFullfileName)); - - if(!gpxFullfileName.toUpperCase().endsWith(".GPX")||srcs.contains(gpxFullfileName))continue; - Message msg= Message.obtain(); - Bundle bundle=new Bundle(); - bundle.putString("file", gpxFullfileName); - msg.setData(bundle);//bundle传值,耗时,效率低 - msg.what=1;//标志是哪个线程传数据 - handler.sendMessage(msg); - succeed=false; - try{ -// succeed= activity.app.impGpx( gpxFullfileName ); - Track tr =Track.newInstance(gpxFullfileName); - succeed=tr!=null; - if(succeed) - activity.app.getImportedGpx().add(tr); - -// importedGpx =new ArrayList();// initial the imported list for each import. so that the list contains the latest imported gpx tracks. - - }catch(Exception er){ - Utils.logStackTrace(er, TAG); - - } - if(!succeed){ - errorGpxfiles.add(gpxFullfileName); - // QLog.getLogger().d(TAG," import succeed?" +succeed +",file "+gpxFullfileName); - } -// if(succeed){ -// // QLog.getLogger().d(TAG," import succeed?" +succeed); -// } - - // QLog.getLogger().d(TAG," import succeed?" +succeed); - - } - - activity.app.impGpx();//persist the new gpx tracks. - - try { - Thread.sleep(5000); //waiting for syncronize completed - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - - handler.sendEmptyMessage(0); - }}.start(); - - -// String fileName="test_imp.gpx"; -// String gpxfileName =QiYouConstant.IMP_PATH+fileName; - -// -// if(srcs.contains(gpxfileName))return; -// -// -// boolean succeed= activity.app.impGpx( gpxfileName ); -// -// if(succeed){ -// // QLog.getLogger().d(TAG," import succeed?" +succeed); -// } -// -// // QLog.getLogger().d(TAG," import succeed?" +succeed); - - } - - - private void showGpxFileList(){ - -// HashMap gpxFiles =FileScan.getFiles(new File(QiYouConstant.IMP_PATH)); - gpxFileList = FileScan.getFiles(new File(QiYouConstant.IMP_PATH)); -// gpxFileList = new ArrayList>(); - ArrayList srcs = activity.app.getImportedGpxFileList(); - String importedOrNot; - final String WAIT_FOR_IMPORT="待导入"; - final String ERROR_WHEN_IMPORT="导入失败"; - if(errorGpxfiles.size()==0) - txt_importNote.setText("请将待导入的GPX文件(夹)放入下面目录: \n" -// +QiYouConstant.IMP_PATH - +"/qiyou/imp/" - +"\n导入的GPX轨迹可以在 我的-->更多-->我的记录-->路书页面中找到。"); - else - txt_importNote.setText("GPX导入过程出现错误,请检查下列文件格式是否正确:"); - mbtn_import.setEnabled(false); - for(Map gpxFile:gpxFileList){ - - String gpxFullfileName= gpxFile.get("fileName"); - - importedOrNot="已导入"; - - if(!srcs.contains(gpxFullfileName)){ - importedOrNot=WAIT_FOR_IMPORT; - if(!mbtn_import.isEnabled()){ - mbtn_import.setEnabled(true); - } -// if(errorGpxfiles.size()==0) -// txt_importNote.setText(txt_importNote.getText()+"\n"+"发现待导入GPX"); - - } - if(errorGpxfiles.contains(gpxFullfileName)){ - if(!mbtn_import.isEnabled()){ - mbtn_import.setEnabled(true); - } - txt_importNote.setText(txt_importNote.getText()+"\n"+gpxFullfileName); - importedOrNot =ERROR_WHEN_IMPORT; - } - - gpxFile.put("imported", importedOrNot); - -// // QLog.getLogger().d(TAG," srcs.contains " + gpxFullfileName+"?" +srcs.contains(gpxFullfileName)); -// gpxFileList.add(gpxFile); -// if(srcs.contains(gpxFullfileName))continue; - } - - - QSimpleAdapter adapter = new QSimpleAdapter(activity,gpxFileList,R.layout.import_gpx_detail, - new String[]{"fileName","imported"}, - new int[]{R.id.txt_gpxfile,R.id.txt_gpxfileImported}); -// ArrayList srcs = activity.app.getImportedGpxFileList(); - adapter.setViewBinder( new ViewBinder(){ - @Override - public boolean setViewValue(View view, Object data,String textRepresentation) { -// - if(view.getId()==R.id.txt_gpxfileImported){ - TextView tv =(TextView)view; - tv.setTextColor(Color.GRAY); - -// if(TextUtils.equals((String)data,ERROR_WHEN_IMPORT)) { -// tv.setTextColor(Color.RED); -// } -// - - if(TextUtils.equals((String)data,WAIT_FOR_IMPORT)||TextUtils.equals((String)data,ERROR_WHEN_IMPORT)) { - tv.setTextColor(Color.RED); - } - tv.setText((String)data); - - - - /*if(Boolean.getBoolean((String)data)) - tv.setText("已导入"); - else{ - tv.setText("未导入"); - tv.setTextColor(Color.RED); - }*/ - return true; - } - else if(view.getId()==R.id.txt_gpxfile){ - TextView tv =(TextView)view; - - String fileName = ((String)data); -// fileName =fileName.substring(fileName.lastIndexOf(QiYouConstant.IMP_PATH) + 1); - fileName =fileName.replace(QiYouConstant.IMP_PATH, ""); - tv.setText(fileName); - return true; - } - return false; - } - }); - - - filelv.setAdapter(adapter); -// adapter.setSelectItem(selectedFoodmarkItem); -// filelv.setSelection(selectedFoodmarkItem); - } - - - String reverseComment; - String reverseName; - @Override - void reverseRoute(){ - reverseName =""; - reverseComment=""; - if(trackId>0 && gpxTrack!=null){ - reverseName = "【返程】"; - reverseName =gpxTrack.getTrackBean().getName().replaceAll(reverseName, "")+reverseName; - reverseComment= "\n"+gpxTrack.getTrackBean().getName()+" 的返程路书."; - } - trackId=0; - initialGpxTrack(); - LatLng tmpSt=startItem.getPosition(); - LatLng tmpEd=endItem.getPosition(); - buildEnd(tmpSt,icon_end); - buildStart(tmpEd,icon_start); - - List tmpWpItems= new ArrayList(); - for(int i=wpItems.size();i>0;i--){ - tmpWpItems.add(wpItems.get(i-1)); - } - - wpItems =tmpWpItems; - - List tmpWpNumItems= new ArrayList(); - for(int i=wpNumItems.size();i>0;i--){ - tmpWpNumItems.add(wpNumItems.get(i-1)); - } - wpNumItems=tmpWpNumItems; - - OverLayItemAdapter =new overLayItemListAdapter(activity, R.layout.list_item_click_remove, R.id.text_waypoint, wpNumItems); - lv.setAdapter(OverLayItemAdapter); - -// mMapView.getOverlays().remove(routeOverlay); - routeOverlay.removeFromMap(); - routeOverlay.getOverlayOptions().clear(); - - restItems() ; - - routeSearch(); - btnReverse.setEnabled(false); - - } - - - - - - - void routeResume(){ - activity.app.isRouting=true; - canLocationMap=true; - updateUI(activity.app.lastLocation, false); - locationInMap(null); - showGpxFileList(); - - } - - - - class RouteOverlay extends OverlayManager{ - - public RouteOverlay(BaiduMap baiduMap) { - super(baiduMap); - // TODO Auto-generated constructor stub - } - - @Override - public boolean onMarkerClick(Marker arg0) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean onPolylineClick(Polyline arg0) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List getOverlayOptions() { - List overlayList = new ArrayList(); - ArrayList tmpGeos = new ArrayList(); - synchronized(custGeos) { - for(LatLng ll : custGeos){ - if (ll != null){ - tmpGeos.add(ll); - } - } - custGeos = tmpGeos; - if(tmpGeos.size()>2){ - overlayList.add(new PolylineOptions().points(custGeos).width(10) - .color( Color.argb(178, 0, 78, 255)).zIndex(0)); - } - } - return overlayList; - } - - } - - - protected Spinner spRouteType; - void initTrackTypeSpin(){ - ArrayAdapter spAdapter; - spRouteType = (Spinner)vContainer.findViewById(R.id.SpinnerRouteType); - if(spRouteType==null)return; - int spinner=R.layout.myspinner; - //将可选内容与ArrayAdapter连接起来 -// spAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.trackType, android.R.layout.simple_spinner_item); - spAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.routeType , spinner/*R.layout.myspinner*/); - - //设置下拉列表的风格 - spAdapter.setDropDownViewResource(R.layout.spinner_item); - - //将adapter2 添加到spinner中 - spRouteType.setAdapter(spAdapter); - - //添加事件Spinner事件监听 - spRouteType.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); - - //设置默认值 -// spRouteType.setVisibility(View.VISIBLE); - - } - - - @Override - public void onResume() { - super.onResume(); - routeResume(); - } - - @Override - public void onPause() { - super.onPause(); - if(!activity.app.isLastTrackExist()){ - if(activity.app.lastGpsStartTime>0 &&!activity.app.isGPSstopped ) - activity.app.stopAndroidGPSRequest(); - activity.app.unregTimeTick(); - activity.app.stopNetworkLocationRequest(); - } - - } - @Override - public void onDestroy() { - super.onDestroy(); - } - @Override - public void setTabOnFiling() { - MAPVIEW_INDEX=0; -// maxTabIndex = 3; - - } - public boolean isRouteGot() { - return isRouteGot; - } - public void setRouteGot(boolean isRouteGot) { - this.isRouteGot = isRouteGot; - } - - @Override - protected void startNavi(boolean isSimulation){ - // // // QLog.getLogger().dLog(dTAG,TAG, "Start to Navigation,gpx trackId is "+trackId); - if(trackId<=0)return; - super.startNavi(isSimulation); - }; - -@Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - /* - void buildWoGEO(Waypoint_bean wb){ - - GEOaddress geo= new GEOaddress(); - if( wb.getGeo()==null && activity.app.getCityGEO(wb.getLatitude(),wb.getLongitude())){ - - geo.setProvince(activity.app.GEOadress.province); - geo.setCity(activity.app.GEOadress.city); - geo.setDistrict(activity.app.GEOadress.district); - geo.setStreet(activity.app.GEOadress.street); - geo.setStreetNo(activity.app.GEOadress.streetNumber); - geo.setLat(wb.getLatitude()); - geo.setLon(wb.getLongitude()); - - wb.setGeo(geo); - - } - - }*/ - - /** - * load track to edit - */ - @Override - void showWebTrack(Track tr){ - if(tr==null)return; - this.activity.app.setCurrentTrack(tr,true); -// this.trackId = tr.getTrackBean().getTrackId(); -// gpxTrack =activity.app.getTrackCache().get(Integer.valueOf(tr.getTrackBean().getSvrNumber())); -// activity.updateActionBarTitle( getResources().getString(R.string.frg_route)+ " 编号"+trackId); - showDetailTrack(tr.getTrackBean().getSvrNumber()); - - } - @Override - void showDetailTrack(int trackId){ - - - this.trackId = trackId; - initialGpxTrack(); - routeInitial(); - tabhost.setCurrentTab(0); -// this.showRoutes(true); - - } - - @Override - public void doQuery() { - // TODO Auto-generated method stub - doTrackQuery(); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Scan_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Scan_fragment.java deleted file mode 100644 index 91f0a35..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Scan_fragment.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - - -import android.os.Bundle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import com.google.zxing.Result; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.server.RestMethods; - -import org.json.JSONObject; - -import me.dm7.barcodescanner.zxing.ZXingScannerView; -/** - * Created by wangmi on 17/1/5. - */ - -public class Scan_fragment extends WebList_fragment implements ZXingScannerView.ResultHandler { - - private ZXingScannerView mScannerView; - - public static Scan_fragment newInstance() { - - Scan_fragment f = new Scan_fragment(); - return f; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - activity.updateActionBarTitle(R.string.frg_notes); - - mScannerView = new ZXingScannerView(activity); // Programmatically initialize the scanner view -// setContentView(mScannerView); // Set the scanner view as the content view - vContainer = mScannerView; - return vContainer; - } - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - - - - - if(activity.app.user.getUserbean().getId() <= 0){ - showNotes("请登录"); - activity.showLogin(); - }else{ - mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results. - mScannerView.startCamera(); // Start camera on resume - } - - - - - - - } - - - - - @Override - public void handleResult(Result rawResult) { - // Do something with the result here - Log.v(TAG, rawResult.getText()); // Prints scan results - Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.) - - String result = rawResult.getText(); - mScannerView.stopCamera(); - String rest = ""; - int svrId = 0; - JSONObject jo = new JSONObject(); - try { - jo = new JSONObject(result); - rest = jo.getString(QiYouConstant.EXTRA_KEY_RESTMETHOD); - svrId = jo.getInt(QiYouConstant.EXTRA_KEY_SVRID); - } catch (Exception e) { - - } - - if (rest.equalsIgnoreCase(RestMethods.ACT_P_ADD_MEMBER) || rest.equalsIgnoreCase(RestMethods.GRP_P_ADD_MEMBER)){ - - - String svrName =""; - int ownerId = 0; - try { - - svrName = jo.getString("svrName"); - ownerId = jo.getInt("ownerId"); - - }catch (Exception e) { - - } - - - doMemberOperation(svrId,svrName,ownerId,activity.app.user.getUserbean().getId(),activity.app.user.getUserbean().getUserName(),rest); - - showNotes("欢迎加入" + svrName); - if (rest.equalsIgnoreCase(RestMethods.ACT_P_ADD_MEMBER) ) { - requestActFromWeb(svrId); - }else if (rest.equalsIgnoreCase(RestMethods.GRP_P_ADD_MEMBER) ) { - requestGroupFromWeb(svrId); - } - }else{ - mScannerView.setResultHandler(this); - mScannerView.startCamera(); - - } - - - - - -// mScannerView.startCamera(); - - } - @Override - protected void initialCommonControlls(){} - - @Override - public void doQuery(){}; - - - @Override - public void setFTag(){ - TAG="com.qiyou.Scan_fragment"; - } - public static String getFTag(){ - return "com.qiyou.Scan_fragment"; - } - @Override - public String getCurrentTag(){ - - return "com.qiyou.Scan_fragment"; - - } - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setTabOnFiling() { - -// maxTabIndex = 3; - - } - - - - - - - - - - - -} - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackDetail_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackDetail_fragment.java deleted file mode 100644 index b922e53..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackDetail_fragment.java +++ /dev/null @@ -1,1734 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.ui.fragments; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - - import org.apache.http.Header; -import org.apache.http.entity.StringEntity; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.app.AlertDialog.Builder; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.DialogInterface.OnClickListener; -import android.database.Cursor; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.support.v4.app.LoaderManager.LoaderCallbacks; -import android.support.v4.content.CursorLoader; -import android.support.v4.content.Loader; -import android.support.v7.widget.GridLayout; -import android.text.InputFilter; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnTouchListener; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.ArrayAdapter; -import android.widget.Button; -import com.qiyou.mb.android.upgrade.UpdateManager; -//import android.widget.ImageView; -import com.qiyou.mb.android.utils.image.QimageView; - -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.Spinner; -import android.widget.TabHost; -import android.widget.TextView; -import android.widget.Toast; - -import com.loopj.android.http.JsonHttpResponseHandler; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.StatTrack; -import com.qiyou.mb.android.beans.basic.Statics_bean; -import com.qiyou.mb.android.beans.basic.TypeStatistics; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.service.TrackDbServiceBackground; -import com.qiyou.mb.android.ui.ChartSpeedKm; -import com.qiyou.mb.android.utils.QiyouRestClient; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.WorkingTrackType; -import com.qiyou.mb.android.utils.log.QLog; -//import com.qiyou.mb.android.service.TrackDbService; - - -/** - * @author mwang - * - */ -//public class TrackDetail_fragment extends TrackTabs_fragment implements LoaderCallbacks { -public class TrackDetail_fragment extends TrackTabs_fragment { - - @Override - public void setFTag(){ - TAG="com.qiyou.TrackDetail_fragment"; - } - public static String getFTag(){ - return "com.qiyou.TrackDetail_fragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.TrackDetail_fragment"; - } - - ProgressDialog progressDialog ; - private Handler handler ; -// private View vContainer; -// private String trackId; - int lastId =0; -// protected MainActivity activity; - QiYouApplication app; -// private boolean getLastTrack =false; -// Track lastTrack; - Track currentTrack; - Statics_bean currentStat; - Statics_bean lastStat; - TypeStatistics TypeStatistics; - int inflat_source ; - int inType=-1; - boolean showSecondes =false; -// boolean isWebRequest =false; - - /** - * - */ - public TrackDetail_fragment() { - // TODO Auto-generated constructor stub - workingTrackType= WorkingTrackType.DETAIL; - } - - public static TrackDetail_fragment newInstance(int inType,int trackId) - { - - TrackDetail_fragment f = new TrackDetail_fragment(); - Bundle args = new Bundle(); -// args.putString(QiYouConstant.EXTRA_KEY_ID, trackId); -// args.putString(QiYouConstant.EXTRA_KEY_TYPE, inType); - args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId); - args.putInt(QiYouConstant.EXTRA_KEY_TYPE, inType); - f.setArguments(args); - return f; - } - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - isShowEdit=true; - app = (QiYouApplication) this.getActivity().getApplication(); - if(activity==null){ - activity = (com.qiyou.mb.android.ui.MainActivity)getActivity(); - } -// if(activity.app.currentTrack!=null)app.initialStatTrack(activity.app.currentTrack.getTrackBean().getType().toInt()); - QLog.getLogger().d(dTAG, TAG+" onCreate, app Current trackid is: "+ app.getCurrentTrack().getTrackBean().getTrackId()); - inflat_source =R.layout.track_chart_detailfragment; - } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - activity.app.playBack=false; - isPlayback=false; -// mTrack =activity.app.getCurrentTrack(); - -// int source =R.layout.track_chart_detailfragment; -// source =R.layout.track_chart_detailfragment; - vContainer = inflater.inflate(inflat_source, container, false); - super. onCreateView( inflater, container, savedInstanceState); - - initialDetailViews(); -// initViewMap(); - if (getArguments() != null) { -// String Id = getArguments().getString(QiYouConstant.EXTRA_KEY_ID); -// if(Id!=null)trackId =Integer.valueOf(Id); - trackId =getArguments().getInt(QiYouConstant.EXTRA_KEY_ID); -// String t=getArguments().getString(QiYouConstant.EXTRA_KEY_TYPE); -// if(!TextUtils.isEmpty(t)) -// inType=Integer.valueOf(t); - inType = getArguments().getInt(QiYouConstant.EXTRA_KEY_TYPE); - isWebRequest = getArguments().getBoolean(QiYouConstant.EXTRA_KEY_WEB_REQUEST); - } - - if(!activity.app.playBack) - initialFootmark(); - chk_showChats.setVisibility(View.GONE); - - -// initialGestureDetector(); - return vContainer; - } - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); -// activity = (MainActivity)getActivity(); -// activity.app.currentActiveFragment =TAG; - - QLog.getLogger().d(dTAG, TAG+ " onActivityCreated, get id from bundle is: "+ trackId ); - QLog.getLogger().d(dTAG, TAG+" onActivityCreated, app Current trackid is: "+ app.getCurrentTrack().getTrackBean().getTrackId()); -// lastId= trackId.intValue() -1; - getStat(); - /*if(!isWebRequest) - if(activity.app.mStatistics!=null - &&activity.app.mStatistics.getStatisticsTracks().get(inType)!=null){ - - ConcurrentHashMap sbs =activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs(); - - currentStat =sbs.get(trackId); - -// try{ - QLog.getLogger().d(dTAG, TAG+" activity.app.mStatistics.getStatisticsTracks()" + - ".get(inType).getTrackIds()" + - ".get(trackId)" - +(activity.app.mStatistics.getStatisticsTracks().get(inType).getTrackIds().get(trackId)==null)); - lastId =activity.app.mStatistics.getStatisticsTracks().get(inType).getTrackIds().get(trackId)==null?// 05-14 20:53:59.159 491 636 I am_crash: [24750,com.qiyou.mb.android,572998,java.lang.NullPointerException,NULL,TrackDetail_fragment.java,135]: system_server - 0:activity.app.mStatistics.getStatisticsTracks().get(inType).getTrackIds().get(trackId) ; //int 不能赋值null - - lastStat =lastId>0?activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs().get(lastId):null ; - - if(lastStat==null || lastId==0 && trackId>1){ - for(int i=trackId-1;i>0;i--) - if(activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs().get(i)!=null){ - lastId=i; - break; - } - } - - -// } -// catch(Exception e){ -// Utils.logStackTrace(e, dTAG); -// } bundle.putInt("id", mTrack_bean.getTrackId()); - - lastStat =lastId>0?activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs().get(lastId):null ; - }*/ - setTrackDesc(); -// setTrackDetail1();//set current track information with currentStat. - getLastTrackDetail(); - getStatTrack(); - setTrackDetailMax(); - - -// progressDialog = ProgressDialog.show(activity, "请稍等...", "获取数据中...", true); - -// tabhost.setEnabled(false); - -// for(int i=1;iQiYouConstant.MAX_TIME_GET_TRACK_FROM_DB ) - { - QLog.getLogger().d(dTAG, TAG+" topWaiting:"+topWaiting+",limit is:"+QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB ); - if(app.getCurrentTrack().getTrackBean().getTrackId() != trackId) - { - handler.sendEmptyMessage(1); - - } else - handler.sendEmptyMessage(0); - - return; - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - - - //向handler发消息 - handler.sendEmptyMessage(0); - }}.start(); - - - } - - - @Override - protected void initialViews(){ - super.initialViews(); - initialCateViews(); - - /* td_btnShowChartKm1 = (Button) vContainer.findViewById(R.id.td_btnShowChartKm1); - if(td_btnShowChartKm1!=null) - td_btnShowChartKm1.setOnClickListener(ButtonOnClickListener); - td_btnShowChartSpeed1 = (Button) vContainer.findViewById(R.id.td_btnShowChartSpeed1); - if(td_btnShowChartSpeed1!=null) - td_btnShowChartSpeed1.setOnClickListener(ButtonOnClickListener); - td_btnShowChartEle1 = (Button) vContainer.findViewById(R.id.td_btnShowChartEle1); - if(td_btnShowChartEle1!=null) - td_btnShowChartEle1.setOnClickListener(ButtonOnClickListener); */ - - } - void initialCateViews(){ - cateLv = (com.qiyou.mb.android.ui.fragments.InnerGridView) vContainer.findViewById(R.id.cate_list); - cateLv. setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - - editNewCate=(EditText) vContainer.findViewById(R.id.edit_newCate); ; -// editNewCate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)}); -// editNewCate.setSelectAllOnFocus(true); - editNewCate.setVisibility(View.GONE); - btnNewCate =(Button) vContainer.findViewById(R.id.btnSaveCate); - btnNewCate.setOnClickListener( - new android.view.View.OnClickListener() { - @Override - public void onClick(View view) { - Utils.hideSoftKeyboard(activity); - final EditText inputServer = new EditText(activity); - inputServer.setHint("请输入新标签(10字内)"); - inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)}); - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setTitle("输入新标签").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer) - .setNegativeButton("取消", null); - builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - editNewCate.setText(inputServer.getText()); - saveNewCate(); - } - }); - builder.show(); - - - } - - } - ); - - } - - @Override - protected void saveNewCate(){ - - String newCate= editNewCate.getText().toString(); - if(TextUtils.isEmpty(newCate)){ - editNewCate.setText(R.string.new_category); - return; - } - if(editNewCate.getText().toString().equalsIgnoreCase( - activity.getResources().getString(R.string.new_category))){ - newCate =null; - } -// editNewCate.setText(R.string.new_category); - -// if(TextUtils.isEmpty(newCate))return; - String msg=""; - isCateChangesSaved =activity.app.updateCates(newCate); - if(isCateChangesSaved){ - msg ="更改已提交保存。"; - Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show(); -// editNewCate.clearFocus(); - showCategoryList(cateLv,textContainer); - } -// else -// editNewCate.selectAll(); -// editNewCate.setText(""); -// else -// msg ="没有更改需要保存。"; -// Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show(); - - } - - @Override - void initialFootmark(){ - super.initialFootmark(); -// textContainer =(ScrollView)vContainer.findViewById(R.id.td_scrollView); - if(textContainer!=null) - textContainer.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - - } - - - - void getStat(){ - if(!isWebRequest) - if(activity.app.mStatistics!=null - &&activity.app.mStatistics.getStatisticsTracks().get(inType)!=null){ - - ConcurrentHashMap sbs =activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs(); - - currentStat =sbs.get(trackId); - -// try{ - QLog.getLogger().d(dTAG, TAG+" activity.app.mStatistics.getStatisticsTracks()" + - ".get(inType).getTrackIds()" + - ".get(trackId)" - +(activity.app.mStatistics.getStatisticsTracks().get(inType).getTrackIds().get(trackId)==null)); - lastId =activity.app.mStatistics.getStatisticsTracks().get(inType).getTrackIds().get(trackId)==null?// 05-14 20:53:59.159 491 636 I am_crash: [24750,com.qiyou.mb.android,572998,java.lang.NullPointerException,NULL,TrackDetail_fragment.java,135]: system_server - 0:activity.app.mStatistics.getStatisticsTracks().get(inType).getTrackIds().get(trackId) ; //int 不能赋值null - - lastStat =lastId>0?activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs().get(lastId):null ; - - if(lastStat==null || lastId==0 && trackId>1){ - for(int i=trackId-1;i>0;i--) - if(activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs().get(i)!=null){ - lastId=i; - break; - } - } - - -// } -// catch(Exception e){ -// Utils.logStackTrace(e, dTAG); -// } bundle.putInt("id", mTrack_bean.getTrackId()); - - lastStat =lastId>0?activity.app.mStatistics.getStatisticsTracks().get(inType).getSbs().get(lastId):null ; - } - } - int topWaiting=0; - public int topWaitingCount(){ - return ++topWaiting; - } - - @Override - protected void drawTrack(){ - - canDrawTrack=app.getCurrentTrack().getTrackBean().getTrackId() == trackId; - canDrawTrack=canDrawTrack ||this.isWebRequest && app.getCurrentTrack().getTrackBean().getSvrNumber() == trackId; - super.drawTrack(); - - } - - @Override - protected void initialTabhost(){ - - tabhost = (TabHost)vContainer.findViewById(R.id.tabhost); - tabhost.setup(); - - TabHost.TabSpec dataSpec = tabhost.newTabSpec(tabData); // This param will - // be used as tabId. -// homeSpec.setIndicator(null, getResources().getDrawable(R.drawable.empty_photo)); - dataSpec.setIndicator(tabData); - dataSpec.setContent(R.id.tab_statistic); - tabhost.addTab(dataSpec); - super.initialTabhost(); - } - - @Override - protected void showMapViews(){ - - super.showMapViews(); -// LinearLayout tm_ll_top_txt =(LinearLayout)vContainer.findViewById(R.id.tm_ll_top_txt); -// tm_ll_top_txt.setVisibility( View.VISIBLE ); -// - LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.ll_recording_data); -// tm_ll_top_txt.setVisibility(ll.getVisibility()==View.GONE?View.VISIBLE:View.GONE); - if(trackDetail!=null) trackDetail.setVisibility( View.GONE ); - if(btnLocation!=null) - btnLocation.setVisibility(View.GONE); - - if(this.btnRotation!=null) - btnRotation.setVisibility(View.GONE); - - if(this.btnAutoZoom!=null) - btnAutoZoom.setVisibility(View.GONE); - - if(this.btnSaveScreen!=null) - btnSaveScreen.setVisibility(View.VISIBLE); - GridLayout grid_top_txt =(GridLayout)vContainer.findViewById(R.id.grid_top_txt); - if(grid_top_txt!=null)grid_top_txt.setVisibility( View.VISIBLE ); - ((TextView)this.vContainer.findViewById(R.id.tm_top_speed_title)).setText("均速"); -// takeMapScreenshot(); - - } - -/* @Override - public Loader onCreateLoader(int arg0, Bundle arg1) { - - // if (!getLastTrack ) return new CursorLoader(activity, null, null, null, null, null); - // to load data from db. - String[] projection = new String[] {TrackProvider.KEY_TRACK_DISTANCE, - TrackProvider.KEY_TRACK_EDOWN_DIST ,TrackProvider.KEY_TRACK_EUP_DIST, - TrackProvider.KEY_TRACK_PAUSE_TIME ,TrackProvider.KEY_TRACK_TOPSPEED, - TrackProvider.KEY_TRACK_SPORT_TIME - }; - String selection = TrackProvider.KEY_ID + "='" + lastId + "'"; - - return new CursorLoader(activity, TrackProvider.TRACKS_URI, projection, selection, null, null); - - } - */ - - - private TextView mSpeedText4; - private TextView mSpeedText3; - private TextView mSpeedText2; - private TextView mSpeedText1; - - private TextView mtSpeedText4; - private TextView mtSpeedText3; - private TextView mtSpeedText2; - private TextView mtSpeedText1; - - private TextView mBurnText1; - private TextView mBurnText2; - private TextView mBurnText3; - private TextView mBurnText4; - - - private TextView mTotalTimeText1; - private TextView mTotalTimeText2; - private TextView mTotalTimeText3; - private TextView mTotalTimeText4; - - private TextView mDistanceText1; - private TextView mDistanceText2; - private TextView mDistanceText3; - private TextView mDistanceText4; - - private TextView mRdText1; - private TextView mRdText2; - private TextView mRdText3; - private TextView mRdText4; - - - - private TextView mTopSpeedText1; - private TextView mTopSpeedText2; - private TextView mTopSpeedText3; - private TextView mTopSpeedText4; - - private TextView mSportTimeText1; - private TextView mSportTimeText2; - private TextView mSportTimeText3; - private TextView mSportTimeText4; - -// private TextView mPausedTimeText1; -// private TextView mPausedTimeText2; -// private TextView mPausedTimeText3; -// private TextView mPausedTimeText4; - - - -// private TextView mOffTimeText1; -// private TextView mOffTimeText2; -// private TextView mOffTimeText3; -// private TextView mOffTimeText4; - -// private TextView mTotaleDownText1; -// private TextView mTotaleDownText2; -// private TextView mTotaleDownText3; -// private TextView mTotaleDownText4; - private TextView mTotaleUpText1; - private TextView mTotaleUpText2; - private TextView mTotaleUpText3; - private TextView mTotaleUpText4; - - private TextView mTotalUpText1; - private TextView mTotalUpText2; - private TextView mTotalUpText3; - private TextView mTotalUpText4; - - private TextView mTotalDownText1; - private TextView mTotalDownText2; - private TextView mTotalDownText3; - private TextView mTotalDownText4; - - private TextView mMaxEleText1; - private TextView mMaxEleText2; - private TextView mMaxEleText3; - private TextView mMaxEleText4; - - private TextView mMinEleText1; - private TextView mMinEleText2; - private TextView mMinEleText3; - private TextView mMinEleText4; - - private TextView mKmTimeText1; - private TextView mKmTimeText2; - private TextView mKmTimeText3; - private TextView mKmTimeText4; - private TextView mTextAccount; - private TextView mTrackType; - -// private TextView mSummaryText; -// private TextView mRoadBookText;//td_textView_roadbook -// private Button btnSave; -// private Button btnViewCompareChart; -// private Button btnViewCurrentChart; -// private Button btnRoadbook; - private TextView mMsgText; - protected Spinner spDetailTrackType; - - void initialDetailViews() - { -// gf1 = (GifView) vContainer.findViewById(R.id.td_gif); - spDetailTrackType = (Spinner)vContainer.findViewById(R.id.SpinnerTrackType); - mTrackId = (TextView) vContainer.findViewById(R.id.td_textView_TrackID);// - mMsgText = (TextView) vContainer.findViewById(R.id.td_textView_Notice); - - mTrackStarTimeText = (TextView) vContainer.findViewById(R.id.td_textView_Startime); - mTrackEndTimeText = (TextView) vContainer.findViewById(R.id.td_textView_EndTime); - - mTrackType=(TextView) vContainer.findViewById(R.id.td_textView_trackType) ; - - mSpeedText1 = (TextView) vContainer.findViewById(R.id.td_textView_av_speed1); - mSpeedText2 = (TextView) vContainer.findViewById(R.id.td_textView_av_speed2); - mSpeedText3 = (TextView) vContainer.findViewById(R.id.td_textView_av_speed3); - mSpeedText4 = (TextView) vContainer.findViewById(R.id.td_textView_av_speed4); - - mtSpeedText1 = (TextView) vContainer.findViewById(R.id.td_textView_tavs1); - mtSpeedText2 = (TextView) vContainer.findViewById(R.id.td_textView_tavs2); - mtSpeedText3 = (TextView) vContainer.findViewById(R.id.td_textView_tavs3); - mtSpeedText4 = (TextView) vContainer.findViewById(R.id.td_textView_tavs4); - - mBurnText1 = (TextView) vContainer.findViewById(R.id.td_textView_burn1); - mBurnText2 = (TextView) vContainer.findViewById(R.id.td_textView_burn2); - mBurnText3 = (TextView) vContainer.findViewById(R.id.td_textView_burn3); - mBurnText4 = (TextView) vContainer.findViewById(R.id.td_textView_burn4); - - mTextAccount = (TextView) vContainer.findViewById(R.id.td_textView_account); - - - mTotalTimeText1 = (TextView) vContainer.findViewById(R.id.td_textView_totalTime1); - mTotalTimeText2 = (TextView) vContainer.findViewById(R.id.td_textView_totalTime2); - mTotalTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_totalTime3); - mTotalTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_totalTime4); - - mSportTimeText1 = (TextView) vContainer.findViewById(R.id.td_textView_sport_time1); - mSportTimeText2 = (TextView) vContainer.findViewById(R.id.td_textView_sport_time2); - mSportTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_sport_time3); - mSportTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_sport_time4); - - - mDistanceText1 = (TextView) vContainer.findViewById(R.id.td_textView_Distance1 ); - mDistanceText2 = (TextView) vContainer.findViewById(R.id.td_textView_Distance2); - mDistanceText3 = (TextView) vContainer.findViewById(R.id.td_textView_Distance3); - mDistanceText4 = (TextView) vContainer.findViewById(R.id.td_textView_Distance4); - - - mRdText1 = (TextView) vContainer.findViewById(R.id.td_textView_maxRd1 ); - mRdText2 = (TextView) vContainer.findViewById(R.id.td_textView_maxRd2 ); - mRdText3 = (TextView) vContainer.findViewById(R.id.td_textView_maxRd3 ); - mRdText4 = (TextView) vContainer.findViewById(R.id.td_textView_maxRd4 ); - - - mTopSpeedText1 = (TextView) vContainer.findViewById(R.id.td_textView_top_speed1 ); - mTopSpeedText2 = (TextView) vContainer.findViewById(R.id.td_textView_top_speed2); - mTopSpeedText3 = (TextView) vContainer.findViewById(R.id.td_textView_top_speed3); - mTopSpeedText4 = (TextView) vContainer.findViewById(R.id.td_textView_top_speed4); - -// mPausedTimeText1 = (TextView) vContainer.findViewById(R.id.td_textView_paused_time1 ); -// mPausedTimeText2 = (TextView) vContainer.findViewById(R.id.td_textView_paused_time2); -// mPausedTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_paused_time3); -// mPausedTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_paused_time4); - -// mOffTimeText1 = (TextView) vContainer.findViewById(R.id.td_textView_off_time1 ); -// mOffTimeText2 = (TextView) vContainer.findViewById(R.id.td_textView_off_time2); -// mOffTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_off_time3); -// mOffTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_off_time4); - - - mTotaleUpText1 = (TextView) vContainer.findViewById(R.id.td_textView_eUp1 ); - mTotaleUpText2 = (TextView) vContainer.findViewById(R.id.td_textView_eUp2); - mTotaleUpText3 = (TextView) vContainer.findViewById(R.id.td_textView_eUp3); - mTotaleUpText4 = (TextView) vContainer.findViewById(R.id.td_textView_eUp4); - - mTotalUpText1 = (TextView) vContainer.findViewById(R.id.td_textView_Up1 ); - mTotalUpText2 = (TextView) vContainer.findViewById(R.id.td_textView_Up2); - mTotalUpText3 = (TextView) vContainer.findViewById(R.id.td_textView_Up3); - mTotalUpText4 = (TextView) vContainer.findViewById(R.id.td_textView_Up4); - - mTotalDownText1 = (TextView) vContainer.findViewById(R.id.td_textView_Down1); - mTotalDownText2 = (TextView) vContainer.findViewById(R.id.td_textView_Down2); - mTotalDownText3 = (TextView) vContainer.findViewById(R.id.td_textView_Down3); - mTotalDownText4 = (TextView) vContainer.findViewById(R.id.td_textView_Down4); - - mMaxEleText1 = (TextView) vContainer.findViewById(R.id.td_textView_Maxe1); - mMaxEleText2 = (TextView) vContainer.findViewById(R.id.td_textView_Maxe2); - mMaxEleText3 = (TextView) vContainer.findViewById(R.id.td_textView_Maxe3); - mMaxEleText4 = (TextView) vContainer.findViewById(R.id.td_textView_Maxe4); - - mMinEleText1 = (TextView) vContainer.findViewById(R.id.td_textView_Mine1); - mMinEleText2 = (TextView) vContainer.findViewById(R.id.td_textView_Mine2); - mMinEleText3 = (TextView) vContainer.findViewById(R.id.td_textView_Mine3); - mMinEleText4 = (TextView) vContainer.findViewById(R.id.td_textView_Mine4); - - mKmTimeText1 = (TextView) vContainer.findViewById(R.id.td_textView_kmtime); - mKmTimeText2 = (TextView) vContainer.findViewById(R.id.td_textView_kmtime2); - mKmTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_kmtime3); - mKmTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_kmtime4); - - shareView =(View) vContainer.findViewById(R.id.td_shareview); - staticMapImg= (QimageView) vContainer.findViewById(R.id.td_staticMap); -// mTotaleDownText1 = (TextView) vContainer.findViewById(R.id.td_textView_eDown1); -// mTotaleDownText2 = (TextView) vContainer.findViewById(R.id.td_textView_eDown2); -// mTotaleDownText3 = (TextView) vContainer.findViewById(R.id.td_textView_eDown3); -// mTotaleDownText4 = (TextView) vContainer.findViewById(R.id.td_textView_eDown4); - - btnSave = (Button) vContainer.findViewById(R.id.td_btnSaveTtrack); - btnDel = (Button) vContainer.findViewById(R.id.td_btnDelTtrack); - btnUpload = (Button) vContainer.findViewById(R.id.td_btnUploadTtrack); - btnShare = (Button) vContainer.findViewById(R.id.td_btnShareTtrack); - if(btnShare!=null) - btnShare.setOnClickListener(ButtonOnClickListener); -// btnViewCompareChart = (Button) vContainer.findViewById(R.id.td_btnViewCompareChart); -// btnViewCurrentChart = (Button) vContainer.findViewById(R.id.td_btnViewCurrentChart); - td_btnPlayback= (Button) vContainer.findViewById(R.id.td_btnPlayback); - td_btnContinue= (Button) vContainer.findViewById(R.id.td_btnContinue); - btnNavi= (Button) vContainer.findViewById(R.id.td_btnNavi); -// btnRoadbook= (Button) vContainer.findViewById(R.id.td_btn_roadbook); -// td_btn_export=(Button) vContainer.findViewById(R.id.td_btn_export); -// td_btn_export.setOnClickListener(ButtonOnClickListener); - if(btnSave!=null){ - btnSave.setOnClickListener(ButtonOnClickListener); - } - if(btnDel!=null){ - btnDel.setOnClickListener(ButtonOnClickListener); - } - if(btnUpload!=null){ - btnUpload.setOnClickListener(ButtonOnClickListener); - } - btnNavi.setOnClickListener(ButtonOnClickListener); - btnSNav=(Button) vContainer.findViewById(R.id.td_btnSNav);// -// btnSNav.setOnClickListener( ButtonOnClickListener); - - btnSNav.setOnClickListener( new android.view.View.OnClickListener() { - @Override - public void onClick(View view) { - startNavi(true); - } - } - ); - -// btnViewCompareChart.setOnClickListener(ButtonOnClickListener); -// btnViewCurrentChart.setOnClickListener(ButtonOnClickListener); - td_btnPlayback.setOnClickListener(ButtonOnClickListener); -// btnRoadbook.setOnClickListener(ButtonOnClickListener); - - if(td_btnContinue!=null) - td_btnContinue.setOnClickListener(ButtonOnClickListener); -// initialTabhost(); -// initTrackTypeSpin(); -// initialChartViews(); - mMsgText.setVisibility(View.GONE); - /* - td_btnPlayback= (Button) vContainer.findViewById(R.id.td_btnPlayback); - td_btnContinue= (Button) vContainer.findViewById(R.id.td_btnContinue); -// btnRoadbook= (Button) vContainer.findViewById(R.id.td_btn_roadbook); - td_btn_export=(Button) vContainer.findViewById(R.id.td_btn_export); - btnSave.setOnClickListener(ButtonOnClickListener); -// btnViewCompareChart.setOnClickListener(ButtonOnClickListener); -// btnViewCurrentChart.setOnClickListener(ButtonOnClickListener); - td_btnPlayback.setOnClickListener(ButtonOnClickListener); -// btnRoadbook.setOnClickListener(ButtonOnClickListener); - td_btn_export.setOnClickListener(ButtonOnClickListener); - td_btnContinue.setOnClickListener(ButtonOnClickListener);*/ - - td_btnShowChartKm = (Button) vContainer.findViewById(R.id.td_btnShowChartKm); - if(td_btnShowChartKm!=null) - td_btnShowChartKm.setOnClickListener(ButtonOnClickListener); - td_btnShowChartSpeed = (Button) vContainer.findViewById(R.id.td_btnShowChartSpeed); - if(td_btnShowChartSpeed!=null) - td_btnShowChartSpeed.setOnClickListener(ButtonOnClickListener); - td_btnShowChartEle = (Button) vContainer.findViewById(R.id.td_btnShowChartEle); - if(td_btnShowChartEle!=null) - td_btnShowChartEle.setOnClickListener(ButtonOnClickListener); - } - - - @Override - protected void updateTrackAvstatus(){ - if(mTrack_bean==null)return; - if(mTrack_bean.getAvStatus()!=TrackAvStatus.DELETED){ - -// mTrack_bean.setAvStatus(TrackAvStatus.INACTIVE); - newAvailableDialog(); - - }else{ - mTrack_bean.setAvStatus(TrackAvStatus.ACTIVE); - btnDel.setText(R.string.delete); - app.updateTrackAvStatus(mTrack_bean.getTrackId()); - } - } - - /* @Override - protected void startNavi(){ - activity.app.naviTrackId=trackId; - activity.startNaviService(); - - - }; */ - protected void newAvailableDialog( ) { - AlertDialog.Builder builder = new Builder(activity); - builder.setMessage("您确认要删除记录吗?"); - builder.setTitle("删除记录"); - builder.setCancelable(true); - builder.setNeutralButton("取消", new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - builder.setPositiveButton("确认删除", new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - mTrack_bean.setAvStatus(TrackAvStatus.DELETED); - if(mTrack_bean.getType()!=TrackType.GPX){ - app. mStatistics.trackMinus(app.getCurrentTrack()); - app.writeStatiscs(); - } - //notice the UI - app.updateTrackAvStatus(mTrack_bean.getTrackId()); -// app.tracks_cached.remove(Integer.valueOf(mTrack_bean.getTrackId())); - app.setGpxShowingTracks(String.valueOf(mTrack_bean.getTrackId()),false); - dialog.dismiss(); - activity.showLocalTrackList(); - - } - }); - /* builder.setNegativeButton("放入回收站", new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - mTrack_bean.setAvStatus(TrackAvStatus.INACTIVE); - btnDel.setText(R.string.track_edit_restore); - app.updateTrackAvStatus(mTrack_bean.getTrackId()); - dialog.dismiss(); - } - });*/ - builder.create().show(); - } - - - @Override - protected void validEditButtons(){ - if(td_btnPlayback!=null){ - //正在记录的track不可以回放 - boolean canNotPlay = activity.app.currentTrack==null - || activity.app.currentTrack!=null && activity.app.currentTrack.getTrackBean().getDistance()==0 - || activity.app.recordingTrack!=null - && activity.app.recordingTrack.getTrackBean().getTrackId() == activity.app.currentTrack.getTrackBean().getTrackId() - && activity.app.recordingTrack.getTrackBean().getStatus()!=TrackStatus.FINISHED - ; - td_btnPlayback.setEnabled(!canNotPlay); -// td_btnPlayback.setVisibility(canNotPlay?View.GONE:View.VISIBLE); - -// td_btnPlayback.setEnabled(activity.app.currentTrack!=null && activity.app.currentTrack.getTrackBean().getDistance()>0); - } - if(td_btnContinue!=null){ - boolean canContinue = activity.app.getRecordingTrack().getTrackBean().getTrackId() !=mTrack_bean.getTrackId(); - canContinue =canContinue - && mTrack_bean.getAvStatus()!=TrackAvStatus.DELETED - && mTrack_bean.getAvStatus()!=TrackAvStatus.INACTIVE -// && mTrack_bean!=null - && mTrack_bean.getTrackId()>0; - td_btnContinue.setEnabled(canContinue ); - } - if(td_btn_export!=null) - td_btn_export.setEnabled(mTrack_bean!=null&&mTrack_bean.getTrackId()>0); - - boolean canNavi= (td_btn_export!=null?td_btn_export.isEnabled():true ) - && activity.app.getCurrentTrack().getTrackBean().getDistance()>0 - && mTrack_bean!=null -// && app.naviTrackId!=mTrack_bean.getTrackId() - && mTrack_bean.getTrackId()!=activity.app.getRecordingTrack().getTrackBean().getTrackId() -// && !app.playBack - ; - if(btnNavi!=null){ - btnNavi.setEnabled(canNavi); - } - - if(btnShare!=null){ - btnShare.setEnabled(activity.app.getCurrentTrack().getTrackBean().getDistance()>0); - } - updateDelButton(); - updateUploadButton(); -// if(spDetailTrackType!=null){ -// spDetailTrackType.setVisibility( td_btnPlayback.getVisibility()); -// } - /*if(td_edit_Type!=null){ - if(spDetailTrackType.getVisibility()==View.GONE) - td_edit_Type.setVisibility(View.VISIBLE); - }*/ - - -// if(td_btn_export!=null){ -// -//// td_btn_export.setVisibility( td_btnPlayback.getVisibility()); -//// td_btn_export.setEnabled(QiYouConstant.DEVELOPER_MODE); -// } - super.validEditButtons(); - - } - @Override - protected void continueTrack() { -// td_btnContinue.setText("加载中。。。"); - td_btnContinue.setEnabled(false); - activity.continueTrack(); - } - - private void updateDelButton(){ - if(workingTrackType==WorkingTrackType.DETAIL||workingTrackType==WorkingTrackType.GPX){ - btnDel.setVisibility(View.VISIBLE); - btnDel.setEnabled(activity.app.getRecordingTrack().getTrackBean().getTrackId()!=trackId); - if(mTrack_bean.getAvStatus()!=TrackAvStatus.DELETED){ - btnDel.setText(R.string.delete); - }else{ - btnDel.setText(R.string.track_edit_restore); - } - - } - else - btnDel.setVisibility(View.GONE); - } - - void updateUploadButton(){ - - if(btnUpload==null){ - return; - } - -// btnUpload.setEnabled(mTrack_bean.getStatus()!=TrackStatus.RECORDING && mTrack_bean.getDistance()>0); - btnUpload.setEnabled( mTrack_bean.getDistance()>0); -// btnUpload.setEnabled(mTrack_bean.getUserid()<=0 -// || mTrack_bean.getUserid()==QiYouConstant.PV_USER_ID); - - btnUpload.setText(mTrack_bean.getSvrNumber()>0?"更新云端":"上传云端"); -// btnUpload.setVisibility(mTrack_bean.getDistance()>0?View.VISIBLE:View.GONE); - } - - -// private String td_textView_Distance2; -// private String td_textView_eDown2; -// private String td_textView_eUp2; -//// private String td_textView_paused_time2; -// private String td_textView_top_speed2; -// private String td_textView_SportTime2; -// private String td_textView_TotalSportTime2; -// private String td_textView_av_speed2; -// private String td_textView_tav_speed2; -//// private String td_textView_OffTime2 ; -// private String td_textView_Rd2 ; - - /** - * {@inheritDoc} - * When the Loader has completed, schedule an update of the Fragment UI on the main application thread. - * - */ - - - private void getLastTrackDetail() - { - if(lastStat==null) return; - - - -// lastTrack = app.getTrackCache().get((Integer.valueOf(lastId))); -// td_textView_Distance2 =String.format("%.2f", lastStat.getDistance()/1000.0); -// td_textView_eDown2 = String.format("%.0f", Math.abs(lastStat.geteDownDist())); -// td_textView_eUp2 = String.format("%.0f", lastStat.geteUpDist()+lastStat.geteDownDist()) ; -// td_textView_eUp2 = String.format("%.0f", lastStat.geteUpDist()) ; - -// td_textView_paused_time2 = Utils.getTimeCnt(lastStat.getPause(),showSecondes); -// td_textView_top_speed2 = String.format("%.2f", lastStat.getTopSpeed()); -// td_textView_SportTime2 = Utils.getTimeCnt(lastStat.getSportTime() ,showSecondes); -// td_textView_TotalSportTime2 =Utils.getTimeCnt( lastStat.getSportTime() + -// lastStat.getPause(),showSecondes); -// td_textView_OffTime2 = Utils.getTimeCnt(lastStat.getOffTime(),showSecondes); -// td_textView_av_speed2 =String.format("%.2f",lastStat.getAVS());//String.format("%.2f", lastStat.getSportTime()>0?3600*lastStat.getDistance()/lastStat.getSportTime():0 ) ; -// td_textView_tav_speed2=String.format("%.2f",lastStat.getTAVS()); -// td_textView_Rd2 = String.format("%.2f", lastStat.getMaxRdist()/1000.0 ); - - setLastTrackDetai(); - } - - - protected void setLastTrackDetai(){ -// handler.post(new Runnable () { -// public void run() { - mTopSpeedText2.setText(String.format("%.2f", lastStat.getTopSpeed())); - mDistanceText2.setText(String.format("%.2f", lastStat.getDist()/1000.0)); - mTotaleUpText2.setText(String.format("%.0f", lastStat.geteUpDist()) ); - if( lastStat.getUpDist()>0){ - mTotalUpText2.setText(String.format("%.2f", lastStat.getUpDist()/1000) ); - mTotalDownText2.setText(String.format("%.2f", lastStat.getDownDist()/1000) ); - mMaxEleText2.setText(String.format("%.0f", lastStat.getMaxEle()) ); - mMinEleText2.setText(String.format("%.0f", lastStat.getMinEle()) ); - } -// mTotaleDownText2.setText(td_textView_eDown2); - mSportTimeText2.setText( Utils.getTimeCnt(lastStat.getSportTime() ,showSecondes)); -// mPausedTimeText2.setText(td_textView_paused_time2); - mSpeedText2.setText(String.format("%.2f",lastStat.getAvs())); - mtSpeedText2.setText(String.format("%.2f",lastStat.getTavs())); - mBurnText2.setText( String.format("%.0f", lastStat.getBurn() )); - mTotalTimeText2.setText(Utils.getTimeCnt( lastStat.getSportTime() + lastStat.getPause(),showSecondes)); -// mOffTimeText2.setText(td_textView_OffTime2); - mRdText2.setText(String.format("%.2f", lastStat.getMaxR()/1000.0 )); - if(lastStat.getKmTime()>0) - mKmTimeText2.setText(Utils.getTimeMS(lastStat.getKmTime())); -// } -// }); - - } - -/* @Override - public void onLoaderReset(Loader arg0) { - // TODO Auto-generated method stub - - } - */ -// GifView gf1; - - - - - - void setVersion(){ - - TextView versionName =(TextView)vContainer.findViewById(R.id.i7lv_words); - versionName.setText(versionName.getText() +" V"+ UpdateManager.getVersionName(app)+(QiYouConstant.DEVELOPER_MODE?":-D":"")); - } - - - - protected void setTrackDetail1() - { -// if(app.getCurrentTrack().getTrackBean().getTrackId() != trackId && app.getRecordingTrack().getTrackBean().getTrackId() == trackId) -// activity.app.setCurrentTrack(activity.app.getRecordingTrack()); - -// currentTrack = app.getTrackCache().get(trackId); -// lastTrack = app.getTrackCache().get((Integer.valueOf(lastId))); - -// Iterator reader=app.getTrackCache().keySet().iterator(); -// -// while(reader.hasNext()) -// { -// int i =reader.next(); -// Track tr = app.getTrackCache().get(i); -// QLog.getLogger().d(dTAG, TAG+ " app.getTrackCache().get(i)'s track id, key of "+i +" : "+ tr.getTrackBean().getTrackId() ); -// } -// - setVersion(); - QLog.getLogger().d(dTAG, TAG+ " ..................end of get ids............. "+ System.currentTimeMillis() ); - if(currentStat ==null){ - - if(app.getCurrentTrack().getTrackBean().getTrackId() == trackId){ - currentStat = new Statics_bean(app.getCurrentTrack().getTrackBean()) ; - } - else - return; - } - - if(app.getCurrentTrack().getTrackBean().getTrackId() == trackId){ //check and update the statistics - try{ - if(currentStat.getAvs()!=app.getCurrentTrack().getTrackBean().getAvs()){ - app. mStatistics.trackMinus(app.getCurrentTrack()); - app. mStatistics.mergeTrack(app.getCurrentTrack()); - // if( canSendLocation2UI) - app.writeStatiscs(); - getStat(); - } - }catch(Exception e){ - - } - -// currentStat = new Statics_bean(app.getCurrentTrack().getTrackBean()) ; - - - - } - - if(currentStat ==null){ // some case cause currentStat = null - - if(app.getCurrentTrack().getTrackBean().getTrackId() == trackId){ - currentStat = new Statics_bean(app.getCurrentTrack().getTrackBean()) ; - } - else - return; - } - - - String td_trackEndTime = Utils.getFormatedTime(currentStat.getEndTime()) ;//+currentStat.getStatus() ; - if(activity.app.getRecordingTrack().getTrackBean().getTrackId()==trackId) - td_trackEndTime="运动进行中"; -// final String td_textView_OffTime1 = Utils.getTimeCnt( currentStat.getOffTime(),showSecondes); - -// final String td_textView_Rd1 = String.format("%.2f", currentStat.getMaxRdist()/1000.0 ); -// final String td_textView_name =currentStat.getName(); - - mDistanceText1.setText(String.format("%.2f", currentStat.getDist()/1000.0 )); - mTotalTimeText1.setText(Utils.getTimeCnt( currentStat.getTotalTime(),showSecondes)); - mRdText1.setText(String.format("%.2f", currentStat.getMaxR()/1000.0 )); - if(currentStat.getSvrNo()>0) - mTrackId.setText(String.valueOf(currentStat.getSvrNo())); -// if(mTrack.getTrackBean().getType()==TrackType.GPX && currentStat.getSvrNo()==0 ||mTrack.isLushu()) - -// mTextAccount.setText(mTrack_bean.getUserName()); - if(activity.app.user!=null){ - mTextAccount.setText(mTrack_bean.getUserid()==activity.app.user.getUserbean().getId()?activity.app.user.getUserbean().getUserName()/*.getAccount()*/:""); - } - if(mTrack.isLushu()) - return; - - if(mTrackStarTimeText==null)return; - -// if(currentStat.getSvrNo()>0) -// mTrackId.setText(String.valueOf(currentStat.getSvrNo())); -// mTrackId.setText(String.valueOf(trackId)); - mTrackStarTimeText.setText(Utils.getFormatedTime(currentStat.getStartTime()) ); - mTrackEndTimeText.setText(td_trackEndTime); - // mSummaryText.setText(td_textView_Distance1); -// mRoadBookText.setText(td_textview_roadbook); - - if(currentStat.getTopSpeed()>= currentStat.getAvs()) - mTopSpeedText1.setText(String.format("%.2f", currentStat.getTopSpeed())); - if(mSpeedText1!=null) - mSpeedText1.setText(String.format("%.2f", currentStat.getAvs() )); - mtSpeedText1.setText( String.format("%.2f", currentStat.getTavs() )); - if(mBurnText1!=null) - mBurnText1.setText( String.format("%.0f", currentStat.getBurn() )); - - - mTotaleUpText1.setText(String.format("%.0f",currentStat.geteUpDist())); - -// mTotaleDownText1.setText(td_textView_eDown1); - if(mSportTimeText1!=null) - mSportTimeText1.setText(Utils.getTimeCnt( currentStat.getSportTime(),showSecondes)); -// mPausedTimeText1.setText(td_textView_paused_time1); - if(currentStat.getUpDist()>0 ){ - mTotalUpText1.setText(String.format("%.2f",currentStat.getUpDist()/1000)); - mTotalDownText1.setText(String.format("%.2f",currentStat.getDownDist()/1000)); - mMaxEleText1.setText(String.format("%.0f",currentStat.getMaxEle())); - mMinEleText1.setText(String.format("%.0f",currentStat.getMinEle())); - } - if(currentStat.getKmTime()>0) - mKmTimeText1.setText(Utils.getTimeMS(currentStat.getKmTime())); -// showCharts(2); -// td_btnPlayback.setEnabled(currentTrack.getTrackBean().getStatus() != QiYouConstant.TRACK_STATUS_TRACKING); -// td_btnPlayback.setEnabled(activity.app.getRecordingTrack().getTrackBean().getTrackId() != trackId -// || activity.app.getRecordingTrack().getTrackBean().getTrackId() == trackId -// && activity.app.getRecordingTrack().getTrackBean().getStatus()!=QiYouConstant.TRACK_STATUS_TRACKING); -// } -// }); - validEditButtons(); - - - - } - @Override - protected void setStaticMap(){ - super.setStaticMap(); - if(staticMapImg==null)return; - IL.DisplayImage(mTrack.getStaticMap(),staticMapImg); - /* - if(mTrack.isStaticMapExist()){ - IL.DisplayImage(mTrack.getStaticMap(),staticMapImg); - } - else - - staticMapImg.setVisibility(View.GONE);*/ - - } - - -/* private void getTrackDetailUpdated(){ - app.getCurrentTrack().getTrackBean().setName(mNameEdit.getText().toString()); - app.getCurrentTrack().getTrackBean().setComment(mCommentEdit.getText().toString()); - app.getCurrentTrack().getTrackBean().setDescription(mDescEdit.getText().toString()); - - }*/ - - - protected void setTrackDetailMax() - {if(TypeStatistics==null)return; - mTopSpeedText3.setText(String.format("%.2f", TypeStatistics.getStatTrack().getTopSpeed())); - mSpeedText3.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvSpeed())); - mtSpeedText3.setText(String.format("%.2f",TypeStatistics.getStatTrack().getTavSpeed())); - mBurnText3.setText( String.format("%.0f", TypeStatistics.getStatTrack().getBurn() )); - mDistanceText3.setText(String.format("%.2f",TypeStatistics.getStatTrack().getDist()/1000)); - mTotaleUpText3.setText(String.format("%.0f",TypeStatistics.getStatTrack().getUpDistE())); - if(TypeStatistics.getStatTrack().getUpDistE()>0){ - mTotalUpText3.setText(String.format("%.2f",TypeStatistics.getStatTrack().getUpDistE()/1000)); - mTotalDownText3.setText(String.format("%.2f",TypeStatistics.getStatTrack().getDownDist()/1000)); - mMaxEleText3.setText(String.format("%.0f",TypeStatistics.getStatTrack().getMaxEle())); - mMinEleText3.setText(String.format("%.0f",TypeStatistics.getStatTrack().getMinEle())); - } -// mTotaleDownText3.setText(String.format("%.0f", Math.abs(TypeStatistics.getStatTrack().getMaxeDownDist()))); - mSportTimeText3.setText( Utils.getTimeCnt(TypeStatistics.getStatTrack().getSportTime(),showSecondes)); -// mPausedTimeText3.setText(Utils.getTimeCnt( TypeStatistics.getStatTrack().getMaxPause(),showSecondes)); - mTotalTimeText3.setText(Utils.getTimeCnt(TypeStatistics.getStatTrack().getTotalTime(),showSecondes)); -// mOffTimeText3.setText(Utils.getTimeCnt( TypeStatistics.getStatTrack().getMaxOffTime(),showSecondes)); - mRdText3.setText(String.format("%.2f",TypeStatistics.getStatTrack().getMaxR()/1000)); - if( TypeStatistics.getStatTrack().getMinKmTime()>0) - mKmTimeText3.setText(Utils.getTimeMS(TypeStatistics.getStatTrack().getMinKmTime())); - setTrackDetailAv(); - setSelectedTrackType(); - } - - /* - * av track - */ - protected void setTrackDetailAv() - { - mTopSpeedText4.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvtopSpeed())); - mSpeedText4.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvavSpeed())); - mtSpeedText4.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvTavSpeed())); - mBurnText4.setText( String.format("%.0f", TypeStatistics.getStatTrack().getAvBurn())); - - mDistanceText4.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvdist()/1000)); -// mTotaleUpText4.setText(String.format("%.0f",TypeStatistics.getStatTrack().getAveUpDist()+TypeStatistics.getStatTrack().getAveDownDist())); - mTotaleUpText4.setText(String.format("%.0f",TypeStatistics.getStatTrack().getAveUpDist() )); - if(TypeStatistics.getStatTrack().getAvUpDist()>0){ - mTotalUpText4.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvUpDist()/1000 )); - mTotalDownText4.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvDownDist()/1000 )); - mMaxEleText4.setText(String.format("%.0f",TypeStatistics.getStatTrack().getAvMaxEle() )); - mMinEleText4.setText(String.format("%.0f",TypeStatistics.getStatTrack().getAvMinEle() )); - } -// mTotaleDownText4.setText(String.format("%.0f", Math.abs(TypeStatistics.getStatTrack().getAveDownDist()))); - mSportTimeText4.setText( Utils.getTimeCnt(TypeStatistics.getStatTrack().getAvsportTime(),showSecondes)); -// mPausedTimeText4.setText(Utils.getTimeCnt( TypeStatistics.getStatTrack().getAvpause(),showSecondes)); - mTotalTimeText4.setText(Utils.getTimeCnt(TypeStatistics.getStatTrack().getAvtotalTime(),showSecondes)); -// mOffTimeText4.setText(Utils.getTimeCnt( TypeStatistics.getStatTrack().getAvoffTime(),showSecondes)); - mRdText4.setText(String.format("%.2f",TypeStatistics.getStatTrack().getAvmaxR()/1000)); - if(TypeStatistics.getStatTrack().getAvKmTime()>0) - mKmTimeText4.setText(Utils.getTimeMS(TypeStatistics.getStatTrack().getAvKmTime())); - setCurrentColors(); - } - - - - void setCurrentColors(){ - if(mDistanceText1==null ||currentStat==null)return; - - mDistanceText1.setText(String.format("%.2f", currentStat.getDist()/1000.0 )); - int style =0; - - style=currentStat.getDist()==TypeStatistics.getStatTrack().getDist()?R.style.topText_b: - currentStat.getDist()0) - mDistanceText1.setTextAppearance(activity, style); - - style=currentStat.getMaxR()==TypeStatistics.getStatTrack().getMaxR()?R.style.topText_b: - currentStat.getMaxR()0) - mRdText1.setTextAppearance(activity, style); -// mTotalTimeText1.setText(Utils.getTimeCnt( currentStat.getTotalTime(),showSecondes)); -// mRdText1.setText(String.format("%.2f", currentStat.getMaxRdist()/1000.0 )); - - if(mTrack.isLushu()) - return; - - if(mTrackStarTimeText==null)return; - - - - style=currentStat.getTopSpeed()==TypeStatistics.getStatTrack().getTopSpeed()?R.style.topText_b: - currentStat.getTopSpeed()0) - mTopSpeedText1.setTextAppearance(activity, style); -// mTopSpeedText1.setText(String.format("%.2f", currentStat.getTopSpeed())); - if(mSpeedText1!=null){ - - style=currentStat.getAvs()==TypeStatistics.getStatTrack().getAvSpeed()?R.style.topText_b: - currentStat.getAvs()0) - mSpeedText1.setTextAppearance(activity, style); -// mSpeedText1.setText(String.format("%.2f", currentStat.getAVS() )); - } - - - style=currentStat.getTavs()==TypeStatistics.getStatTrack().getTavSpeed()?R.style.topText_b: - currentStat.getTavs()0) - mtSpeedText1.setTextAppearance(activity, style); -// mtSpeedText1.setText( String.format("%.2f", currentStat.getTAVS() )); - - if(mBurnText1!=null){ - style=currentStat.getBurn()==TypeStatistics.getStatTrack().getBurn()?R.style.topText_b: - currentStat.getBurn()0) - mBurnText1.setTextAppearance(activity, style); -// mBurnText1.setText( String.format("%.0f", currentStat.getBurn() )); - } - - - style=currentStat.geteUpDist()==TypeStatistics.getStatTrack().getUpDistE()?R.style.topText_b: - currentStat.geteUpDist()0) - mTotaleUpText1.setTextAppearance(activity, style); - -// mTotaleUpText1.setText(String.format("%.0f",currentStat.geteUpDist())); - - // mTotaleDownText1.setText(td_textView_eDown1); - if(mSportTimeText1!=null){ - style=currentStat.getSportTime()==TypeStatistics.getStatTrack().getSportTime()?R.style.topText_b: - currentStat.getSportTime()0) - mSportTimeText1.setTextAppearance(activity, style); - -// mSportTimeText1.setText(Utils.getTimeCnt( currentStat.getSportTime(),showSecondes)); - } - // mPausedTimeText1.setText(td_textView_paused_time1); - if(currentStat.getUpDist()>0 ){ - style=currentStat.getUpDist()==TypeStatistics.getStatTrack().getUpDistE()?R.style.topText_b: - currentStat.getUpDist()0) - mTotalUpText1.setTextAppearance(activity, style); - -// mTotalUpText1.setText(String.format("%.2f",currentStat.getUpDist()/1000)); - style=currentStat.getDownDist()==TypeStatistics.getStatTrack().getDownDist()?R.style.topText_b: - currentStat.getDownDist()0) - mTotalDownText1.setTextAppearance(activity, style); - -// mTotalDownText1.setText(String.format("%.2f",currentStat.getDownDist()/1000)); - style=currentStat.getMaxEle()==TypeStatistics.getStatTrack().getMaxEle()?R.style.topText_b: - currentStat.getMaxEle()0) - mMaxEleText1.setTextAppearance(activity, style); - -// mMaxEleText1.setText(String.format("%.0f",currentStat.getMaxEle())); - /* style=currentStat.getMinEle()==TypeStatistics.getStatTrack().getMaxMinEle()?R.style.topText_b: - currentStat.getMinEle()>TypeStatistics.getStatTrack().getAvMinEle()?R.style.lowText:0; - if(style>0) - mMinEleText1.setTextAppearance(activity, style); */ - -// mMinEleText1.setText(String.format("%.0f",currentStat.getMinEle())); - } - - style=currentStat.getKmTime()==TypeStatistics.getStatTrack().getMinKmTime()?R.style.topText_b: - currentStat.getKmTime()>TypeStatistics.getStatTrack().getAvKmTime()?R.style.lowText:0; - if(style>0) - mKmTimeText1.setTextAppearance(activity, style); - -// mKmTimeText1.setText(Utils.getTimeMS(currentStat.getKmTime())); - } - - - -/* private ImageGetter imageGetter = new ImageGetter() { - @Override - public Drawable getDrawable(String source) { -// int id = Integer.parseInt(source);//source为图片id。比如 R.id.tupian - - Drawable d = null; - try { - d = Drawable.createFromPath(source);// getResources().getDrawable(id); - } catch (Exception ex) { - ex.printStackTrace(); - } - if(d!=null) d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); - return d; - } -};*/ - - - /*void saveTrack() { - boolean isSaveAble=false; - isSaveAble = mCommentEdit.getText().toString().equalsIgnoreCase(app.getCurrentTrack().getTrackBean().getComment()); - isSaveAble = isSaveAble || mDescEdit.getText().toString().equalsIgnoreCase(app.getCurrentTrack().getTrackBean().getDescription()); - isSaveAble = isSaveAble || mNameEdit.getText().toString().equalsIgnoreCase(app.getCurrentTrack().getTrackBean().getName()); - isSaveAble = isSaveAble ||trackType==app.getCurrentTrack().getTrackBean().getType().toInt(); - - if(!isSaveAble ){ - Toast.makeText(activity,"没有变更需要保存。", Toast.LENGTH_SHORT).show(); - return; - } - - getTrackDetailUpdated(); - Intent serviceIntent = new Intent(activity, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.UPDATE_TRACK, trackId); - // serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_FORCEREFRESH, true); - activity.startService(serviceIntent); - Toast.makeText(activity,"变更已成功保存。", Toast.LENGTH_SHORT).show(); - } - */ - - - - private ArrayAdapter spAdapter; - - @Override - void initTrackTypeSpin(){ - - int type_array= Utils.getTrackType();//R.array.trackType; -// if(QiYouConstant.DEVELOPER_MODE) -// type_array =R.array.trackType_develop_use; -// - - spDetailTrackType = (Spinner)vContainer.findViewById(R.id.SpinnerTrackType); - - if(spDetailTrackType==null)return; - spDetailTrackType.setVisibility(View.VISIBLE); - - //将可选内容与ArrayAdapter连接起来 - spAdapter = QArrayAdapter.createFromResource( getActivity(), type_array, android.R.layout.simple_spinner_item); - - //设置下拉列表的风格 - spAdapter.setDropDownViewResource(R.layout.spinner_item); - - //将adapter2 添加到spinner中 - spDetailTrackType.setAdapter(spAdapter); - - //添加事件Spinner事件监听 - spDetailTrackType.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); - - //设置默认值 -// spDetailTrackType.setVisibility(View.VISIBLE); - - } - // int trackType; - class SpinnerXMLSelectedListener implements OnItemSelectedListener{ - @Override - public void onItemSelected(AdapterView spinner, View textView, int spID, - long arg3) { - switch (spinner.getId() ){ - case R.id.SpinnerTrackType: { - oTrackType = activity.app.getCurrentTrack().getTrackBean().getType().toInt(); - activity.app.getCurrentTrack().getTrackBean().setType(TrackType.valueOf(spID)); - mTrackType.setText(spDetailTrackType.getSelectedItem().toString()); - } - - break; - } - } - - @Override - public void onNothingSelected(AdapterView arg0) { - // TODO Auto-generated method stub - - } - - } - @Override - void setSelectedTrackType(){ -// spDetailTrackType.setSelection(activity.app.getCurrentTrack().getTrackBean().getType().toInt()); - /* spDetailTrackType.setSelection(inType); - - mTrackType.setText(spDetailTrackType.getSelectedItem().toString()); - */ - - if(inType< spDetailTrackType.getCount()){ - spDetailTrackType.setSelection(inType); - }else - spDetailTrackType.setSelection(spDetailTrackType.getCount()-1); - - mTrackType.setText(spDetailTrackType.getSelectedItem().toString()); -// spDetailTrackType.setEnabled(inType!=TrackType.GPX.toInt() );//||QiYouConstant.DEVELOPER_MODE); - } - void getStatTracks(){ - - TypeStatistics = new TypeStatistics(); - if(activity.app.getStatisticsTrack(inType)==null) return;//no records for selected type or date. - - - - ConcurrentHashMap sbs =activity.app.getStatisticsTrack(inType).getSbs(); - Statics_bean sb; - - for(Integer key :sbs.keySet()){ - sb=sbs.get(key); - if(sb==null)continue; - TypeStatistics.getSbs().put(sb.getTrackid(), sb); - } - - StatTrack st = new StatTrack(); - for(Integer key : TypeStatistics.getSbs().keySet()){ - sb=TypeStatistics.getSbs().get(key); -// st.seteDownDist(sb.geteDownDist() ); -// st.seteUpDist( sb.geteUpDist()+sb.geteDownDist()); - st.setUpDistE( sb.geteUpDist()); - st.setTopSpeed(sb.getTopSpeed() ); - st.setPause(sb.getPause() ); - st.setOffTime( sb.getOffTime()); - st.setDist(sb.getDist()); - st.setMaxR( sb.getMaxR()); - st.setSportTime( sb.getSportTime()); - st.setAvSpeed(sb.getAvs()); - st.setTavSpeed(sb.getTavs()); - st.setBurn(sb.getBurn()); -// st.setTotalTime(sb.getSportTime()+sb.getPause()); - st.setTotalTime(sb.getTotalTime()); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd getStatTracks------------------" ); -// -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getDistance()"+sb.getDistance() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getSportTime()"+sb.getSportTime() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getAVS()"+sb.getAVS() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getPause()"+sb.getPause() ); - - } - - TypeStatistics.setStatTrack(st); - QLog.getLogger().d(dTAG, TAG+ " dddddddddddddddddddddd-------------------Get StatTrack. -------------" ); -// statChart= activity.app.mStatistics.getLastStrack(); - - - } - - - void getStatTrack(){ -// TypeStatistics =activity.app.getTracksStat(mTrack_bean.getType().toInt(), 0, 0); - TypeStatistics =activity.app.getTracksStat(inType, 0, 0); - - QLog.getLogger().d(dTAG, TAG+ " -------------------Get StatTrack. -------------" ); - } - - - @Override - void showTabs(boolean isVisible ){ - - if(trackId==0)return; - if(tabhost==null)return; - - String title=isVisible?tabData:trackId>0?"数据加载中。。。":tabData;//"定位成功后将自动开始"; - - TextView textview = (TextView)tabhost.getTabWidget().getChildAt(0).findViewById(android.R.id.title); -// textview.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); - textview.setText(title); - - - int visible = isVisible?View.VISIBLE:View.GONE; - for(int i=1;i0){ - mTrackId.setText(String.valueOf(svrNo)); - btnUpload.setText("更新云端"); -// handler.sendEmptyMessage(0); - - } - - } - - /* @Override - void showSpeedKmChart(int type){ - Intent intent = new Intent(activity, ChartSpeedKm.class); - Bundle bundle=new Bundle(); - bundle.putInt("type", type); - intent.putExtras(bundle); - activity.startActivity(intent); - - };*/ - - @Override - public void onResume() { -// setTrackDesc(); - super.onResume(); - if(editNewCate!=null){ - editNewCate.clearFocus(); - } - -// if(mTrack_bean.getAvStatus()!=TrackAvStatus.ACTIVE){ - if(!this.isWebRequest && mTrack_bean.getAvStatus()==TrackAvStatus.DELETED){ - activity.showTrackStatics(); - } -// activity.updateActionBarTitle( getResources().getString(R.string.frg_trackdetail)+ " 编号"+trackId); - int title=isWebRequest?R.string.frg_trackWeb - :inflat_source ==R.layout.gpx_lushu_fragment?R.string.frg_trackLushu:R.string.frg_trackdetail; - -// activity.updateActionBarTitle( getResources().getString(R.string.frg_trackdetail)+ " "+mTrack_bean.getName()); - activity.updateActionBarTitle( getResources().getString(title)+ "|"+mTrack_bean.getName()); -// activity.app.currentActiveFragment =getFTag(); - validEditButtons(); -// activity.app.canSendLocation2UI =false; - activity.app.updateUIstatus(false); - setWorkingTrack(); - Utils.hideSoftKeyboard(activity); -// activity.updateTabVisibility(false); -// mRecTrack = activity.app.getCurrentTrack().getTrackBean(); -// drawTrack=true; -// drawTrack(); -// mMapView.onResume(); -// setSelectedTrackType(); - QLog.getLogger().d(dTAG," 当前用户id "+ activity.app.user.getUserbean().getId() ); - if(isForShare &&mTrack.getTrackBean().getTrackId()>0 && activity.app.user.getUserbean().getId()>0){ -// isForShare =false; - this.uploadTrack(mTrack); - } - } - - - - @Override - public void onPause() { -// activity.updateTabVisibility(true); - super.onPause(); - - } - @Override - public void onDestroy() { - super.onDestroy(); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - } - @Override - public void setTabOnFiling() { - MAPVIEW_INDEX=2; - maxTabIndex = 2; - - } - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub -// activity.updateActionBar(true ); - return false; - } - - - - //to get trackList can be merged - - /* - private String whereClause=" 1=1 "; - @Override - public Loader onCreateLoader(int arg0, Bundle arg1) { - String[] projection = new String[] {TrackProvider.KEY_ID,TrackProvider.KEY_TRACK_NAME }; - String orderby =( TrackProvider.KEY_ID +" DESC"); - whereClause+=" and ( ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")=" +TrackAvStatus.ACTIVE + - " OR " + TrackProvider.KEY_TRACK_AVSTATUS+" = "+TrackAvStatus.ACTIVE +")"; - whereClause += " and TrackProvider.KEY_ID >"+ trackId; - return new CursorLoader(activity, TrackProvider.TRACKS_URI, - projection, whereClause, null, orderby); - - } - @Override - public void onLoadFinished(Loader arg0, Cursor arg1) { - // TODO Auto-generated method stub - - } - @Override - public void onLoaderReset(Loader arg0) { - // TODO Auto-generated method stub - - }*/ -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackList_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackList_fragment.java deleted file mode 100644 index 52809a1..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackList_fragment.java +++ /dev/null @@ -1,390 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.ListView; -import android.widget.TabHost; -import android.widget.TabHost.OnTabChangeListener; - -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.NoScrollGridView; -import com.qiyou.mb.android.utils.enums.TrackType; -//import android.widget.ImageView; - -/** - * @author mwang - * - */ -public class TrackList_fragment extends /*TrackMap_fragment *//*TrackingBasic_fragment*/ Querybase_fragment - { -// public static final String TAG ="com.qiyou.TrackList_fragment"; -// public static final String dTAG ="com.qiyou"; - @Override - public void setFTag(){ - TAG="com.qiyou.TrackList_fragment"; -// FirstTabTextColor= getResources().getColorStateList(R.color.red); -// FirstTabBackGround=R.drawable.icon_databse; - } - - public static String getFTag(){ - return "com.qiyou.TrackList_fragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.TrackList_fragment"; - } - - private NoScrollGridView picGrid; - - - - /* private EditText edUserName; - private EditText edSvrNo; - private EditText webCity; - - private ImageButton btn_webquery; - ImageButton btn_pageup; - ImageButton btn_pagedown; - private CheckBox chk_web_pic; - private CheckBox chk_my_tracks; - boolean isShowPic; - private boolean isShowMytrackOnly; - - - private LinearLayout ll_web_others; - private LinearLayout ll_webinput;*/ - -// private String webUserName=""; -// private String webSvrNo=""; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if(activity==null){ - activity = (com.qiyou.mb.android.ui.MainActivity)getActivity(); - } - firstLoad=true; - if(activity!=null &&activity.app!=null){ - webTrackType = activity.app.getLastTracktype(); -// IL= new com.qiyou.mb.android.utils.ImageLoader(activity); - } - IL= new com.qiyou.mb.android.utils.ImageLoader(getActivity()); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - vContainer = inflater.inflate(R.layout.track_list, container, false); -// noRec = (TextView) vContainer.findViewById(R.id.trakList_tv_norec); - localTracklist =(ListView)vContainer.findViewById(R.id.tr_list); - localTracklist.setOnItemClickListener(trackListItemListener); - - - - chk_show_pic = (CheckBox)vContainer.findViewById(R.id.fm_chk_show_pic); - chk_show_pic.setOnCheckedChangeListener(m_checkboxListener); - chk_show_map = (CheckBox)vContainer.findViewById(R.id.fm_chk_show_map); - chk_show_map.setOnCheckedChangeListener(m_checkboxListener); - initialView(); - showCategoryList(cateLv,null); - activity.updateActionBarTitle(R.string.frg_list); - return vContainer; - } - - - - CheckBox.OnCheckedChangeListener m_checkboxListener =new CheckBox.OnCheckedChangeListener(){ - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - // TODO Auto-generated method stub - switch (buttonView.getId() ){ - /*case R.id.fm_chk_web_pic: - isShowPic = !chk_web_pic.isChecked(); -// doWebTrackQuery(); - break;*/ - case R.id.fm_chk_show_pic: - doTrackQuery(); - break; - case R.id.fm_chk_show_map: - doTrackQuery(); - break; - - - } - - - } - - }; -// @Override -// protected void initialView(){ -// super.initialView(); -// } - - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - - getLoaderManager().initLoader(0, null, this); - } - - - - - - final String dateTypeTab ="轨迹"; - final String catesTab ="标签"; -// final String inactiveTab ="回收站"; - final String routeTab ="路书"; - - protected void initialTabhost(){ - - tabhost = (TabHost)vContainer.findViewById(R.id.queryTabhost); - if(tabhost==null)return; - tabhost.setup(); - - TabHost.TabSpec statTab = tabhost.newTabSpec(dateTypeTab); - statTab.setIndicator(dateTypeTab); - statTab.setContent(R.id.tab_data_type_picker); - tabhost.addTab(statTab); - - TabHost.TabSpec t1 = tabhost.newTabSpec(routeTab); - t1.setIndicator(routeTab); - t1.setContent(R.id.tab_route); - tabhost.addTab(t1); - - TabHost.TabSpec t2 = tabhost.newTabSpec(catesTab); - t2.setIndicator(catesTab); - t2.setContent(R.id.tab_categories); - tabhost.addTab(t2); - - - - - initialTabhostStyle(tabhost); - - - - tabhost.setOnTabChangedListener(new OnTabChangeListener() { - @Override - public void onTabChanged(String tabId ) { - - - onMyTabChanged(tabId); - - - - - } - }); - - } - -// String getShortString(String str,int lng){ -//// String value =cursor.getString(6); -// str =TextUtils.isEmpty(str)?str:str.length()>lng?str.substring(0,lng)+"...":str; -// str =TextUtils.isEmpty(str)?str:" "+str; -// return str; -// } - - /* *//** - * {@inheritDoc} - * When a venue is clicked, fetch the details from your server and display the detail page. - *//* - @Override - public void onListItemClick(ListView l, View v, int position, long theid) { - super.onListItemClick(l, v, position, theid); - // activity.app.setCurrentTrack(null); - // Find the ID and Reference of the selected track. - - Cursor c = adapter.getCursor(); - c.moveToPosition(position); - String id = c.getString(c.getColumnIndex(TrackProvider.KEY_ID)); - QLog.getLogger().d(dTAG, TAG+ "start request for track of id "+ id ); - - // Request the parent Activity display the track detail UI. - activity.showTrackDetail(id); - } - */ - // 条目上单击处理方法. -// int selectedTrackItem=-1; -// int selectedActItem=-1; -// int selectMemberItem=-1; -// int selectActShareItem=-1; -// int selectGroupItem=-1; -// boolean isActShareQuery=false; - - - - @Override - void showDetailTrack(int trackId){ - -// QLog.getLogger().d(dTAG, TAG+String.format(" to show track detail....is NormalQuery ? %s,is isRouteQuery ? %s ,is isByCatesQuery? %s " , isNormalQuery,isRouteQuery,isByCatesQuery)); - - switchTabOptions(currentTab); - - if(isNormalQuery){ -// if(lastTypeId==TrackType.GPX.toInt()) -// activity.showGpxTrackDetail(lastTypeId,trackId,false); -// else - activity.showTrackDetail(lastTypeId,trackId); - }else - if( isRouteQuery /*||isInactiveQuery*/ ||isByCatesQuery ){ - int trackType =lastTypeId; - if(activity.app.getCurrentTrack().getTrackBean().getTrackId()==trackId){ - trackType =activity.app.getCurrentTrack().getTrackBean().getType().toInt(); - } - if( isRouteQuery || trackType==TrackType.GPX.toInt()||activity.app.getCurrentTrack().isLushu()) - activity.showGpxTrackDetail(TrackType.GPX.toInt(),trackId,false); - else - activity.showTrackDetail(trackType,trackId); - } - /*else if (this.isWebTrackQuery||this.isActShareQuery){ - - this.activity.showGpxTrackDetail( this.svrTrackType , trackId, true); - }*/ - - - - - - - } - /* private OnClickListener avatarClickListener = new OnClickListener() { - - - @SuppressWarnings("unchecked") - - public void onClick(View v) { - - Map item = (Map) v.getTag();//还记得上面的那个setTag么?我们在这里给丫取出来 - - Intent mIntent = new Intent(AdapterWithHashMap.this.context, - - MySelf.class); - - mIntent.putExtra("user_id", item.get("uid").toString()); - - - AdapterWithHashMap.this.context.startActivity(mIntent); - - } - - }; - */ - - - - @Override - public void onResume() { -// activity.app.currentActiveFragment =TAG; - super.onResume(); - activity.updateActionBarTitle( getResources().getString(R.string.frg_list)); -// QLog.getLogger().e(dTAG,TAG+" app.currentActiveFragment of trackList: "+TAG); - - - } - @Override - public void onPause(){ - super.onPause(); - if(progressDialog!=null)progressDialog.dismiss(); - } - -// com.qiyou.mb.android.utils.ImageLoader IL ; - - - - - - - - - - - - - - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - @Override - public void setTabOnFiling() { - - maxTabIndex = 3; - - } - @Override - protected void setSelectedTab(){ - if(tabhost!=null&& tabhost.getCurrentTab()!=currentTab){ - tabhost.setCurrentTab(currentTab); - } - } - - - - @Override - protected void onMyTabChanged(String tabId){ - super.onMyTabChanged(tabId); - /*if(tabhost==null)return; - initialTabhostStyle(tabhost); - setSelectedTabhostStyle(tabhost); - currentTab= tabhost.getCurrentTab();*/ - processTabQuery(); - - - } - - void processTabQuery(){ - if(progressDialog!=null) - progressDialog.dismiss(); -// noRec.setVisibility(View.GONE); - - switchTabOptions(currentTab); - - localTracklist.setVisibility(View.GONE); - - - canclick =true; - if(currentTab==0){ - this.localTracklist.setVisibility(View.VISIBLE); - doTrackQuery(); - }else if(isByCatesQuery){ - this.localTracklist.setVisibility(View.VISIBLE); - doCatesQuery(); -// }else if(isInactiveQuery){ -// doInactiveQuery(); - }else if(isRouteQuery){ - this.localTracklist.setVisibility(View.VISIBLE); - doRouteQuery(); - } - } - - - void switchTabOptions(int queryType){ - isNormalQuery =queryType ==0; - isRouteQuery =queryType ==1; - isByCatesQuery =queryType ==2; - - } - - @Override - public void doQuery() { - // TODO Auto-generated method stub - doTrackQuery(); - } -} - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackMap_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackMap_fragment.java deleted file mode 100644 index 15fba73..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackMap_fragment.java +++ /dev/null @@ -1,2727 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.graphics.drawable.BitmapDrawable; -import android.location.Location; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.text.TextUtils; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.MeasureSpec; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback; -import com.baidu.mapapi.map.BaiduMap.OnMapTouchListener; -import com.baidu.mapapi.map.BaiduMap.SnapshotReadyCallback; -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.map.DotOptions; -import com.baidu.mapapi.map.InfoWindow; -import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener; -import com.baidu.mapapi.map.MapStatus; -import com.baidu.mapapi.map.MapStatusUpdate; -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.MyLocationConfiguration; -import com.baidu.mapapi.map.MarkerOptions.MarkerAnimateType; -import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode; -import com.baidu.mapapi.map.MyLocationData; -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.model.LatLngBounds; -import com.baidu.mapapi.overlayutil.OverlayManager; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.R.color; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.GPItem; -import com.qiyou.mb.android.beans.basic.Media; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.BMapUtil; -import com.qiyou.mb.android.utils.CompositDrawableView; -import com.qiyou.mb.android.utils.TextDrawableView; -import com.qiyou.mb.android.utils.TextDrawableViewKm; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.bmap.ZoomControlView; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.WorkingTrackType; -import com.qiyou.mb.android.utils.enums.mediaType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.SharedLocation; -//import com.baidu.mapapi.model.inner.LatLng; -//import com.baidu.mapapi.map.OverlayOptions; -//import com.baidu.mapapi.map.TextOptions; -//import com.baidu.mapapi.model.LatLng; - -@TargetApi(Build.VERSION_CODES.HONEYCOMB) -public class TrackMap_fragment extends TrackingBasic_fragment implements IlocationFragment { -//public static final String popupRight = null; - - // public static final String TAG ="com.qiyou.TrackMap_fragment"; -// public static final String dTAG ="com.qiyou"; - @Override - public void setFTag(){ - TAG="com.qiyou.TrackMap_fragment"; - } -// View vContainer; - /** - * MapView 是地图主控件 - */ - -// int screenShotDist=0; -// Waypoint mdWp; -// protected MapController mMapController = null; - // 定位相关 - //LocationClient mLocClient; - //public MyLocationListenner myListener = new MyLocationListenner(); - -// protected LineOverlay gpxOverlay = null; -// protected GraphicsOverlay gpRecordingOverlay = null; -// protected GraphicsOverlay gpNaviOverlay = null; -// protected GraphicsOverlay gpPlaybackOverlay = null; -//// protected GraphicsOverlay gpKMpointsOverlay = null; -// protected GraphicsOverlay gpTurnPointsOverlay = null; -// protected LineOverlay gpBearLinesOverlay = null; -// protected GraphicsOverlay gpFmPointsOverlay = null; -// protected /*ItemizedOverlay*/ Marker startOverlay =null; -// protected /*ItemizedOverlay*/ Marker endOverlay =null; - protected /*ItemizedOverlay */Marker bearStartMarker =null; - protected /*ItemizedOverlay*/Marker bearEndMarker =null; -// protected /*ItemizedOverlay*/TrackOverlay gpxStartOverlay =null; -// protected /*ItemizedOverlay*/TrackOverlay gpxEndOverlay =null; -// protected /*ItemizedOverlay*/MarkerOptions kmOverlay =null; - - protected List shortLines =new ArrayList(); - protected LineOverlay gpBearLinesOverlay = null; - - - private MdOverlay mPhotoOverlay = null; - private RoadOverlay mRdOverlay = null; - protected TrackOverlay recordingOverlay; - private TrackOverlay gpxOverlay; - private TrackOverlay recordingStartOvelay; - private TrackOverlay recordingEndOvelay; - private MdOverlay kmOverlay = null; - private RoadOverlay mShareOverlay = null; -// private RdOverlay mRdOverlay = null; -// private PopupOverlay popMd = null; -// private PopupOverlay popRd = null; -// private OverlayItem mCurItem = null; - - protected TextView popupText; - protected View popupInfo = null; - private TextView wpNumText; - protected String[] ValidUrls; - protected String[] ValidThumbUrls; - private Handler handler ; - private HashMap picUrlMap;//<原图url,缩略图url> - - protected BaiduMap mBaiduMap; - protected InfoWindow mInfoWindow; -// private RdOverlay mShareOverlay = null; -// protected boolean isShowRestCheckOnly = false; - protected Boolean canAutoZoomMap =false;//true; - protected boolean canDrawTrack; - boolean isDrawingTrack =false; //flag that the track is in the process of drawing to avoid duplicated call to the drawTrack(..) - boolean isPlaybackTrackDrawed =false; - - - -// private ScaleView mScaleView; - private ZoomControlView mZoomControlView; - - public TrackMap_fragment() { - // TODO Auto-generated constructor stub - } - /*public static TrackMap_fragment newInstance(int trackId) - { - QLog.getLogger().d(dTAG,TAG+" "+ "newInstance(), trackId " +trackId); - TrackMap_fragment f = new TrackMap_fragment(); - if( trackId<=0) return f;//TODO: check why the 'if' exists - Bundle args = new Bundle(); - args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId); - f.setArguments(args); - return f; - }*/ - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); -// if(activity.app!=null) activity.app.currentActiveFragment =TAG; -// currentLayout =R.layout.trackingmap_fragment; -// QLog.getLogger().d(dTAG,TAG+" "+ "onCreate"); - canDrawTrack=true; - - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - super.onCreateView(inflater, container, savedInstanceState); - return vContainer; - - } - - @Override - protected void initialViews(){ - super.initialViews(); - initViewMap(); - -// locationInMap(); - - } - - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { -// myLocationOverlay = new MyLocationOverlay(mMapView); - - initialMarkLayers(); - LocationMode mCurrentMode = LocationMode.NORMAL; - BitmapDescriptor mCurrentMarker=null; - if(activity.app.playBack){ - mCurrentMode= LocationMode.FOLLOWING; - mCurrentMarker = BitmapDescriptorFactory - .fromResource(R.drawable.icon_geo); - - } - if(mBaiduMap!=null){ - - mBaiduMap - .setMyLocationConfigeration(new MyLocationConfiguration( - mCurrentMode, true, mCurrentMarker)); - - mBaiduMap.setOnMapLoadedCallback(new OnMapLoadedCallback() { - - @Override - public void onMapLoaded() { - // TODO Auto-generated method stub - zoomToSpan(); - loadPOIs(); - mBaiduMap.setCompassPosition(new android.graphics.Point(55, 55)); - } - - - }); - - mBaiduMap.setOnMapTouchListener(new OnMapTouchListener(){ - - @Override - public void onTouch(MotionEvent arg0) { - Utils.hideSoftKeyboard(activity); -// mBaiduMap.hideInfoWindow(); - if(!isShowingPicMark && mInfoWindow!=null){ - mBaiduMap.hideInfoWindow(); - isShowingPicMark =false; - } - } - - }); - } - - super.onActivityCreated(savedInstanceState); - - mapViewOnActivityCreated(); - - - } - - - void locateBaiduMapCenter(double bdlat, double bdlng){ - if(bdlat>0 && bdlat>0 ){ - - locData = new MyLocationData.Builder() - .latitude(bdlat) - .longitude( bdlng).build(); - - mBaiduMap.setMyLocationData(locData); - MapStatus.Builder builder = new MapStatus.Builder(); - builder.target(new LatLng(locData.latitude,locData.longitude)) .zoom(18.0f); - mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); - } - } - - void locateMapCenter(double lat, double lng){ - if (mBaiduMap == null) {return;} - if(lat>0 && lng>0 ){ - - locData = new MyLocationData.Builder() - .latitude(Utils.getbdLat(lat,lng)) - .longitude( Utils.getbdLon(lat,lng)).build(); - - mBaiduMap.setMyLocationData(locData); - MapStatus.Builder builder = new MapStatus.Builder(); - builder.target(new LatLng(locData.latitude,locData.longitude)) .zoom(18.0f); - mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); - } - - /* mMapView.getOverlays().remove(myLocationOverlay); - myLocationOverlay.setData(locData); - mMapView.getOverlays().add(myLocationOverlay); - myLocationOverlay.enableCompass(); - mMapController.animateTo(new LatLng( - (int) (locData.latitude * 1e6), - (int) (locData.longitude * 1e6))); - mMapView.refresh(); - - locData = new MyLocationData.Builder() - .latitude( location.getLatitude() ) - .longitude(location.getLongitude()).build(); */ - - - } - - - void mapViewOnActivityCreated(){ - - if(QiYouConstant.PV_LAST_LAT>0 ){ - locateMapCenter(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON); - } - - if(!isPlaying){ - showMapViews(); - } - /* if(isPlayback) - { - this.drawTrack(activity.app.currentTrack.getTrackBean()); - playbackTrackDrawed =true; - }*/ - - - if(isPlaying){ - setSelectedTrackType(); - } - else - QiYouConstant.MAX_GEO_TIME =QiYouConstant.PLAYBACK_TIME_INTERVAL*60; - - gpxDrawd = new ArrayList(); - -// if(!activity.app.playBack) -// drawGpx(); - - - - } - - - @Override - protected void locationInMap(Location loc){ -// takeMapScreenshot(); - canLocationMap =!canLocationMap; - - if(canLocationMap){ - - if(activity.app.isRouting /*||activity.app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag() )*/){ - if(!Utils.isNetworkConnected(activity) && !Utils.isGpsEnabled(activity)){ - Toast.makeText(activity, "地图定位需要开启GPS或网络连接", Toast.LENGTH_SHORT).show(); - canLocationMap=false; - return; - } - /*activity.app.isLocationFinding =activity.app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag() );*/ - activity.app.startAndroidGPSRequest(); - activity.app.startNetworkLocationRequest(false); - } - btnLocation.setImageResource(R.drawable.location); - if(workingTrackType==WorkingTrackType.RECORDING||activity.app.isRouting) - Toast.makeText(activity, "地图已切换到自动定位模式", Toast.LENGTH_SHORT).show(); - }else{ - if(activity.app.isRouting &&!activity.app.isLastTrackExist() - /*||activity.app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag())*/ ){ - activity.app.stopAndroidGPSRequest(); - activity.app.stopNetworkLocationRequest(); - } - if(loc!=null){ - canLocationMap=true; -// updateUI(loc,false ) ; -// updateGraphics(loc,false); - updateMapView(loc); - canLocationMap=false; - - } - if(btnLocation!=null) - btnLocation.setImageResource(R.drawable.nolocation); - if(workingTrackType==WorkingTrackType.RECORDING ||activity.app.isRouting) Toast.makeText(activity, "地图已切换到自由浏览模式", Toast.LENGTH_SHORT).show(); -// Toast.makeText(activity, "地图进入自由浏览模式", Toast.LENGTH_SHORT).show(); - } - - - } - - @Override - protected void showMapViews(){ - if(vContainer.findViewById(R.id.ll_liveshareMsg)==null){ - return; - } - - QiYouConstant.PV_BL_SHARE_LOCATION = QiYouConstant.PV_BL_SHARE_LOCATION && activity.app.user.getUserbean().getId() > 0; - - ((TextView)vContainer.findViewById(R.id.txt_livesharemsg)).setText(QiYouConstant.PV_STR_SHARE_MSG); - - vContainer.findViewById(R.id.ll_liveshareMsg).setVisibility(QiYouConstant.PV_BL_SHARE_LOCATION?View.VISIBLE:View.GONE); - - } - - @Override -protected void showPoints(int which){ - - if(which!=1 || kmOverlay==null){ - return; - } - if( kmOverlay.getOverlayMarkers().size()==0){ - - kmOverlay.addToMap(); - btnKmpoints.setImageResource(R.drawable.icon_dist); - } - else{ - kmOverlay.removeFromMap(); - btnKmpoints.setImageResource(R.drawable.icon_dist_in); - } - } - - - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) -protected void initialLiveViews(){ - - - - liveLv = (ListView)vContainer.findViewById(R.id.act_live_list); - if(liveLv!=null){ - - /* View header = inflater.inflate(R.layout.header, - (ViewGroup) vContainer(R.id.LinearLayoutHeader)); - View search_box = inflater.inflate(R.layout.search_box, - (ViewGroup) vContainer(R.id.RelativeLayoutSearchBox)); - lv.addHeaderView(header, null, false); - lv.addHeaderView(search_box, null, false); - */ - - - -// liveLv.setLayoutParams(new RelativeLayout.LayoutParams(QiYouConstant.PV_INT_SCREEN_WIDTH/2,RelativeLayout.LayoutParams.WRAP_CONTENT/2)); //set the layout, or will not show out - liveLv.setLayoutParams(new LinearLayout.LayoutParams(QiYouConstant.PV_INT_SCREEN_WIDTH/2, - LinearLayout.LayoutParams.WRAP_CONTENT /*QiYouConstant.PV_INT_SCREEN_WIDTH/3*/)); //set the layout, or will not show out - - liveLv.setOnItemClickListener(shareListItemListener); - liveLv.setOnTouchListener(new OnTouchListener() { - - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - - btn_live_refresh =(Button)vContainer.findViewById(R.id.share_btn_refresh); - btn_live_list =(Button)vContainer.findViewById(R.id.share_btn_list); - btn_live_list.setAlpha(0.8f); - btn_live_refresh.setAlpha(0.8f); -// btn_live_query =(Button)vContainer.findViewById(R.id.share_btn_query); - btn_live_query =(ImageView)vContainer.findViewById(R.id.share_btn_query); - btn_live_refresh.setOnClickListener(ButtonOnClickListener); - btn_live_list.setOnClickListener(ButtonOnClickListener); - btn_live_query.setOnClickListener(ButtonOnClickListener); - edit_act_query=(EditText)vContainer.findViewById(R.id.share_edit_username); -// edit_act_query.addTextChangedListener(watcher); - } - - // to initial map objects for sharelocation - popupText=(TextView) vContainer.findViewById(R.id.textcache); - popupInfo = (View) vContainer.findViewById(R.id.popinfo); - - - - } - - void initialMapview(){ - mMapView = (MapView) vContainer.findViewById(R.id.tm_bmapView); - mBaiduMap = mMapView.getMap(); - - mZoomControlView = (ZoomControlView) vContainer.findViewById(R.id.ZoomControlView); - mZoomControlView.setMapView(mMapView); - mMapView.showZoomControls(false); - - refreshScaleAndZoomControl(); - - initialLiveViews(); - - } - - - protected void initViewMap() { - - initialMapview(); - initialSportMapViews(); - - } - - protected void initialSportMapViews(){ - alpha = 50; - top_sptime = (TextView) vContainer.findViewById(R.id.tm_textView_top_sptime); - top_dist = (TextView) vContainer.findViewById(R.id.tm_textView_top_dist); - top_speed =(TextView) vContainer.findViewById(R.id.tm_textView_top_speed); -// popupText=(TextView) vContainer.findViewById(R.id.textcache); -// popupInfo = (View) vContainer.findViewById(R.id.popinfo); - wpNumText=(TextView) vContainer.findViewById(R.id.txt_custWpNum); - - btnAutoZoom=(ImageButton) vContainer.findViewById(R.id.tm_btnAutozoom); - btnAutoZoom.setVisibility(View.GONE); -// btnAutoZoom.setOnClickListener(ButtonOnClickListener); - - - btnRotation=(ImageButton) vContainer.findViewById(R.id.tm_btnRotaiton); - btnRotation.setOnClickListener(ButtonOnClickListener); - if(!isPlaying){ - btnLocation =(ImageButton) vContainer.findViewById(R.id.tm_btnLocaiton); - if(this.btnLocation!=null) btnLocation.setOnClickListener(ButtonOnClickListener); - } - btnKmpoints=(ImageButton) vContainer.findViewById(R.id.tbs_btnKMpoints); -// btnTurnPoints=(Button) vContainer.findViewById(R.id.tbs_btnTurnPoints); - btnSaveScreen=(ImageButton) vContainer.findViewById(R.id.tm_btnSaveScreen); - btnSataliteMap=(ImageButton) vContainer.findViewById(R.id.tm_btnSatalite);// - btnMapWayinstruction=(ImageButton) vContainer.findViewById(R.id.tbs_btnwayinstruction);// - btnMapWayinstruction.getBackground().setAlpha(alpha); - btnMapPicture=(ImageButton) vContainer.findViewById(R.id.tbs_btnpicture);// - btnMapPicture.getBackground().setAlpha(alpha); - btnMapLoadRoadbook =(ImageButton) vContainer.findViewById(R.id.map_btnLoadRoadbook); - btnMapLive =(ImageButton) vContainer.findViewById(R.id.map_btnLive); - btnMapLive.getBackground().setAlpha(alpha); - - btnLiveList = (ImageButton) vContainer.findViewById(R.id.map_btnSharelist); - btnLiveList.getBackground().setAlpha(alpha); - - btnMapLoadRoadbook.getBackground().setAlpha(alpha); - if(this.btnMapLive!=null){ - btnMapLive.setOnClickListener( ButtonOnClickListener); - btnMapLoadRoadbook.setOnClickListener( ButtonOnClickListener); - btnLiveList.setOnClickListener( ButtonOnClickListener); - } - - if(this.btnMapWayinstruction!=null){ - - btnMapWayinstruction.setOnClickListener( ButtonOnClickListener); - btnMapPicture.setOnClickListener( ButtonOnClickListener); - } - if(this.btnSaveScreen!=null){ -// btnSaveScreen.setVisibility(View.VISIBLE); - btnSaveScreen.setOnClickListener( ButtonOnClickListener); - } - if(this.btnSataliteMap!=null){ - btnSataliteMap.setOnClickListener( ButtonOnClickListener); - - } - - if(this.btnKmpoints!=null) - btnKmpoints.setOnClickListener( ButtonOnClickListener); -// if(this.btnTurnPoints!=null) -// btnTurnPoints.setOnClickListener( ButtonOnClickListener); - - // activity.app.getmBMapManager().start(); -// mMapView = (MapView) vContainer.findViewById(R.id.tm_bmapView); - -// gpKMpointsOverlay = new GraphicsOverlay(mMapView); - /* - gpTurnPointsOverlay =new GraphicsOverlay(mMapView); - - endOverlay=getItemizedOverlay(R.drawable.icon_send); - startOverlay=getItemizedOverlay(R.drawable.icon_sstart); - bearStartOverlay =getItemizedOverlay(R.drawable.icon_bstart); - bearEndOverlay =getItemizedOverlay(R.drawable.icon_bend); - gpxStartOverlay =getItemizedOverlay(R.drawable.icon_bstart); - gpxEndOverlay=getItemizedOverlay(R.drawable.icon_bend); - kmOverlay=getItemizedOverlay(R.drawable.icon_bend); - if( isPlayback){ - gpPlaybackOverlay = new GraphicsOverlay(mMapView); - mMapView.getOverlays().add(gpPlaybackOverlay); - } - - if( activity.app.isNaving){ - gpNaviOverlay = new GraphicsOverlay(mMapView); - mMapView.getOverlays().add(gpNaviOverlay); - } - - gpRecordingOverlay = new GraphicsOverlay(mMapView); - - - - mMapView.getOverlays().add(gpRecordingOverlay); - gpxOverlay =new GraphicsOverlay(mMapView); - mMapView.getOverlays().add(gpxOverlay);*/ - - - - - handler = new Handler(){ - @Override - public void handleMessage(Message msg) { - if(msg.what==1){ - btnMapWayinstruction.setVisibility(View.VISIBLE); - if(mTrack_bean.getType()==TrackType.GPX) - showWayinstructions(); - }else if(msg.what==0){ - btnMapPicture.setVisibility(View.VISIBLE); - } else if(msg.what==3){ - - } - }}; - - -// showMapPicture(); - - -// if(mTrack_bean.getType()==TrackType.GPX) -// showWayinstructions(); - } - /*PopupClickListener popMdListener2 = new PopupClickListener(){ - @Override - public void onClickedPopup(int index) { - - activity.showImagePagerFragment(index, mCurItem.getTitle().split(QiYouConstant.SPLITOR_KEY)); - - } - }; - */ - private void refreshScaleAndZoomControl(){ - //更新缩放按钮的状态 - -// QLog.getLogger().d(dTAG, String.format("...........map zoom level is %s", mMapView.getZoomLevel())); -// mZoomControlView.refreshZoomButtonStatus(Math.round(mMapView.getZoomLevel())); -// mScaleView.refreshScaleView(Math.round(mMapView.getZoomLevel())); - mZoomControlView.refreshZoomButtonStatus(Math.round(mBaiduMap.getMapStatus().zoom)); -// mScaleView.refreshScaleView(Math.round(mBaiduMap.getMapStatus().zoom)); - - } - /* - * load mksearch to find nearby pois - */ - void loadPOIs(){ - - } - - @Override - protected void saveScreen(){ - if(mMapView==null)return; -// mMapView.getMap().getCurrentMap(); - - mMapView.getMap().snapshot(new SnapshotReadyCallback() { - public void onSnapshotReady(Bitmap snapshot) { - onGetCurrentMap(snapshot) ; - } - }); - - btnSaveScreen.setEnabled(false); - Toast.makeText(activity, "正在截取当前地图...请稍候...", Toast.LENGTH_LONG ).show(); - } - - - void onGetCurrentMap(Bitmap b) { - /** - * 当调用过 mMapView.getCurrentMap()后,此回调会被触发 - * 可在此保存截图至存储设备 - */ - b= watermarkBitmap(b,null,QiYouConstant.MAP_PIC_WATER_MARK_WORDS); - String filePath =mTrack.getMediaPah(mediaType.MAP); - File PHOTO_DIR = new File(filePath); - - if(!PHOTO_DIR.exists()) PHOTO_DIR.mkdirs();// 创建文件夹 -// screenShotDist=screenShotDist<=0?System.currentTimeMillis():screenShotDist; - camPicName =filePath + String.format("%s.png", System.currentTimeMillis() ); - File file = new File(camPicName); - FileOutputStream out; - try{ - out = new FileOutputStream(file); - if(b.compress(Bitmap.CompressFormat.PNG, 70, out)) - { - out.flush(); - out.close(); - } - setMD(camPicName,System.currentTimeMillis(),mdWp,mediaType.MAP ); - -// Toast.makeText( activity, "屏幕截图成功,图片存在: "+file.toString(), Toast.LENGTH_SHORT).show(); - Toast.makeText( activity, "屏幕截图成功,您可以在足迹找到截图。", Toast.LENGTH_SHORT).show(); - /* if(btnSataliteMap!=null){ - btnSaveScreen.setWidth(btnSataliteMap.getWidth()); - btnSaveScreen.setHeight(btnSataliteMap.getHeight()); - }*/ - btnSaveScreen.setEnabled(true); - if(mTrack_bean.getType()==TrackType.GPX){ - - btnSaveScreen.setVisibility(View.GONE); - } - - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - } - - - int bearCnt=2; -// float lastLocAccuracy =0; - @Override - protected void updateMapView(Location location){ - - - -// QLog.getLogger().d(dTAG, String.format("%s, location has hasAltitude :%s,location provider is %s", TAG, hasA,location.getProvider())); - - - - - if(activity.app.isNetworkLocationRequestStarted && Utils.isLocOfBD(location) - || Utils.isLocOfRD(location)){ -// QLog.getLogger().d(dTAG, String.format("%s, BDloc service location." ,TAG)); - - locData = new MyLocationData.Builder() - .latitude( location.getLatitude() ) - .longitude(location.getLongitude()).build(); - - - - }else if(Utils.isLocOfGPS(location)){ - - locData = new MyLocationData.Builder() - .latitude( Utils.getbdLat(location.getLatitude(), location.getLongitude())) - .longitude(Utils.getbdLon(location.getLatitude(), location.getLongitude())) - .accuracy(location.getAccuracy()) - .direction(location.getBearing()) - .build(); - - }else - return; - - int limit=5; - limit=isPlaying?(QiYouConstant.MAX_GPS_SPAN/QiYouConstant.PLAYBACK_TIME_INTERVAL)*limit:limit; - limit=limit<3?3:limit; - limit=limit>10?10:limit; -// -// QLog.getLogger().d(dTAG, String.format("%s,%s limit----------------------------->:" ,TAG,limit)); - /*if(mTrack_bean==null || mTrack_bean.getType()!=TrackType.GPX){ - locData.accuracy = location.getAccuracy(); - locData.direction = location.getBearing(); - - }*/ - -// myLocationOverlay.setData(locData); - - if(canLocationMap ||activity.app.isLocationFinding){ - mBaiduMap.setMyLocationData(locData); - MapStatus.Builder builder = new MapStatus.Builder(); - builder.target(new LatLng(locData.latitude,locData.longitude));//.zoom(18.0f); - mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); - - if(location.hasBearing()&& bearCnt>= limit){ - if(canRotationMap){ - int ang = (int) (location.getBearing() > 180 ? location.getBearing() - 360:location.getBearing()); - - perfomRotate(ang); - } - - bearCnt=0; - }else{ //zoom span and animate to current location. - if(location.getSpeed()>0 ){ -// if(location.getSpeed()>0 || lastLocation!=null && lastLocation.getAccuracy()>=location.getAccuracy()){ - - bearCnt++; - - // - if( bearCnt>=4 && canAutoZoomMap){ - - if(location!=null && location.getSpeed()!=0) { - QLog.getLogger().d(dTAG, String.format("%s updateMapView zoomtospan:" ,TAG )); - zoomToSpan(location); - } - } - } - - } - - } - -// QLog.getLogger().d(dTAG, String.format("target lat%s,lng%s " ,locData.latitude,locData.longitude)); -// mapviewInitialized =true; - } - - - /** - * 处理旋转 旋转角范围: -180 ~ 180 , 单位:度 逆时针旋转 - */ - protected void perfomRotate(int rotateAngle ) { - - MapStatus ms = new MapStatus.Builder(mBaiduMap.getMapStatus()).rotate(rotateAngle).build(); - MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(ms); - mBaiduMap.animateMapStatus(u); - - } - - - - public void zoomToSpan(Location location) { - if (mBaiduMap == null) { - return; - } - LatLngBounds.Builder builder = new LatLngBounds.Builder(); - if(mTrack_bean!=null && mTrack_bean.getStartWp()!=null/* && mMapController!=null*/){ - - float nwLat = mTrack_bean.getStartWp().getWb().getLatitude(); - if(nwLat==0f)return; - float seLat =mTrack_bean.getMaxDistWp().getWb().getLatitude(); - if(seLat==0f)return; - float seLng = mTrack_bean.getMaxDistWp().getWb().getLongitude(); - if(seLng==0f)return; - float nwLng = mTrack_bean.getStartWp().getWb().getLongitude(); - if(nwLng==0f)return; - if(mTrack_bean.getLastWp().getWb().getLongitude()==0)return; - builder.include( this.getLatLng(mTrack_bean.getStartWp().getWb()) ) - .include( this.getLatLng(mTrack_bean.getMaxDistWp().getWb()) ) - .include( this.getLatLng(mTrack_bean.getLastWp().getWb()) ); - } - - - if(location!=null){ - float nwLat2 =(float) location.getLatitude(); - - float nwLng2 = mTrack_bean.getStartWp().getWb().getLongitude(); - if(nwLng2!=0f && nwLat2!=0f){ - builder.include( new LatLng(nwLat2,nwLng2 ) ); - } - } - - - mBaiduMap.setMapStatus(MapStatusUpdateFactory - .newLatLngBounds(builder.build())); - - - } - - - void initialMarkLayers(){ - - if(mBaiduMap==null)return; - - recordingOverlay= new TrackOverlay(mBaiduMap); - gpxOverlay= new TrackOverlay(mBaiduMap); - recordingEndOvelay= new TrackOverlay(mBaiduMap); - recordingStartOvelay= new TrackOverlay(mBaiduMap); - mRdOverlay = new RoadOverlay(mBaiduMap); - kmOverlay = new MdOverlay(mBaiduMap); - mPhotoOverlay = new MdOverlay(mBaiduMap); - - - } - - @Override - protected void updateGraphics(Location location, Boolean isOnPause){ - try{ -// QLog.getLogger().d(dTAG, TAG+ "................drawTrack............ :"+ "updateGraphics()" ); -// -// QLog.getLogger().dLog(dTAG, TAG+ " !isPlayback && drawTrack && !isDrawingTrack:" -// +(!isPlayback && canDrawTrack && !isDrawingTrack )); - - /*QLog.getLogger().dLog(dTAG,String.format("begin to draw track," + - "isPlaying: %s,isPlayback :%s, canDrawTrack:%s,isDrawingTrack:%s, isNaving: %s", - isPlaying, isPlayback , canDrawTrack,isDrawingTrack,activity.app.isNaving));*/ - - lastLocation = currentLocation==null?location:currentLocation; - - currentLocation= location; - - if(recordingOverlay==null){ - recordingOverlay= new TrackOverlay(mBaiduMap); - } - if(gpxOverlay==null){ - gpxOverlay= new TrackOverlay(mBaiduMap); - } - if(recordingEndOvelay==null){ - recordingEndOvelay= new TrackOverlay(mBaiduMap); - } - if(recordingStartOvelay==null){ - recordingStartOvelay= new TrackOverlay(mBaiduMap); - } - - - if(isPlaying && !isPlaybackTrackDrawed && !isDrawingTrack){ -// QLog.getLogger().dLog(TAG, "begin to draw track, draw playback track." ); -// gpPlaybackOverlay.removeAll(); - drawTrack(activity.app.getCurrentTrack().getTrackBean(),gpxOverlay,true); - - }else - if(!isPlaying && canDrawTrack && !isDrawingTrack) - { -// QLog.getLogger().dLog(dTAG,TAG+" begin to draw track updateGraphics(),to draw all the track." ); - // if(isPlayback) - // drawTrack(activity.app.currentTrack.getTrackBean(), gpPlaybackOverlay); - // else -// gpRecordingOverlay.removeAll(); - recordingOverlay.removeFromMap(); - drawTrack(mTrack_bean,/*gpRecordingOverlay,*/recordingOverlay,false); - - }else if(lastLocation!=null - && currentLocation !=null - && location!=null - && !isOnPause - && Utils.isLocOfGPS(currentLocation) - && Utils.isLocOfGPS(lastLocation) - ) { -// QLog.getLogger().dLog(TAG, "begin to draw track, drawShortLine()" ); - drawShortLine(); - -// if(lastLocation!=null &&lastLocation.getSpeed()==0) -// { -// drawNaviLine(); -// } - } - - drawNaviLine(); - - - }catch(NullPointerException er){ - QLog.getLogger().dLog( TAG," while draw graphic on the map, nullPoint Exception:" +er.getStackTrace()); - Utils.logStackTrace(er, dTAG); - }catch(Exception er){ - QLog.getLogger().dLog( TAG," while draw graphic on the map, Exception:" +er.getStackTrace()); - Utils.logStackTrace(er, dTAG); - } - - - - - } - - - /* - * draw a line between last location and current location - */ - public void drawShortLine(){ -// QLog.getLogger().d(dTAG,String.format("%s, currentlocation's provider: %s,lastLocation's provider%s", -// TAG,currentLocation.getProvider(),lastLocation.getProvider())); - - if( currentLocation==null ||currentLocation.distanceTo(lastLocation)>1000)return;//the distance between two wp should not far than 200 - - - - new Thread(){ - @Override - public void run() { -// LatLng[] linePoints = new LatLng[2]; - ArrayList points= new ArrayList (); - - if(currentLocation==null) return; - double mLat = Utils.getbdLat(currentLocation.getLatitude(),currentLocation.getLongitude()); - double mLon = Utils.getbdLon(currentLocation.getLatitude(),currentLocation.getLongitude()); -// int lat = (int) (mLat*1E6); -// int lon = (int) (mLon*1E6); -// linePoints[i-1] = new LatLng(lat, lon); -// linePoints[0] = new LatLng(lat, lon); - points.add( new LatLng(mLat, mLon)); - mLat = Utils.getbdLat(lastLocation.getLatitude(),lastLocation.getLongitude()); - mLon = Utils.getbdLon(lastLocation.getLatitude(),lastLocation.getLongitude()); -// lat = (int) (mLat*1E6); -// lon = (int) (mLon*1E6); -// linePoints[1] = new LatLng(lat, lon); - points.add( new LatLng(mLat, mLon)); -// QLog.getLogger().d(TAG,String.format("shortline from %d,%d to %d,%d", -// linePoints[0].getLatitudeE6(),linePoints[0].getLongitudeE6() -// ,linePoints[1].getLatitudeE6(),linePoints[1].getLongitudeE6())); -// gpRecordingOverlay.setData(drawLine(linePoints,false)); - /* if(isPlaying){ -// gpPlaybackverlay.setData(drawColorsShortLine(currentLocation.getSpeed(),points)); -// mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points)); - mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline); - shortLines.add((Polyline)mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points)) ); - } - else{ -// gpRecordingOverlay.setData(drawColorsShortLine(currentLocation.getSpeed(),points)); - mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points)); - } - */ - - - if(currentLocation==null || currentLocation.getSpeed()==0){ - QLog.getLogger().dLog(dTAG, TAG+" drawShortLine --> draw track end icon"); - - setEndIcon(/*linePoints[0]*/points.get(0)); - - - }else{ - - if(recordingEndOvelay !=null) { - recordingEndOvelay.removeFromMap(); - } - - } - - shortLines.add((Polyline)mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points)) ); - - }}.start(); - - } - - - public void drawNaviLine(){ -// QLog.getLogger().d(dTAG,String.format("%s, currentlocation's provider: %s,lastLocation's provider%s", -// TAG,currentLocation.getProvider(),lastLocation.getProvider())); -// if(currentLocation ==null || !currentLocation.hasSpeed() || !currentLocation.getProvider().equalsIgnoreCase(LocationManager.GPS_PROVIDER))return; -// if(lastLocation ==null || !currentLocation.hasSpeed() || !lastLocation.getProvider().equalsIgnoreCase(LocationManager.GPS_PROVIDER))return; -// if(currentLocation==null || lastLocation==null ) return; - // QLog.getLogger().d(dTAG,"activity.app.playBack||activity.app.isNaving: "+(activity.app.playBack||activity.app.isNaving)); -// if( !(activity.app.playBack||activity.app.isNaving) )return; - - if( activity.app.naviTrackId<0 ||activity.app.playBack||!activity.app.isNaving)return; - - - - if( Utils.isLocOfGPS(currentLocation) ) - new Thread(){ - @Override - public void run() { - - Track tr =activity.app.getTrackCache().get(Integer.valueOf(activity.app.naviTrackId)); - - if( tr==null ||tr.getTrackBean().getLastWp().getWb().getLatitude()==0)return; - - LatLng[] linePoints = new LatLng[2]; - if(currentLocation==null) return; - double mLat = Utils.getbdLat(currentLocation.getLatitude(),currentLocation.getLongitude()); - double mLon = Utils.getbdLon(currentLocation.getLatitude(),currentLocation.getLongitude()); - int lat = (int) (mLat*1E6); - int lon = (int) (mLon*1E6); -// linePoints[i-1] = new LatLng(lat, lon); - linePoints[0] = new LatLng(lat, lon); - -// mLat = Utils.getbdLat(lastLocation.getLatitude(),lastLocation.getLongitude()); -// mLon = Utils.getbdLon(lastLocation.getLatitude(),lastLocation.getLongitude()); -// lat = (int) (mLat*1E6); -// lon = (int) (mLon*1E6); -// linePoints[1] = new LatLng(lat, lon); - linePoints[1] =getLatLng(tr.getTrackBean().getLastWp().getWb()); - -// QLog.getLogger().d(TAG,String.format("shortline from %d,%d to %d,%d", - - try{ - mBaiduMap.addOverlay(drawNaviLine(linePoints)); - - }catch(Exception e){ - QLog.getLogger().d(dTAG,e.getMessage()); - } - }}.start(); - - } - - public /*Graphic*/ PolylineOptions drawNaviLine(LatLng[] linePoints) - { -// QLog.getLogger().d(dTAG, TAG+" begin draw the tracke line: drawLine start."); - //构建线 - /* Geometry lineGeometry = new Geometry(); - lineGeometry.setPolyLine(linePoints); - //设定样式 - Symbol lineSymbol = new Symbol(); - Symbol.Color lineColor = lineSymbol.new Color(); -// if(isPlayback &&drawTrack){ //draw playback track - int tsize =1; - - { - lineColor.red = 200; - lineColor.green = 0; - lineColor.blue = 0; - lineColor.alpha =70; - - } - lineSymbol.setLineSymbol(lineColor, tsize); - //生成Graphic对象 - Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol); -// QLog.getLogger().d(dTAG, TAG+" end draw the tracke line: drawLine end."); - return lineGraphic; - */ - ArrayList ps= new ArrayList (); - ps.add(linePoints[0]); - ps.add(linePoints[1]); - int tsize =1; - - PolylineOptions ooPolyline = new PolylineOptions().width(tsize) - .points(ps).color(Color.argb(70, 200, 0, 0)).dottedLine(true) ; - - return ooPolyline; - } - - - - public void drawTrack( final Track_bean tb ,/* final GraphicsOverlay graphicsOverlay,*/ final TrackOverlay trackOverly, final Boolean isDrawAsistTrack ) - { - QLog.getLogger().dLog(dTAG,TAG+" begin to draw track "+ tb.getTrackId()+ ",isDrawAsistTrack ? " + isDrawAsistTrack); - - if(tb==null|| tb.getTrkseg().size()==0|| tb.getLastWp() ==null || tb.getLastWp().getWb()==null - ||tb.getStartWp() ==null||tb.getStartWp().getWb() ==null -// ||graphicsOverlay==null - ||!isAdded()) return; - - removeShortLines(); - -// isDrawingTrack =true; -// QLog.getLogger().dLog(dTAG,TAG+" begin to draw track "+ tb.getTrackId()+ ",isDrawAsistTrack ? " + isDrawAsistTrack); - - LatLng startPt =getLatLng(tb.getStartWp().getWb());//new LatLng(lat, lon); - - // QLog.getLogger().d(dTAG, " calculate lat lon of track startIcon............................"); - // QLog.getLogger().d(dTAG, " lat is: "+tb.getStartWp().getWb().getLatitude() +", lon is: "+tb.getStartWp().getWb().getLongitude()); - - - if(isDrawAsistTrack){ - trackOverly.getOverlayOptions().add(setGeoIcon(startPt,R.drawable.icon_bstart)); - }else{ -// trackOverly.getOverlayOptions().add(setStartIcon(startPt)); - this.setStartIcon(startPt); - } - - - //draw line for the whole track - new Thread(){ - @Override - public void run() { - - if(isDrawingTrack){ - QLog.getLogger().d(dTAG, String.format("new thread to draw track....isDrawingTrack? %s",isDrawingTrack)); - return; - }else{ - isDrawingTrack =true; - } - - ArrayList al =tb.getTrkseg(); - if(al.size()<=2) { - isDrawingTrack=false; - return; - } - ArrayList gpal= new ArrayList(); - long lastTime =0; -// float colorFactor=0; - LatLng gp = null ; -// Waypoint_bean lastWb=null; -// LatLng lastGp=null; - float dist=0f; - final int colorCnt=2+(int)(tb.getDistance()/20000);//each 20 km add 1 more gp for color track. - long time=0; - int kmDist=(int)(tb.getDistance()/1000/50);//show 10 dist overlay item for a track. - kmDist=kmDist>0?kmDist:1; - kmDist=kmDist>1?kmDist:1; -// kmDist=1; - ArrayList kmgp= new ArrayList(); - float nextKm=0f; - int lastKm=0; - boolean hasKmflag=false; - boolean islushu = tb.getCreator()!=null &&tb.getCreator().startsWith("爱骑驴路书"); - - try{ - synchronized(al) { - //draw points in cache - if(tb.getStatus()==TrackStatus.RECORDING - && activity.app.getRecordingTrack().getTrackBean().getTrackId() ==tb.getTrackId() - && activity.app.getRecordingTrack().getTrackBean().getStartTime() ==tb.getStartTime() - ){ - Location loc; - Waypoint_bean wb; - for (int i = 0; i <= activity.app.getLocationCached().size()-1; i++) { - loc = activity.app.getLocationCached().get(i); - if(loc==null)continue; - wb =new Waypoint_bean(); - wb.setLatitude((float) loc.getLatitude()); - wb.setLongitude((float) loc.getLongitude()); - wb.setSpeed(loc.getSpeed()* 3.6f); - wb.setTime(loc.getTime()); - if(loc.getExtras().containsKey("dist")){ - wb.setDistance((float) loc.getExtras().getDouble("dist")); - } - al.add(wb); - } - - } - - for(Waypoint_bean wb:al){ //java.util.ConcurrentModificationException @Synchronized// there is lock conflict with playback service. use clone and resolve. - - if(wb ==null ||wb.getLatitude()==0 ||wb.getLongitude()==0)continue; - if(wb.getTime()0){ - gpKMpointsOverlay.setData(drawKMPoint(gp)); - - } */ - - if(!hasKmflag &&wb.getKmflag()>0){ - hasKmflag=true; - } - if((int)(wb.getKmflag()/kmDist)>lastKm ||!hasKmflag && (int) (wb.getSumDist()/1000/kmDist)>lastKm){ - lastKm++; - kmgp.add(gp); - } - - nextKm+=wb.getDistance()/1000; - if(kmDist>0&& nextKm>=kmDist){ - // kmgp.add(gp); - nextKm=0; - } - if(lastTime ==0|| wb.getTime() -lastTime <= QiYouConstant.TIME_FOR_LIGHT_LINE) - gpal.add(gp); - - if(lastTime >0 && wb.getTime() -lastTime > QiYouConstant.TIME_FOR_LIGHT_LINE){ - if(gpal.size()>0 && ( isDrawAsistTrack ||islushu )){ - - mBaiduMap.addOverlay(drawLine( gpal ,isDrawAsistTrack ||islushu)); -// trackOverly.getPolylineOptions().add(drawLine( gpal ,isDrawAsistTrack)) ; - gpal.clear(); - } else{ - - mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000, gpal)); -// trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000, gpal)); - if( gpal.size()>=2 ||al.indexOf(wb)==al.size()-1){ - if(al.indexOf(wb)==al.size()-1) - gpal.add(gp); - - mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000, gpal)); -// trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000, gpal)); - } - if( gpal.size()>0 ){ - LatLng[] gps= { gpal.get(gpal.size()-1),gp}; - - mBaiduMap.addOverlay(drawNaviLine(gps)); -// trackOverly.getPolylineOptions().add(drawNaviLine(gps)); - } - - gpal.clear(); - dist=0; - time=0; - } - // gpal.clear(); - gpal.add(gp); - - - } else if(isDrawAsistTrack ||islushu){ - gpal.add(gp); - } - else if(lastTime>0){ - // gpal.add(gp); - dist +=wb.getDistance(); - time +=wb.getTime()-lastTime; - - if(gpal.size()>colorCnt ||al.indexOf(wb)==al.size()-1){ - - // gpal.toArray(new LatLng[2] ); - mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000, gpal )); -// trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000, gpal )); - gpal.clear(); - gpal.add(gp); - dist=0; - time=0; - } - } - - lastTime =wb.getTime(); - - - } - } - if((isDrawAsistTrack ||islushu) && gpal.size()>0 ){ - mBaiduMap.addOverlay(drawLine( gpal,isDrawAsistTrack ||islushu)); -// trackOverly.getPolylineOptions().add(drawLine( gpal,isDrawAsistTrack)); - - } - else if(gpal.size()>0){ - mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000, gpal )); -// trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000, gpal )); - } - - QLog.getLogger().d(dTAG,TAG+" Draw track finished, it is isDrawAsistTrack track? " + isDrawAsistTrack); - - if(gp!=null){ - if(isDrawAsistTrack){ - trackOverly.getOverlayOptions().add(setGeoIcon(gp,R.drawable.icon_bend)); - }else{ - setEndIcon(gp); - } - } - - if(!isDrawAsistTrack) { - QLog.getLogger().d(dTAG, String.format(" set candrawtrack %s", false)); - - canDrawTrack=false; - - } else{ - - isPlaybackTrackDrawed =true; - - } - - - - showPicsOnMap(tb); - -// if( tb.getStatus()!=TrackStatus.RECORDING || tb.getType()==TrackType.COPY){ -// showRoutePointsOnMap(tb); -// } - showRoutePointsOnMap(tb); - showKMonMap(kmgp,kmDist); - -// QLog.getLogger().dLog(dTAG, " drawing track done, id is "+tb.getTrackId()+",track status is "+tb.getStatus()); - - - isDrawingTrack =false; - - trackOverly.addToMap(); //for gpx - /* QLog.getLogger().dLog(dTAG, String.format(" drawing track done, id is %s," + - "trackOverly.getOverlayOptions().size() %s, trackOverly.getOverlayMarkers().size() %s \n" + - ", trackOverly.getOverlayOptions().size() %s , trackOverly.getOverlayOptions().size() %s" , - tb.getTrackId(), trackOverly.getPolylineOptions().size(),trackOverly.getShortLines().size() - ,trackOverly.getPolylineOptions().size(),trackOverly.getShortLines().size() - )); */ - - - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - isDrawingTrack =false; - QLog.getLogger().dLog(dTAG, " draw track throws exception...... "); - - } finally{ - isDrawingTrack =false; - } - //finished the track line, set the flag to true; - - }}.start(); - - /* if(!isDrawAsistTrack) { - QLog.getLogger().d(dTAG, String.format(" set candrawtrack %s", false)); - - canDrawTrack=false; - - } else{ - - isPlaybackTrackDrawed =true; - - }*/ - - - - } - private /*Graphic*/ PolylineOptions drawColorsShortLine(float speed, ArrayList linePoints) { - - /* - Geometry lineGeometry = new Geometry(); -// LatLng[] linePoints = { fg,tg}; - - lineGeometry.setPolyLine(linePoints); - //设定样式 - Symbol lineSymbol = new Symbol(); - Symbol.Color lineColor = lineSymbol.new Color(); -// if(isPlayback &&drawTrack){ //draw playback track - int tsize =4; - - float factor =mTrack_bean.getAvs()/speed; - int red = 200; - int green= 200; - red =(int) (factor==0?0:(red -factor*40)); -// green =(int) (factor==0?255:(factor*100)); - red=red<0?0:red; - green=255-red; - float avs =activity.app.playBack?activity.app.getCurrentTrack().getTrackBean().getAvs():mTrack_bean.getAvs(); - float factor =avs==0?0:(speed/(avs/3.6f)); - int green = (int) (150 -30*factor); - green=green>0?green:0; - int red = (int) (180*factor); - red=red>255?255:red; - - lineColor.red = red; - lineColor.green = green; - lineColor.blue = 255; - lineColor.alpha = 255; - - - lineSymbol.setLineSymbol(lineColor, tsize); - //生成Graphic对象 - Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol); -// QLog.getLogger().d(dTAG, TAG+String.format(" speed %s, avs %s, factor:%s, red %s, green %s",speed,mTrack_bean.getAvs()/3.6f, factor,red,green)); - return lineGraphic; */ - - - float avs =activity.app.playBack?activity.app.getCurrentTrack().getTrackBean().getAvs():mTrack_bean.getAvs(); - float factor =avs==0?0:(speed/(avs/3.6f)); - int green = (int) (150 -30*factor); - green=green>0?green:0; - int red = (int) (180*factor); - red=red>255?255:red; - - - PolylineOptions ooPolyline =null; - int tsize =activity.app.playBack?6:8; - tsize = tsize *2; - if(linePoints.size()>1) { - ooPolyline = new PolylineOptions().width(tsize) - .points(linePoints).color(Color.argb(255, red, green, 255)) ; - } -// QLog.getLogger().d(dTAG, TAG+String.format(" linePoints.size() %s" ,linePoints.size())); - return ooPolyline; - - } - protected void zoomToSpan(){ - - if( mTrack_bean==null || mTrack_bean.getRoadWps()==null || mTrack_bean.getRoadWps().isEmpty())return; - -// if(!canAutoZoomMap)return; - -// if( activity.app.getRecordingTrack().getTrackBean().getTrackId() ==mTrack_bean.getTrackId() &&mTrack_bean.getStatus()==TrackStatus.RECORDING )return; - - double nwLat = -90 * 1000000; - double nwLng = 180 * 1000000; - double seLat = 90 * 1000000; - double seLng = -180 * 1000000; - // find bounding lats and lngs - LatLng point; - for(Waypoint_bean wb:mTrack_bean.getRoadWps()){ -// for (LatLng point : points) { - if(wb==null)continue; - point=getLatLng(wb); - nwLat = Math.max(nwLat, point.latitude); - nwLng = Math.min(nwLng, point.longitude ); - seLat = Math.min(seLat, point.latitude); - seLng = Math.max(seLng, point.longitude ); - } - LatLngBounds.Builder builder = new LatLngBounds.Builder(); - - builder.include( new LatLng(nwLat,nwLng) ); - builder.include( new LatLng(seLat,seLng) ); - - mBaiduMap.setMapStatus(MapStatusUpdateFactory - .newLatLngBounds(builder.build())); - - -} - - protected LatLng[] getGPs( ArrayList D ){ - - return D.toArray(new LatLng[1]); - - } - - - - - public /*Graphic*/ PolylineOptions drawLine(List linePoints,Boolean isDrawAsistTrack) - { -// QLog.getLogger().d(dTAG, TAG+" begin draw the tracke line: drawLine start."); - //构建线 - /* Geometry lineGeometry = new Geometry(); - lineGeometry.setPolyLine(linePoints); - //设定样式 - Symbol lineSymbol = new Symbol(); - Symbol.Color lineColor = lineSymbol.new Color(); -// if(isPlayback &&drawTrack){ //draw playback track - int tsize =activity.app.playBack?2:4; - if( isDrawAsistTrack){ - lineColor.red = 0; - lineColor.green = 255; - lineColor.blue = 0; - lineColor.alpha = 255; -// tsize=2; - }else //draw current Track - { - lineColor.red = 255; - lineColor.green = 0; - lineColor.blue = 0; - lineColor.alpha = 255; - - } - lineSymbol.setLineSymbol(lineColor, tsize); - */ - -// Color color =new Color(Color.GREEN); - - if(linePoints==null || linePoints.size()<2){ - return null; - } - - int tsize =activity.app.playBack?4:8; - tsize = tsize *2; - PolylineOptions ooPolyline = new PolylineOptions().width(tsize) - .points(linePoints).color(isDrawAsistTrack?Color.GREEN:Color.RED) ; - - return ooPolyline; - - - } - - - - - /** - * km point - * @return 点对象 - */ - public /*Graphic*/ DotOptions drawFootPoint(GPItem gp ,int mAlpha){ - - if(gp==null )return null; - - LatLng gpt = Utils.getLatLng(gp.getLat(),gp.getLng()); - - if( gpt==null)return null; - -// Geometry pointGeometry = new Geometry(); - - - int cnt=gp.getCnt(); - int size= 10+cnt/5 ; -// int alpha=mAlpha>0?mAlpha:(100-cnt*2); - - - size=size>30?30:size; - int alpha=mAlpha>0?mAlpha:(100-3*size); - alpha=alpha<10?10:alpha; - - //pink - int red=250 ; - int green=150; - int blue=250; - - green=green-cnt*5; - green=green<0?0:green; - -// QLog.getLogger().d(dTAG, String.format("cnt: %s rgb:%s,%s,%s alpha:%s",cnt,red,green,blue,alpha)); - - //设置坐标 -// pointGeometry.setPoint(gp.getGp(), size); - -// pointGeometry.setPoint(gpt , size); - - -/* OverlayOptions ooDot = new DotOptions().center(gpt).radius(size) - .color(0xFF0000FF); - - symbol pointSymbol = new Symbol(); - Symbol.Color pointColor = pointSymbol.new Color(); - pointColor.red = red; - pointColor.green = green; - pointColor.blue = blue; - pointColor.alpha = alpha; - pointSymbol.setPointSymbol(pointColor); - Graphic pointGraphic = new Graphic(pointGeometry, pointSymbol); - return pointGraphic;*/ - size= 20+cnt ; - size=size>30?30:size; - - float zoom = mBaiduMap.getMapStatus().zoom; - - size = (int)(zoom/18f)*size; - - mAlpha =(int)( (cnt/4+0.5)*mAlpha); - mAlpha =mAlpha>255?255:mAlpha; - - - - return new DotOptions().center(gpt).radius(size ) - .color(Color.argb(mAlpha, red, green, blue)); - } - - - public Bitmap getBitmapFromView(View view) { - //Define a bitmap with the same size as the view - Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888); - return returnedBitmap; - - } - - - - /** - * remove existed drawed shortlines - */ - void removeShortLines(){ - for(Polyline pl :shortLines){ - pl.remove(); - } - } - - protected void setStartIcon(LatLng gp){ - - // QLog.getLogger().d(dTAG, " to draw track startIcon............................"); - // QLog.getLogger().d(dTAG, " gp.lat is: "+gp.getLatitudeE6() +", gp.lon is: "+gp.getLongitudeE6()); - -// setGeoIcon(gp,startOverlay); - -// setGeoIcon(gp,startOverlay,R.drawable.icon_sstart); - recordingStartOvelay.getOverlayOptions().add( setGeoIcon(gp,R.drawable.icon_sstart )); - recordingStartOvelay.addToMap(); - - } - - protected void setEndIcon(LatLng gp){ - -// if(mTrack_bean.getDistance()==0)return; -// setGeoIcon(gp,endOverlay,R.drawable.icon_send); - - recordingEndOvelay.getOverlayOptions().clear(); //endpoint is only one. - recordingEndOvelay.getOverlayOptions().add( setGeoIcon(gp,R.drawable.icon_send ) ); - recordingEndOvelay.addToMap(); - -// return setGeoIcon(gp,R.drawable.icon_send ); - } - - protected void removeMark(Marker mark){ - if(mark!=null){ - mark.remove(); - } - } - - protected void setGeoIcon(LatLng gp, Marker mark,int resid){ - removeMark(mark); - setGeoIcon(gp,mark,resid,true); - } - - protected MarkerOptions setGeoIcon(LatLng gp, int resid ){ - return new MarkerOptions().position(gp).icon(BitmapDescriptorFactory - .fromResource(resid) ); - } - - protected void setGeoIcon(LatLng gp,/*ItemizedOverlay*/ Marker mark,int resid,Boolean isClean){ - - MarkerOptions ooB = new MarkerOptions().position(gp).icon(BitmapDescriptorFactory - .fromResource(resid) ) /*.zIndex(5)*/; - - mark = (Marker) (mBaiduMap.addOverlay(ooB)); - - - -// markerOptions.position(gp); -// .zIndex(9) -// .draggable(true); - -// (Marker) (mBaiduMap.addOverlay(markerOptions.position(gp))); -// mBaiduMap. markerOptions.position(gp) -// mBaiduMap.addOverlay(markerOptions.position(gp)); - - - - - } - - - - - ArrayList getGpxTracks(){ - ArrayList ids; - if(activity.app.naviTrackId>0 &&activity.app.isNaving){ - ids =new ArrayList(); - ids.add(activity.app.naviTrackId); - }else{ - - ids =activity.app.getGpxShowingTracks(); - } - return ids; - } - - ArrayList gpxDrawd ;//= new ArrayList(); - protected void drawGpx(){ - - new Thread(){ - - @Override - public void run() { - - - ArrayList ids =getGpxTracks(); - - - for(int id:ids){ - QLog.getLogger().d(dTAG, " begin to draw track, "+" check if gpx id is drawed or not: " +id); - - if(gpxDrawd.contains(Integer.valueOf(id))) { - continue; - }else{ - } - - if(mTrack_bean!=null && id==mTrack_bean.getTrackId()) continue; -// if( id==mTrack_bean.getTrackId()) continue; - Track tr = activity.app.getCurrentTrack().getTrackBean().getTrackId() ==id? - activity.app.getCurrentTrack() - :activity.app.getTrackCache().get(Integer.valueOf(id)); - if(tr==null)continue; - - while( isDrawingTrack ){ - // - try { - Thread.sleep(100); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - QLog.getLogger().d(dTAG, " begin to draw track, "+" to draw gpx id is: " +id); - - if(gpxOverlay==null){ - gpxOverlay= new TrackOverlay(mBaiduMap); - } - drawTrack( tr.getTrackBean(),gpxOverlay ,true); - - gpxDrawd.add(id); - } - - //向handler发消息 -// handler.sendEmptyMessage(0); - }}.start(); - - } - - - - - protected LatLng getLatLng(Waypoint_bean wb){ - return Utils.getLatLng(wb.getLatitude(), wb.getLongitude()); - } - - - - protected Waypoint_bean getWb(LatLng pt){ -// double mLat = Utils.getggLat(pt.getLatitudeE6()/1e6, pt.getLongitudeE6()/1e6 ); -// double mLon = Utils.getggLon(pt.getLatitudeE6()/1e6, pt.getLongitudeE6()/1e6); - double mLat = Utils.getggLat(pt.latitude, pt.longitude ); - double mLon = Utils.getggLon(pt.latitude, pt.longitude ); - Waypoint_bean wb = new Waypoint_bean(); - wb.setLatitude((float) mLat); - wb.setLongitude((float) mLon); - return wb; - } - - - void showPicsOnMap(Track_bean mTrack_bean){ -// btnMapPicture.setVisibility(View.GONE); - if(mTrack_bean.getMdWps().size()==0)return; - if(IL==null)IL = new com.qiyou.mb.android.utils.ImageLoader(activity); - try{ - LatLng lastGp = null; -// ArrayList Urls=new ArrayList(); - String Urlstr =""; -// List items =new ArrayList(); -// List markers =new ArrayList(); - List markerOs = new ArrayList(); - ArrayList medias = new ArrayList(); - LatLng gp = null; - LatLng newGp=null; - picUrlMap =new HashMap(); - for(Waypoint_bean mwb:mTrack_bean.getMdWps()){ - // if(wb!=null && wb.getTime()>=start && wb.getTime()<=end){ - - if(mwb!=null ){ - gp = getLatLng(mwb); - newGp=gp; -// Urls.add(md.getUri()); - if(lastGp==null)lastGp=gp; - -// if(lastGp!=null){ - - if(gp.latitude==lastGp.latitude - && gp.longitude ==lastGp.longitude -// - ){ -// medias.addAll(mwb.getMedias());// - - for(Media md: mwb.getMedias()){ - - if(md.getType()==mediaType.PIC ){ -// - QLog.getLogger().d(dTAG,TAG+" "+ "same location: to add new pic to urls: " +mTrack.getValidMdUrl(md,false)); -// Urls.add(md.getUri()); - medias.add(md); - String url =mTrack.getValidMdUrl(md,false); - if(!TextUtils.isEmpty(url)){ - picUrlMap.put(url, mTrack.getValidMdUrl(md,true)); - Urlstr+=url+QiYouConstant.SPLITOR;//取原图 - } - } - } - lastGp=gp; - continue; - } - else{ - //get mds from cache to OverlayItem list . - int i=0; - for(Media md: medias){ -// newGp=new LatLng(lastGp.latitudeE6+50*(i++),lastGp.getLongitudeE6()+50*i); - newGp=new LatLng(lastGp.latitude ,lastGp.longitude); - - Bundle bd = new Bundle(); - bd.putInt("index", 1 ); - bd.putString("urls", Urlstr ); - MarkerOptions ooA = new MarkerOptions().position(newGp).anchor( 5*(i++), 10*i) - .extraInfo(bd) - .icon( - BitmapDescriptorFactory.fromBitmap( - IL.getBitmap(mTrack.getValidMdUrl(md,true), QiYouConstant.MAP_PIC_SIZE))) - /*.zIndex(9)*/.draggable(true); - markerOs.add(ooA); -// Marker mark = (Marker) (mBaiduMap.addOverlay(ooA)); -// markers.add(mark); - - /* -// OverlayItem item = new OverlayItem(newGp,Urlstr,md.getComment()); - try{ - item.setMarker(new BitmapDrawable(IL.getBitmap(mTrack.getValidMdUrl(md,true), QiYouConstant.MAP_PIC_SIZE))); //取缩略图 - }catch(IllegalStateException e){ - Utils.logStackTrace(e,dTAG); - continue; - } - items.add(item); */ - } - -// Urls =new ArrayList(); - Urlstr=""; - medias = new ArrayList(); - - //add current md to cache -// medias.addAll(mwb.getMedias());// - for(Media md: mwb.getMedias()){ - if(md.getType()==mediaType.PIC){ - QLog.getLogger().d(dTAG,TAG+" "+ " 1 to add new pic to urls: " +mTrack.getValidMdUrl(md,false)); -// Urls.add(md.getUri()); - medias.add(md); - String url =mTrack.getValidMdUrl(md,false); - if(!TextUtils.isEmpty(url)){ - picUrlMap.put(url, mTrack.getValidMdUrl(md,true)); - Urlstr+=url+QiYouConstant.SPLITOR;//取原图 - } - - } - } - - } - - lastGp=gp; - - -// } - } - - } - //get mds from cach to OverlayItem list . - int i=0; - for(Media md: medias){ - Bitmap b =IL.getBitmap(mTrack.getValidMdUrl(md,true),QiYouConstant.MAP_PIC_SIZE); - if(b==null)continue; - /* newGp=new LatLng(lastGp.getLatitudeE6()+50*(i++),lastGp.getLongitudeE6()+50*i); - OverlayItem item = new OverlayItem(newGp,Urlstr,md.getComment()); - item.setMarker(new BitmapDrawable(b)); - items.add(item); */ - - newGp=new LatLng(lastGp.latitude ,lastGp.longitude); - - Bundle bd = new Bundle(); - bd.putInt("index", 1 ); - bd.putString("urls", Urlstr ); - MarkerOptions ooA = new MarkerOptions().position(newGp).anchor( 5*(i++), 10*i) - .extraInfo(bd) - .icon( - BitmapDescriptorFactory.fromBitmap( - IL.getBitmap(mTrack.getValidMdUrl(md,true), QiYouConstant.MAP_PIC_SIZE))) - /*.zIndex(9)*/.draggable(true); - markerOs.add(ooA); -// Marker mark = (Marker) (mBaiduMap.addOverlay(ooA)); -// markers.add(mark); - - } - if(markerOs.isEmpty()) return; - - - - if(mPhotoOverlay==null){ - mPhotoOverlay = new MdOverlay (mBaiduMap); - QLog.getLogger().dLog(dTAG,TAG+" initial mPhotoOverlay ..................."); - } - QLog.getLogger().dLog(dTAG,TAG+" before add, mPhotoOverlay.getOverlayOptions().size " + mPhotoOverlay.getOverlayOptions().size()); - mPhotoOverlay.getOverlayOptions().clear(); - mPhotoOverlay.getOverlayOptions().addAll(markerOs); - mPhotoOverlay.addToMap(); - if(handler!=null) handler.sendEmptyMessage(0); - QLog.getLogger().dLog(dTAG,TAG+" after add, mPhotoOverlay.getOverlayOptions().size " + mPhotoOverlay.getOverlayOptions().size()); - - - - }catch(Exception er){ - Utils.logStackTrace(er, dTAG); - } - } - - - - class RoadOverlay extends MdOverlay{ - - public RoadOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - public static final String EXTR_KEY ="INFO"; - public static final String EXTR_KEY_NAME ="NAME"; - public static final String EXTR_KEY_INDEX ="INDEX"; - public static final String EXTR_KEY_FLAG ="FLAG"; - @Override - public boolean onMarkerClick(Marker marker) { - OnInfoWindowClickListener listener = null; - QLog.getLogger().d(dTAG,TAG+" pic icon on tap ..................to show road info window"); - for (Overlay mMarker : mOverlayList) { - if (mMarker instanceof Marker && mMarker.equals(marker)) { - - if (marker.getExtraInfo() != null) { - - isShowingPicMark =false; - return showInfoWindow( marker.getPosition(),marker.getExtraInfo().getString(EXTR_KEY),marker.getPosition()); -// - /* popupText.setText(marker.getExtraInfo().getString(EXTR_KEY)); - - if(TextUtils.isEmpty(popupText.getText()))return true; - Bitmap[] bitMaps={ - BMapUtil.getBitmapFromView(popupInfo) - }; - - listener = new OnInfoWindowClickListener() { - public void onInfoWindowClick() { - // - mBaiduMap.hideInfoWindow(); - } - - }; - - LatLng ll = marker.getPosition() ; - mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromBitmap(bitMaps[0]), ll, -47, listener); - mBaiduMap.showInfoWindow(mInfoWindow); */ - - } - return true; - } - - } - return false; - - } - - } - - - - boolean showInfoWindow(LatLng ll ,String text,LatLng center){ - if(popupText==null){ - return false; - } - popupText.setText(text); - OnInfoWindowClickListener listener = null; - if(TextUtils.isEmpty(popupText.getText()))return false; - Bitmap[] bitMaps={ - BMapUtil.getBitmapFromView(popupInfo) - }; - - listener = new OnInfoWindowClickListener() { - public void onInfoWindowClick() { -// - mBaiduMap.hideInfoWindow(); - } - - }; - - if(center!=null){ - locateBaiduMapCenter( center.latitude,center.longitude); - } - mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromBitmap(bitMaps[0]), ll, -47, listener); - mBaiduMap.showInfoWindow(mInfoWindow); - return true; - } - - class LineOverlay extends OverlayManager{ - -// private List latlngs = new ArrayList(); - private List overlayList = new ArrayList(); - public LineOverlay(BaiduMap baiduMap) { - super(baiduMap); - // TODO Auto-generated constructor stub - } - - @Override - public boolean onMarkerClick(Marker arg0) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean onPolylineClick(Polyline arg0) { - // TODO Auto-generated method stub - return false; - } - - /*public void setLatLngs(List lls){ - latlngs =lls; - }*/ - - - @Override - public List getOverlayOptions() { - - /*List overlayList = new ArrayList(); - - overlayList.add(new PolylineOptions().points(latlngs).width(10) - .color( Color.argb(178, 0, 78, 255)).zIndex(0)); - */ - return overlayList; - } - - public void setOverlayList(List overlayList) { - this.overlayList = overlayList; - } - - } - - class TrackOverlay extends MdOverlay{ -// private List mPolylineOptionLists; -// private List mShortLines =new ArrayList(); - public TrackOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - - - @Override - public boolean onMarkerClick(Marker marker) { - return false; - } - - @Override - public List getOverlayOptions() { - // TODO Auto-generated method stub - if (mOverlayOptionList == null) { - mOverlayOptionList = new ArrayList(); - } - return mOverlayOptionList; - } - - - - /* public List getPolylineOptions() { - if (mPolylineOptionLists == null) { - mPolylineOptionLists = new ArrayList(); - } - return mPolylineOptionLists; - } - - - - *//** - * 将所有Overlay 从 地图上消除 - *//* - public void removeLinesFromMap() { - if (mBaiduMap == null) { - return; - } - for (Polyline line : mShortLines) { - line.remove(); - } - - mShortLines.clear(); - - } - - - public List getShortLines() { - return mShortLines; - }*/ - - - } - - boolean isShowingPicMark=false; - - class MdOverlay extends OverlayManager{ - protected List mOverlayOptionList; - public MdOverlay(BaiduMap baiduMap) { - super(baiduMap); - } - void init(){ - - } - @Override - public boolean onMarkerClick(Marker marker) { - OnInfoWindowClickListener listener = null; - QLog.getLogger().d(dTAG,TAG+" pic icon on tap ..................to show popMd"); - for (Overlay mMarker : mOverlayList) { - if (mMarker instanceof Marker && mMarker.equals(marker)) { - - if (marker.getExtraInfo() != null) { -// onRouteNodeClick(marker.getExtraInfo().getInt("index")); - final String[] urls =marker.getExtraInfo().getString("urls").split(QiYouConstant.SPLITOR_KEY); - final int index =marker.getExtraInfo().getInt("index"); - Bitmap[] bitMaps={ - IL.getBitmap(picUrlMap.get(urls[urls.length-1]) , QiYouConstant.SUBNAIL_PIC_SIZE) - }; -// popMd.showPopup(bitMaps,item.getPoint(),32); - -// if (marker == mMarkerA || marker == mMarkerD) { -// button.setText("更改位置"); - - listener = new OnInfoWindowClickListener() { - public void onInfoWindowClick() { -// if(mCurItem==null|| TextUtils.isEmpty(mCurItem.getTitle()))return; -// String[] urls=mCurItem.getTitle().split(QiYouConstant.SPLITOR_KEY); - mBaiduMap.hideInfoWindow(); - if(urls.length>0){ - activity.showImagePagerFragment(index, urls); - } - - } - }; - -// BitmapDescriptorFactory.fromBitmap(bitMaps[0]); - LatLng ll = marker.getPosition(); - mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromBitmap(bitMaps[0]), ll, -47, listener); - mBaiduMap.showInfoWindow(mInfoWindow); - isShowingPicMark =true; - Toast.makeText(activity, "点击缩略图可以浏览原图", 2).show(); -// } - } - return true; - } - - } - return false; - - } - - @Override - public boolean onPolylineClick(Polyline arg0) { - // TODO Auto-generated method stub - return false; - } - @Override - public List getOverlayOptions() { - // TODO Auto-generated method stub - if (mOverlayOptionList == null) { - mOverlayOptionList = new ArrayList(); - } - return mOverlayOptionList; - } - } - - - - @Override - protected void showNaviPaoPao(Location location){ - LatLng ll = Utils.getLatLng(location.getLatitude(), location.getLongitude()); - String msg=location.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG); - msg=TextUtils.isEmpty(msg)?"":msg.trim(); - - showInfoWindow(ll,msg,null); - - /* if(popupText==null)return; - popupText.setText(location.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG)); - if(TextUtils.isEmpty(popupText.getText()))return; - Bitmap[] bitMaps={ - BMapUtil.getBitmapFromView(popupInfo), - - }; -// -// popRd.showPopup(bitMaps,getLatLng(activity.app.getRecordingTrack().getTrackBean().getLastWp().getWb()),32); - try{ - popRd.showPopup(bitMaps,Utils.getLatLng(location.getLatitude(), location.getLongitude()),32); - }catch (Exception er){ - Utils.logStackTrace(er, TAG); - }*/ - } - - @Override - protected void showSharePaoPao(Map location){ - - float lat=Float.valueOf( location.get("lat")); - float lng=Float.valueOf( location.get("lon")); - LatLng ll = new LatLng( Utils.getbdLat( lat,lng) ,Utils.getbdLon(lat,lng) ); - String msg=location.get("msg"); - msg=TextUtils.isEmpty(msg)?"":msg.trim(); - -// LatLng center = new LatLng(Utils.getbdLat( ll.latitude,ll.longitude), Utils.getbdLon(ll.latitude,ll.longitude)); - -// locateMapCenter( ll.latitude,ll.longitude); - - showInfoWindow(ll,msg,ll); - - /*if(popupText==null)return; - locateMapCenter(Float.valueOf( location.get("lat")) - ,Float.valueOf( location.get("lon"))); - String msg=location.get("msg"); -// if(TextUtils.isEmpty(popupText.getText()))return; - msg=TextUtils.isEmpty(msg)?"":msg.trim(); - popupText.setText(msg); - if(TextUtils.isEmpty(popupText.getText()))return; - Bitmap[] bitMaps={ - BMapUtil.getBitmapFromView(popupInfo), - - }; -// -// popRd.showPopup(bitMaps,getLatLng(activity.app.getRecordingTrack().getTrackBean().getLastWp().getWb()),32); - try{ - popRd.showPopup(bitMaps,Utils.getLatLng(Float.valueOf( location.get("lat")) - ,Float.valueOf( location.get("lon"))),32); - }catch (Exception er){ - Utils.logStackTrace(er, TAG); - } */ - } - - - private void showKMonMap( ArrayList kmgp,int kmDist){ - - if(kmOverlay==null){ - kmOverlay = new MdOverlay(mBaiduMap); - } - - for(LatLng gp:kmgp){ - kmOverlay.getOverlayOptions().add(getCustKmWpNum(gp,(kmgp.indexOf(gp)+1)*kmDist)); - } - - } - - - MarkerOptions getCustKmWpNum( LatLng mGp,int i){ - - - - TextDrawableViewKm view = new TextDrawableViewKm(activity, ""); - - MarkerOptions custWpNo =new MarkerOptions().position(mGp); - - - int size=i<100?40:i>999?80:60; -// QLog.getLogger().d(dTAG,TAG+" cust view size .................."+size); - size =(int)(size*QiYouConstant.PV_INT_SCREEN_WIDTH/720f); -// QLog.getLogger().d(dTAG,TAG+" cust view new size .................."+size); - view.measure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY)); - view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); - view.destroyDrawingCache(); - view.reWriteText((i)+""); -// view.setBackGround(i<100?R.drawable.icon_km:R.drawable.icon_km_big); - view.setBackGround( R.drawable.icon_km ); - view.setAlpha(1); - view.setTextColor(Color.BLACK); - - view.buildDrawingCache(); - - custWpNo.icon(BitmapDescriptorFactory.fromBitmap( view.getDrawingCache() )) .anchor(0.5f, 0.5f); - - - return custWpNo; - } - - - @SuppressLint("NewApi") - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - private void showRoutePointsOnMap(Track_bean mTrack_bean){ -// this.btnMapWayinstruction.setVisibility(View.GONE); -// List items =new ArrayList(); - - List markerOs = new ArrayList(); - - QLog.getLogger().dLog(dTAG, "TrackMap_fragment begin draw road points.............. "); - - int i=0; - int j=0; -// Waypoint_bean nextWb; - String title=""; - int drawIcon=0; - BitmapDescriptor bitDesc=null; - BitmapDescriptor bitDescPass=BitmapDescriptorFactory.fromResource(R.drawable.icon_pass); - BitmapDescriptor bitDescTent=BitmapDescriptorFactory.fromResource(R.drawable.icon_tent);; - BitmapDescriptor bitDescRest=BitmapDescriptorFactory.fromResource(R.drawable.icon_rest);; - BitmapDescriptor bitDescHand=BitmapDescriptorFactory.fromResource(R.drawable.icon_edit);; - BitmapDescriptor bitDescDefault = BitmapDescriptorFactory.fromResource(R.drawable.icon_waypoint);; - for(Waypoint_bean mwb:mTrack_bean.getRoadWps()){ - j++; - if(mwb==null)continue; - drawIcon=0; - title =mwb.getRoadBook();//+";"+mwb.getComment(); - - if(QiYouConstant.DEVELOPER_MODE){ - title =String.format(" roadbook %s, \n turn %s,beardist %s,dist %s", - title,mwb.getTurnFlag().toCHString(),mwb.getBearDist(),mwb.getDistance()); - } - LatLng lg= getLatLng(mwb); -// OverlayItem custWp = new OverlayItem(,"",title); -// title=""; - Bundle bd = new Bundle(); - - bd.putString(RoadOverlay.EXTR_KEY, title ); - - MarkerOptions ooA = new MarkerOptions().position(lg).extraInfo(bd) ; - - if(isCustWaypoint(mwb)){ - - QLog.getLogger().dLog(dTAG,TAG+" building custom roadinfo markoptions...."+j +", mwb.getTurnFlag() "+mwb.getTurnFlag().toCHString()); - - - if(mwb.getTurnFlag()==wpFlag.CUST && !isLiveQuery){ - drawIcon =R.drawable.icon_pass; - bitDesc =bitDescPass; - } - else if(mwb.getTurnFlag()==wpFlag.TENT){ - drawIcon =R.drawable.icon_tent; - bitDesc =bitDescTent; - } - else if(mwb.getTurnFlag()==wpFlag.REST){ - drawIcon =R.drawable.icon_rest; - bitDesc =bitDescRest; - } else if(mwb.getTurnFlag()==wpFlag.CHECK){ - drawIcon =R.drawable.icon_check; - } else if(mwb.getTurnFlag()==wpFlag.HAND && !isLiveQuery){ - drawIcon =R.drawable.icon_edit; - bitDesc = bitDescHand; - } - - - -// ooA.anchor(0.5f, 1.0f); - if (drawIcon !=0){ - try{ - markerOs.add( getCustWpNum(getLatLng(mwb),Integer.valueOf(mwb.getName()),mwb.getTurnFlag())); - QLog.getLogger().dLog(dTAG,TAG+" 1 add customer wp number ..................." +Integer.valueOf(mwb.getName())); -// markerOs.add(ooA); - }catch(NumberFormatException er){ - try{ - markerOs.add( getCustWpNum(getLatLng(mwb),++i,mwb.getTurnFlag())); - QLog.getLogger().dLog(dTAG,TAG+" 2 add customer wp number ..................." +i); - }catch(Exception e){ - Utils.logStackTrace(e, dTAG); - } -// markerOs.add(ooA); - } - } - - - }else if (!isLiveQuery){ - - -// drawIcon =R.drawable.icon_waypoint; - drawIcon = mwb.getBearing() > 0 ? R.drawable.icon_direction_small :R.drawable.icon_waypoint ; - - ooA.anchor(0.5f, 0.5f); - if ( mwb.getBearing()> 0){ - ooA.rotate(360 - mwb.getBearing() ); //逆时针旋转 - } - - } - if(drawIcon!=0){ - - ooA .icon(BitmapDescriptorFactory.fromResource(drawIcon)).draggable(true); - - markerOs.add(ooA); - } - } - - - if(markerOs.isEmpty()) return; - -// - - - - if(mRdOverlay==null){ - mRdOverlay = new RoadOverlay (mBaiduMap); - QLog.getLogger().dLog(dTAG,TAG+" initial RoadOverlay ..................."); - } - QLog.getLogger().dLog(dTAG,TAG+" before add, mRdOverlay.getOverlayOptions().size " + mRdOverlay.getOverlayOptions().size()); - mRdOverlay.getOverlayOptions().clear(); - mRdOverlay.getOverlayOptions().addAll(markerOs); - mRdOverlay.addToMap(); - if(handler!=null) handler.sendEmptyMessage(1); - } - - - - MarkerOptions getCustWpNum( LatLng mGp,int i,wpFlag flag){ - - MarkerOptions custWpNo =new MarkerOptions().position(mGp); - int width=i<10?20:i>=100?40:30; - int height =i<10?25:i>=100?35:30; -// QLog.getLogger().d(dTAG,TAG+" cust view size .................."+width); -// QLog.getLogger().d(dTAG,TAG+" cust view size .................."+width*QiYouConstant.PV_INT_SCREEN_WIDTH/720f); - width =(int)(width*QiYouConstant.PV_INT_SCREEN_WIDTH/720f); - height =(int)(height*QiYouConstant.PV_INT_SCREEN_WIDTH/720f); - // QLog.getLogger().d(dTAG,TAG+" cust view new size .................."+width); - - TextDrawableView view = new TextDrawableView(activity,i+"", width,height); - - view.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); - view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); - view.destroyDrawingCache(); -// view.reWriteText(String.valueOf(i)); - - view.buildDrawingCache(); - - Bundle bd = new Bundle(); - - bd.putInt(RoadOverlay.EXTR_KEY_INDEX, i); - bd.putInt(RoadOverlay.EXTR_KEY_FLAG , flag.toInt()); - custWpNo.icon(BitmapDescriptorFactory.fromBitmap( view.getDrawingCache() )/*.fromView(wpNumText)*/).extraInfo(bd).anchor(0.5f, 0.5f); - - - - return custWpNo; - } - - - @Override - void clearLiveItems(){ - reNewShareOverflay(); - } - - void reNewShareOverflay(){ - if(mShareOverlay==null){ - mShareOverlay= new RoadOverlay(mBaiduMap); - } - mShareOverlay.removeFromMap(); - mBaiduMap.hideInfoWindow(); - } - - - Map items =new HashMap(); - - @Override - void showLiveMap(ArrayList deltaList) { - - QLog.getLogger().d(dTAG, "begin to paint live locations.............."); - - reNewShareOverflay(); -// this.btnMapWayinstruction.setVisibility(View.GONE); -// List items =new ArrayList(); - String title=""; -// int drawIcon=0; - - - QLog.getLogger().d(dTAG, String.format("----------deltaList.size %s", deltaList.size())); - - for(SharedLocation mwb:deltaList){ - - if(mwb==null)continue; - - title =mwb.getMsg(); - - Bundle bd = new Bundle(); - - bd.putString(RoadOverlay.EXTR_KEY, title ); - bd.putString(RoadOverlay.EXTR_KEY_NAME, mwb.getName() ); - - -// MarkerOptions ooA = items.get(Integer.valueOf(mwb.getId())) ; -// MarkerOptions ooA = new MarkerOptions().position(Utils.getLatLng(mwb.getLat(), mwb.getLon())).extraInfo(bd); -// OverlayItem custWp =items.get(Integer.valueOf(mwb.getId())); - - /* if(ooA==null){ -// custWp= new OverlayItem( Utils.getLatLng(mwb.getLat(), mwb.getLon()),"",title); - ooA = new MarkerOptions().position(Utils.getLatLng(mwb.getLat(), mwb.getLon())).extraInfo(bd); - }else{ - custWp.setLatLng(Utils.getLatLng(mwb.getLat(), mwb.getLon())); - custWp.setSnippet(title); - } - */ - - - String nm=mwb.getName(); - QLog.getLogger().d(dTAG, String.format("building name %s", mwb.getName() )); - - nm=TextUtils.isEmpty(nm)?"unknown":nm; - - int width=mwb.getName().length()*25; - int height =35; - width =(int)(width*QiYouConstant.PV_INT_SCREEN_WIDTH/720f); - height =(int)(height*QiYouConstant.PV_INT_SCREEN_WIDTH/720f); - CompositDrawableView view = new CompositDrawableView(activity, mwb.getName(),10, - TextUtils.isEmpty(title),mwb.getBear(),width,height); - view.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); - view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); - view.destroyDrawingCache(); -// view.reWriteText(String.valueOf(i)); -// view.setAlpha(alpha); - view.buildDrawingCache(); -// custWp.setMarker( new BitmapDrawable(view.getDrawingCache()) ); - - -// custWp.setAnchor(OverlayItem.ALIGN_TOP); -// custWp.setTitle(mwb.getName()); - -// items.add(custWp); - - MarkerOptions ooA = new MarkerOptions().position(Utils.getLatLng(mwb.getLat(), mwb.getLon())).extraInfo(bd) - .icon(BitmapDescriptorFactory.fromBitmap( view.getDrawingCache() )).anchor(0.5f, 0.1f); - - items.put(mwb.getId(), ooA); - - - - - QLog.getLogger().d(dTAG, "begin to paint live locations..............x"); - } - - /* for( MarkerOptions custWp : items.values()){ - if(mShareOverlay.getAllItem().contains(custWp)){ -// boolean b=mShareOverlay.removeItem(custWp); -// QLog.getLogger().d(dTAG, String.format("removing sharpoints,name :%s msg: %s,succeed?%s", mwb.getName(),mwb.getMsg(),b)); -// QLog.getLogger().d(dTAG, String.format("existed sharpoints,name :%s msg: %s ", mwb.getName(),mwb.getMsg() )); - QLog.getLogger().d(dTAG, String.format("existed sharpoints,name :%s msg: %s ",custWp.getSnippet(),custWp.getTitle())); - - } else{ - mShareOverlay.addItem(custWp); - QLog.getLogger().d(dTAG, String.format("adding sharpoints,name :%s msg: %s",custWp.getSnippet(),custWp.getTitle())); - } - }*/ - - QLog.getLogger().d(dTAG, "begin to paint live locations..............1"); - - if(items.isEmpty()) return; - QLog.getLogger().d(dTAG, "begin to paint live locations..............2"); -// - if(handler!=null) handler.sendEmptyMessage(3); - - if(mShareOverlay==null){ - mShareOverlay= new RoadOverlay(mBaiduMap); - } - mShareOverlay.getOverlayOptions().clear(); - mShareOverlay.getOverlayOptions().addAll(items.values()); - mShareOverlay.addToMap(); - - - mShareOverlay.zoomToSpan(); - - } - - - - @Override - protected void showWayinstructions(){ - - - if(mRdOverlay==null)return; - - QLog.getLogger().dLog(dTAG,TAG+" mRdOverlay.getOverlayOptions().size " + mRdOverlay.getOverlayOptions().size()); - QLog.getLogger().dLog(dTAG,TAG+" mRdOverlay.getOverlayMarkers().size " + mRdOverlay.getOverlayMarkers().size()); - - if(mRdOverlay.getOverlayMarkers().size()>0){ - QLog.getLogger().d(dTAG, " begin to hide wayinstructions"); - mRdOverlay.removeFromMap(); - this.btnMapWayinstruction.setImageResource(R.drawable.wayinstructions_inactive); - }else{ - QLog.getLogger().d(dTAG, " begin to show wayinstructions"); - perfomRotate(360); - mRdOverlay.addToMap(); - this.btnMapWayinstruction.setImageResource(R.drawable.wayinstructions4); - } - - - } - -// boolean - - @Override - protected void showMapPicture(){ - - if(mPhotoOverlay==null)return; - - QLog.getLogger().dLog(dTAG,TAG+" mPhotoOverlay.getOverlayOptions().size " + mPhotoOverlay.getOverlayOptions().size()); - QLog.getLogger().dLog(dTAG,TAG+" mPhotoOverlay.getOverlayMarkers().size " + mPhotoOverlay.getOverlayMarkers().size()); - - if(mPhotoOverlay.getOverlayMarkers().size()>0){ - QLog.getLogger().d(dTAG, "begin to hide pics"); - mPhotoOverlay.removeFromMap(); - this.btnMapPicture.setImageResource(R.drawable.picture_inactive); - }else{ - QLog.getLogger().d(dTAG, "begin to show pics"); - mPhotoOverlay.addToMap(); - btnMapPicture.setImageResource(R.drawable.picture); - } - - } - - @Override - protected void roationMap(){ - canRotationMap=!canRotationMap; - - handler = new Handler(){ - @Override - public void handleMessage(Message msg) { - if (msg.what==1 && !canRotationMap) { -// mMapController.setRotation(360); -// mMapController.setOverlooking(-5); - perfomRotate(361); - btnRotation.setImageResource(R.drawable.icon_rotation_inactive); - } - }}; - - - - String msg="地图已切换到随动旋转模式"; - if(!canRotationMap){ - new Thread() { - - public void run() { - - try { - - Thread.sleep(500); - - } catch (Exception e) { - - } - - handler.sendEmptyMessage(1); - }; - - }.start(); - - - msg="地图已退出随动旋转模式"; - }else - btnRotation.setImageResource(R.drawable.icon_rotation); - - Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show(); - } - - - @Override - protected void autoZoomMap(){ - canAutoZoomMap=!canAutoZoomMap; - String msg="地图已切换到随动缩放模式"; - if(!canAutoZoomMap){ - btnAutoZoom.setImageResource(R.drawable.icon_auto_zoom_inactive); - msg="地图已退出随动缩放模式"; - }else - btnAutoZoom.setImageResource(R.drawable.icon_auto_zoom); - - Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show(); - } - - - - @Override - public void onResume() { - /** - * MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume() - */ -// - if(mMapView!=null){ - mMapView.onResume(); -// mMapView.refresh(); - } - super.onResume(); - updateFinshButonText(); - isShowingPicMark =false; - } - - @Override - public void onPause() { - /** - * MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause() - */ - - - if(mMapView!=null) - try{ -// mMapView.setVisibility(View.INVISIBLE); - mMapView.onPause(); - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - } - - - super.onPause(); - } - - - @Override - public void onDestroy() { - if(mMapView!=null) - - try{ - mMapView.onDestroy(); - }catch(Exception e){ - Utils.logStackTrace(e, TAG); - } - - // QLog.getLogger().d(dTAG,TAG+" "+"onDestroy" ); - super.onDestroy(); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - if(mMapView!=null)mMapView.onSaveInstanceState(outState); - } - - - /** - * load track and to start navi - */ - @Override - void showWebTrack(Track tr){ - if(tr==null)return; - this.activity.app.setCurrentTrack(tr,true); - - activity.startNaviService(tr.getTrackBean().getSvrNumber(), false); - ll_navi_progress.setVisibility(View.VISIBLE); - } - - - -} - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackStatics_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackStatics_fragment.java deleted file mode 100644 index 1b69479..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackStatics_fragment.java +++ /dev/null @@ -1,1520 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.location.Location; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.text.TextUtils; -import android.view.Gravity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.TabHost; -import android.widget.TabHost.OnTabChangeListener; -import android.widget.TabWidget; -import android.widget.TextView; - -import com.baidu.mapapi.map.MapStatusUpdateFactory; -import com.baidu.mapapi.model.LatLng; -import com.baidu.mapapi.model.LatLngBounds; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.GPItem; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.TypeStatistics; -import com.qiyou.mb.android.ui.charts.AbstractChart; -import com.qiyou.mb.android.ui.charts.TrackPieChart; -import com.qiyou.mb.android.ui.charts.TrackStaticsChart; -import com.qiyou.mb.android.upgrade.UpdateManager; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.log.QLog; - -import java.util.HashMap; - - -public class TrackStatics_fragment extends TrackMap_fragment implements IlocationFragment { - @Override - public void setFTag(){ - TAG="com.qiyou.TrackStatics_fragment"; -// FirstTabTextColor= getResources().getColorStateList(R.color.red); -// FirstTabBackGround=R.drawable.icon_statistics; - } - - public static String getFTag(){ - return "com.qiyou.TrackStatics_fragment"; - } - - @Override - public String getCurrentTag(){ - return "com.qiyou.TrackStatics_fragment"; - } - - LinearLayout llcharts ; -// LinearLayout stat_chart; - final String overallChartTab =" 汇总"; - final String typeTab =" 明细"; - final String aboutTab ="关于"; - -// final String =" "; - final String myfootTab =" 足迹"; - - final String moreTab ="更多"; - final String Chart3 =" "; -// ProgressDialog progressDialog; - Handler handler; - - - private TypeStatistics typeStatistics=null;; - private TypeStatistics statChart=null;; - - private HashMap trackStatMap; - private TextView mftNoteText; - private TextView mdetailNoteText; - private ImageView imgBtnEditUser; - private Button btnMoreHistory,btnMoreConfigure,btnMoreOffline,btnScan,btnMoreScore; - -// private GraphicsOverlay gpFootPointsOverlay = null; - - public TrackStatics_fragment() { - // TODO Auto-generated constructor stub - TAG="com.qiyou.mb.android.ui.TrackStatics_fragment"; - } - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if(activity==null){ - activity = (com.qiyou.mb.android.ui.MainActivity)getActivity(); - } - QLog.getLogger().d(dTAG, TAG+" TrackStatics starting onCreate finished............."); - - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - QLog.getLogger().d(dTAG, TAG+" TrackStatics starting onCreateView start............."); - vContainer = inflater.inflate(R.layout.track_statics, container, false); - QLog.getLogger().d(dTAG, TAG+" TrackStatics starting initialView start............."); - initialView(); - initialMapview(); - QLog.getLogger().d(dTAG, TAG+" TrackStatics starting initialView end............."); - QLog.getLogger().d(dTAG, TAG+" TrackStatics starting onCreateView finished............."); - return vContainer; - } - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - //default to show chart1 -// llcharts = (LinearLayout)vContainer.findViewById(R.id.st_chart1); -// stat_chart= (LinearLayout)vContainer.findViewById(R.id.stat_chart); - -// if(llcharts.getChildCount()==0) -// showCharts(0); -// initQueryTrackTypeSpin(); -// initialStatTracks(); -// mMapView.getOverlays().remove(myLocationOverlay); - QLog.getLogger().d(dTAG, TAG+" TrackStatics starting onActivityCreated finished............."); - } - @Override - protected void initialView(){ -// mNoteText = (TextView) vContainer.findViewById(R.id.text_note); -// initialTabhost(); - - initialDetails(); - - initStatViews(); - - initialMoreViews(); - - super.initialView(); - - setVersion(); - } - @SuppressLint("NewApi") - @Override - protected void initialMapview(){ - super.initialMapview(); - // gpFootPointsOverlay = new GraphicsOverlay(mMapView); -// mMapView.getOverlays().add(gpFootPointsOverlay); - footNumber=0; - isLookingFootMark=false; -// - - -// mMapView.setBuiltInZoomControls(false); -// myLocationOverlay.setMarker(null); -// mMapView.setAlpha(0.50f); - - - } - - @Override - protected void initialLiveViews(){ - - } - - private String notesMsg=""; -// @Override - void showLocalNotes(String notes){ - - if( activity.app.mStatistics==null)return; - Utils.getlastGeoRequestTime(activity); - - if(QiYouConstant.LAST_GEO_UPDATE>0){ - Utils.getTimeCnt(System.currentTimeMillis()-QiYouConstant.LAST_GEO_UPDATE); - } - boolean notInWifi =!Utils.isNetworkConnected(activity) || Utils.getNetworkType(activity)!= QiYouConstant.NETWORK_TYPE_WIFII; - Boolean needWifi4GEO =activity.app.mStatistics.getLastTime()>QiYouConstant.LAST_GEO_UPDATE; - Boolean needWifi4MAP =QiYouConstant.LAST_OFFMAP_UPDATE==0; - needWifi4GEO=needWifi4GEO&¬InWifi; - needWifi4MAP=needWifi4MAP&¬InWifi; - String split=needWifi4GEO?"\n":"提示:"; -// String split= "\n提示:"; - notesMsg=needWifi4GEO?"提示:请链接WIFI以更新足迹信息":""; - split=TextUtils.isEmpty(notesMsg)?"提示:":"\n提示:"; - notesMsg+=needWifi4MAP?split+"请链接WIFI检查更新离线地图":""; - QiYouConstant.CAN_SPEAK=QiYouConstant.CAN_SPEAK && Utils.checkSpeechServiceInstall(activity); - split=TextUtils.isEmpty(notesMsg)?"提示:":"\n提示:"; - notesMsg+=Utils.checkSpeechServiceInstall(activity)?"":split+"语音导航功能需安装<<讯飞语音+>>"; - -// ll_ftnote.setVisibility(needWifi4GEO?View.VISIBLE:View.GONE); -// mftNoteText.setText("正在为您寻找小脚印"); - - - if(TextUtils.isEmpty(notesMsg)){ - notesMsg= "您还没有运动记录,马上开始吧!"; - - /* if(!activity.app.isShowSlidTabs()) - msg= "提示:左右滑动屏幕可以切换标签页面"; - else*/ - if(activity.app.isLastTrackExist()|| activity.app.mStatistics!=null && activity.app.mStatistics.getCnt()>0 &&activity.app.mStatistics.getFirstTime()>0 ){ - long time =activity.app.mStatistics.getFirstTime(); - - notesMsg =time>0?String.format("驴子从%s开始为您服务", Utils.getFormatedTime(time)):""; - } - -// mNoteText.setText(msg); - - } -// else{ -// mNoteText.setText(notesMsg); -// } - - if(activity.app.isShowSlidTabs()){ - notesMsg +=TextUtils.isEmpty(notesMsg)?"":"\n"; - notesMsg +="提示:左右滑动屏幕可以切换标签页面"; - } - - notesMsg =TextUtils.isEmpty(notesMsg)?"运动数据汇总统计":notesMsg; - - mNoteText.setText(notesMsg); - } - - @Override - protected void initialTabhost(){ - super.initialTabhost(); - tabhost = (TabHost)vContainer.findViewById(R.id.tabhost); - tabhost.setup(); - - - TabHost.TabSpec statTab = tabhost.newTabSpec(overallChartTab); - statTab.setIndicator(overallChartTab); - statTab.setContent(R.id.tab_statchart); - tabhost.addTab(statTab); - - - TabHost.TabSpec t1 = tabhost.newTabSpec(typeTab); - t1.setIndicator(typeTab); - t1.setContent(R.id.tabType); - tabhost.addTab(t1); - -// TabHost.TabSpec readmeTabSpec = tabhost.newTabSpec(aboutTab); // This param will be used as tabId. -// readmeTabSpec.setIndicator(aboutTab); -// readmeTabSpec.setContent(R.id.ll_readme); -// tabhost.addTab(readmeTabSpec); - - TabHost.TabSpec myfootSpec = tabhost.newTabSpec(myfootTab); // This param will be used as tabId. - myfootSpec.setIndicator(myfootTab); - myfootSpec.setContent(R.id.tab_map); - tabhost.addTab(myfootSpec); - - -// TabHost.TabSpec tabmore = tabhost.newTabSpec("more"); // This param will be used as tabId. -// myfootSpec.setIndicator("more"); -// myfootSpec.setContent(R.id.tabMore); -// tabhost.addTab(tabmore); - - - TabHost.TabSpec moreSpec = tabhost.newTabSpec(moreTab); // This param will be used as tabId. - moreSpec.setIndicator(moreTab); - moreSpec.setContent(R.id.tabMore); - tabhost.addTab(moreSpec); - - -// TabHost.TabSpec readmeTabSpec = tabhost.newTabSpec(exchangeTab); // This param will be used as tabId. -// readmeTabSpec.setIndicator(exchangeTab); -// readmeTabSpec.setContent(R.id.ll_exchange); -// tabhost.addTab(readmeTabSpec); - -// TabHost.TabSpec c1 = tabhost.newTabSpec(AVSchartTab); -// c1.setIndicator(AVSchartTab); -// c1.setContent(R.id.AVSchartTab); -// tabhost.addTab(c1); - -// int height =getResources().getDimensionPixelSize(R.dimen.tab_top_height); -// Utils.setTabhostStyle(tabhost, height,-1); - - - initialTabhostStyle(tabhost); - -// TabHost.TabSpec chart2 = tabhost.newTabSpec(Chart2); -// chart3.setIndicator(Chart3); -// chart3.setContent(R.id.tab3); -// tabhost.addTab(chart3); - - - tabhost.setOnTabChangedListener(new OnTabChangeListener() { - @Override - public void onTabChanged(String tabId ) { - - activity.isMapActive=false; - -// Toast toast = Toast.makeText(getActivity(), tabId, Toast.LENGTH_SHORT); -// toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 50); -// toast.show(); - if(tabId.equalsIgnoreCase(typeTab)){ - if(activity.app.isStaticsticsDone) - initQueryTrackTypeSpin(); - } - - if(tabId.equalsIgnoreCase(myfootTab)){ - showMyfoot(); - activity.isMapActive=true; -// activity.speech("的"); - } - - onMyTabChanged(tabId); - - - -// if(tabId.equalsIgnoreCase(overallChartTab)){ -// -// ll_selection.setVisibility(View.GONE); -// }else{ -// -// ll_selection.setVisibility(View.VISIBLE); -// } -// else if(tabId.equalsIgnoreCase(Chart1)){ -// -// } -// }else if(tabId.equalsIgnoreCase(Chart3)){ -// llcharts = (LinearLayout)vContainer.findViewById(R.id.st_chart3); -// if(llcharts.getChildCount()==0) -// showCharts(2); -// } - - - - } - }); - - } - - - - int chartType; - @Override - protected void showCharts( int type){ - - chartHeight =getResources().getDimensionPixelSize(R.dimen.chart_height_in_scrollview); - chartHeight=QiYouConstant.PV_INT_SCREEN_HEIGHT/4; - this.chartType=type; - if(typeStatistics ==null)doQuery(); - if(typeStatistics==null)return; - if(chartType ==0)getLastAvsDistCharts(statChart); - - if(chartType ==1)getTypePieCharts(); - if(chartType ==2)getTypeStatCharts(); - - -// String[] tmp =new String[]{}; - -// llcharts = (LinearLayout)vContainer.findViewById(R.id.st_chart1); -// if(llcharts.getChildCount()>0) -// llcharts.removeAllViews(); -// else - { - - -// geEleCharts(trs); -// geEledBarChart(trs); -// geEleDChart(trs); -// if(chartType ==1)getBasicCharts(trs); -// if(chartType ==2) getBasicCharts(trs); - } - } - - void getTypeStatCharts(){ -// int height =getResources().getDimensionPixelSize(R.dimen.tab_top_height); - - getChart(typeStatistics,new TrackStaticsChart()); - } - - void getTypePieCharts(){ -// showCharts((new TrackPieChart(activity.app.mStatisticsTracks)).getChartView(activity)); - try{ - if(activity.app.mStatistics!=null &&activity.app.mStatistics.getTypeUsedLst().size()>0) - showCharts((new TrackPieChart(activity.app.mStatistics.getTypeUsedLst())).getChartView(activity)); - - }catch(Exception e){ - - Utils.logStackTrace(e, dTAG); - } - } - - void getLastAvsDistCharts(TypeStatistics sttr){ - - getChart(sttr,new TrackStaticsChart()); - } - - void getChart(TypeStatistics sttr,AbstractChart chart){ - chart.setStrack(sttr); - showCharts(chart.getChartView(activity)); - - } - - int chartHeight=LayoutParams.MATCH_PARENT; - void showCharts(View v) - { - if(v==null)return; - try{ - -// int height=500; - - v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,chartHeight)); //set the layout, or will not show out - llcharts.addView(v); - }catch (Exception e) - { - Utils.logStackTrace(e, TAG); - } - - } - - /* - * initial statics tracks when it is null - */ - @Override - public void doQuery(){ - -// getStatTracks(); - - int stSize =0; - if(activity.app.mStatistics!=null ) - stSize =activity.app.mStatistics.getStatisticsTracks().size(); -// QLog.getLogger().d(dTAG, TAG+" activity.app.mStatisticsTracks.size()>0?: " +(stSize>0)); -// QLog.getLogger().d(dTAG, TAG+"@@@@@@ activity.app.startTime : " +activity.app.startTime); -// QLog.getLogger().d(dTAG, TAG+" activity.app.statTrackLoading?: " +activity.app.statTrackLoading); -// QLog.getLogger().d(dTAG, TAG+" activity.app.isStaticsticsDone?: " +activity.app.isStaticsticsDone); -// QLog.getLogger().d(dTAG, TAG+" activity.app.isNewLogin?: " + activity.app.isNewLogin); - -// if(typeStatistics==null || isFilterChanged || stSize==0 ){ //||start,end, type){ - - /* if(stSize==0){ -// activity.app.getStaticsTracks(); - progressDialog = ProgressDialog.show(activity, "请稍等...", "获取数据中...", true); - }*/ - if(activity.app.statTrackLoading ){ - /* progressDialog = ProgressDialog.show(activity, "请稍等...", "获取统计数据中...", true); - progressDialog.setCancelable(true); - progressDialog.setCanceledOnTouchOutside(true); - ll_note.setVisibility(View.VISIBLE);*/ - mNoteText.setText("正在加载数据,请稍后..."); - } - if(activity.app.isNewLogin ||!activity.app.isStaticsticsDone){ - mNoteText.setText("正在从云端下载数据。。。请稍等..."); - } - - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog -// if(progressDialog!=null)progressDialog.dismiss(); -// mNoteText.setText(""); - - - if(msg.what==0){ - //更新UI -// setTrackDetail1();//statusTextView.setText("Completed!"); -// typeStatistics =activity.app.typeStatistics; -// if(spTrackType==null){ -//// buildStatMap(); -// initQueryTrackTypeSpin(); -// } -// if(firstLoad){ -// initQueryTrackTypeSpin(); -// } - if (activity.app.mStatistics != null && activity.app.mStatistics.getFirstTime() > 0 && activity.app.mStatistics.getCnt() > 0 ){ - getStatTracks(); - setDetails(); - } - showLocalNotes(null); -// showGpxFileList(); -// showMyfoot(); -// mNoteText.setText(""); -// ll_note.setVisibility(View.GONE); -// showCharts(chartType); - - } - else if(msg.what==1){ - mNoteText.setText("查询超时,请重试"); -// ll_note.setVisibility(View.VISIBLE); - } - }}; - - new Thread(){ - - @Override - public void run() { - //需要花时间计算的方法 - int topWaiting=0; - - activity.app.getStatisticsTrack(trackType); - while(!activity.app.isStaticsticsDone - ||activity.app.isNewLogin - ||activity.app.statTrackLoading - ||activity.app.mStatistics ==null - ||activity.app.mStatistics.getCnt() > 0 && activity.app.mStatistics.getStatisticsTracks().get(trackType)==null - ||activity.app.mStatistics.getStatisticsTracks().get(trackType)!=null - && activity.app.mStatistics.getStatisticsTracks().get(trackType) - .getSbs().size()==0 - - ){ //||start,end, type){ - try { - Thread.sleep(200); - topWaiting+=200; - QLog.getLogger().d(dTAG, TAG+" get staticts topWaiting: " +topWaiting); - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB*2 ) - { - handler.sendEmptyMessage(0); - return; - } - if(!(activity.app.statTrackLoading - || !activity.app.isStaticsticsDone - ||activity.app.isNewLogin - ||activity.app.statTrackLoading)) { - break; - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - handler.sendEmptyMessage(0); - } - } - - - //向handler发消息 - handler.sendEmptyMessage(0); - }}.start(); - -// } else if(typeStatistics!=null &&typeStatistics.getStart()>0 ){ -// getStatTracks(); -// setDetails(); -// mNoteText.setText(""); -// ll_note.setVisibility(View.GONE); -// } - - } - - - - void getStatTracks(){ - - - - statChart= activity.app.mStatistics.getLastStrack(); -// int totalChartSize=11; - -// if(activity.app.typeStatistics==null ) -// initialStatTracks(); - - //startDate=0;, endDate - typeStatistics = new TypeStatistics(); - if(activity.app.getStatisticsTrack(trackType)==null) return;//no records for selected type or date. - QLog.getLogger().d(dTAG, TAG+ " dddddddddddddddddddddd-------------------begin to get StatTrack. ------------of type-"+ trackType ); - if(custStartDate>0||custEndDate>0){ - startDate =custStartDate; - endDate =custEndDate; - } - typeStatistics =activity.app.getTracksStat(trackType, startDate, endDate); - - /* - if(startDate == endDate && startDate==0){ - - for(Statics_bean sb:activity.app.typeStatistics.getStaticsTrackBeans()){ - if(sb==null)continue; - if( sb.getType() == trackType) - typeStatistics.getStaticsTrackBeans().add(sb); - } - - }else - - startDate=startDate>0?startDate:0; - endDate=endDate>0?endDate:System.currentTimeMillis(); - - - ConcurrentHashMap sbs =activity.app.getStatisticsTrack(trackType).getSbs(); - Statics_bean sb; - int sbCnt=0; - for(Integer key :sbs.keySet()){ - sb=sbs.get(key); - if(sb==null)continue; - - if( ( - startDate>0 && endDate >= startDate - && - (sb.getStartTime()>=startDate && sb.getStartTime()<=endDate - ||sb.getEndTime()>=startDate && sb.getEndTime()<=endDate - ) - ||(startDate == endDate && startDate==0) - ) - && sb.getType() == trackType ) - typeStatistics.getSbs().put(sb.getTrackid(), sb); - } - - StatTrack st = new StatTrack(); - for(Integer key : typeStatistics.getSbs().keySet()){ - sb=typeStatistics.getSbs().get(key); -// st.seteDownDist(sb.geteDownDist() ); - st.seteUpDist( sb.geteUpDist()+sb.geteDownDist()); - st.setTopSpeed(sb.getTopSpeed() ); - st.setPause(sb.getPause() ); - st.setOffTime( sb.getOffTime()); - st.setDist(sb.getDistance()); - st.setMaxR( sb.getMaxRdist()); - st.setSportTime( sb.getSportTime()); - st.setAvSpeed(sb.getAVS()); - st.setTAvSpeed(sb.getTAVS()); - st.setBurn(sb.getBurn()); -// st.setTotalTime(sb.getSportTime()+sb.getPause()); - st.setTotalTime(sb.getTotalTime()); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd getStatTracks------------------" ); -// -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getDistance()"+sb.getDistance() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getSportTime()"+sb.getSportTime() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getAVS()"+sb.getAVS() ); -// QLog.getLogger().d(dTAG, TAG+ "ddddddddddddddd sb.getPause()"+sb.getPause() ); - - } - - typeStatistics.setStatTrack(st); - QLog.getLogger().d(dTAG, TAG+ " dddddddddddddddddddddd-------------------Get StatTrack. -------------" ); - statChart= activity.app.mStatistics.getLastStrack(); - */ - - - } - - - - private TextView mCntText; - private TextView mSumDistText; - private TextView mSumTimeText; - private TextView mSumSpTimeText; - private TextView mSumSumEupText; - private TextView mSumSumEdownText; - private TextView mSumCostText; - - - - - private TextView mSpeedText4; - private TextView mSpeedText3; - - private TextView mKmTime3; - private TextView mKmTime4; - - private TextView mTotalTimeText3; - private TextView mTotalTimeText4; - - - private TextView mDistanceText3; - private TextView mDistanceText4; - - - private TextView mRdText3; - private TextView mRdText4; - - - - private TextView mTopSpeedText3; - private TextView mTopSpeedText4; - - - private TextView mSportTimeText3; - private TextView mSportTimeText4; - - private TextView mTavsText3; - private TextView mTavsText4; - - - private TextView mBurnText3; - private TextView mBurnText4; - -// private TextView mPausedTimeText3; -// private TextView mPausedTimeText4; -// private TextView mOffTimeText3; -// private TextView mOffTimeText4; - - private TextView mTotaleUpText3; - private TextView mTotaleUpText4; - private TextView mTotaleDownText3; - private TextView mTotaleDownText4; - - private LinearLayout ll_ftnote; - - void initialDetails(){ - mSpeedText3 = (TextView) vContainer.findViewById(R.id.td_textView_av_speed3); - mSpeedText4 = (TextView) vContainer.findViewById(R.id.td_textView_av_speed4); - - mKmTime3 = (TextView) vContainer.findViewById(R.id.td_textView_kmTime3); - mKmTime4 = (TextView) vContainer.findViewById(R.id.td_textView_kmTime4); - - - mTotalTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_totalTime3); - mTotalTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_totalTime4); - - mSportTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_sport_time3); - mSportTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_sport_time4); - - mTavsText3 = (TextView) vContainer.findViewById(R.id.td_textView_tavs3); - mTavsText4 = (TextView) vContainer.findViewById(R.id.td_textView_tavs4); - - mBurnText3 = (TextView) vContainer.findViewById(R.id.td_textView_burn3); - mBurnText4 = (TextView) vContainer.findViewById(R.id.td_textView_burn4); - - mDistanceText3 = (TextView) vContainer.findViewById(R.id.td_textView_Distance3); - mDistanceText4 = (TextView) vContainer.findViewById(R.id.td_textView_Distance4); - - mRdText3 = (TextView) vContainer.findViewById(R.id.td_textView_maxRd3 ); - mRdText4 = (TextView) vContainer.findViewById(R.id.td_textView_maxRd4 ); - - mTopSpeedText3 = (TextView) vContainer.findViewById(R.id.td_textView_top_speed3); - mTopSpeedText4 = (TextView) vContainer.findViewById(R.id.td_textView_top_speed4); - -// mPausedTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_paused_time3); -// mPausedTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_paused_time4); -// -// mOffTimeText3 = (TextView) vContainer.findViewById(R.id.td_textView_off_time3); -// mOffTimeText4 = (TextView) vContainer.findViewById(R.id.td_textView_off_time4); - - - mTotaleUpText3 = (TextView) vContainer.findViewById(R.id.td_textView_eUp3); - mTotaleUpText4 = (TextView) vContainer.findViewById(R.id.td_textView_eUp4); - - - mTotaleDownText3 = (TextView) vContainer.findViewById(R.id.td_textView_eDown3); - mTotaleDownText4 = (TextView) vContainer.findViewById(R.id.td_textView_eDown4); - - - - mCntText= (TextView) vContainer.findViewById(R.id.ts_txt_cnt); - mSumDistText= (TextView) vContainer.findViewById(R.id.ts_sum_dist); - mSumSpTimeText= (TextView) vContainer.findViewById(R.id.ts_sum_sptime); - mSumSumEupText= (TextView) vContainer.findViewById(R.id.ts_sum_eup); - mSumSumEdownText=(TextView) vContainer.findViewById(R.id.ts_sum_edown); - mSumCostText= (TextView) vContainer.findViewById(R.id.ts_sum_cost); - mSumTimeText= (TextView) vContainer.findViewById(R.id.ts_sum_alltime); - - - mNoteText= (TextView) vContainer.findViewById(R.id.note_stat); - ll_note =(LinearLayout)vContainer.findViewById(R.id.ll_note); - ll_note.setVisibility(View.VISIBLE); - - - mRecordingDist= (TextView) vContainer.findViewById(R.id.recording_dist); - mRecordingSporttime=(TextView) vContainer.findViewById(R.id.recording_sportTime); - mRecordingAVS= (TextView) vContainer.findViewById(R.id.recording_avs); - mRecordingBurn= (TextView) vContainer.findViewById(R.id.recording_burn); - mRecordingSpd= (TextView) vContainer.findViewById(R.id.recording_speed); - mRecordingNoSpd= (TextView) vContainer.findViewById(R.id.recording_nospeed); - - recordingLL = (LinearLayout) vContainer.findViewById(R.id.recording_ll); - - mftNoteText= (TextView)vContainer.findViewById(R.id.ft_notice) ; - ll_ftnote= (LinearLayout)vContainer.findViewById(R.id.ll_ft_notice); - - - } - - - - - - - - - - - - - - - private void setDetails(){ -// if(typeStatistics==null){ -// initialDetailValues(); -// } - - - - setAVS_DistChart(); - setType_Chart(); - -// if(!firstLoad){ - setTrackAV(); - setTrackMax(); - setBasicData(); - setTypeSt_Chart(); -// } - setStatDesc(); -// showGpxFileList(); - - } - - private void setTrackMax() - { - mTopSpeedText3.setText(String.format("%.2f", typeStatistics.getStatTrack().getTopSpeed())); - mSpeedText3.setText(String.format("%.2f",typeStatistics.getStatTrack().getAvSpeed())); - mDistanceText3.setText(String.format("%.2f",typeStatistics.getStatTrack().getDist()/1000)); - mTotaleUpText3.setText(String.format("%.0f",typeStatistics.getStatTrack().getUpDistE())); -// mTotaleDownText3.setText(String.format("%.0f", Math.abs(typeStatistics.getStatTrack().getMaxeDownDist()))); - mSportTimeText3.setText( Utils.getTimeCnt(typeStatistics.getStatTrack().getSportTime(),false)); -// mPausedTimeText3.setText(Utils.getTimeCnt( typeStatistics.getStatTrack().getMaxPause(),false)); - mTotalTimeText3.setText(Utils.getTimeCnt(typeStatistics.getStatTrack().getTotalTime(),false)); -// mOffTimeText3.setText(Utils.getTimeCnt( typeStatistics.getStatTrack().getMaxOffTime(),false)); - mRdText3.setText(String.format("%.2f",typeStatistics.getStatTrack().getMaxR()/1000)); - mBurnText3.setText( String.format("%.2f",typeStatistics.getStatTrack().getBurn())); - mTavsText3.setText( String.format("%.2f",typeStatistics.getStatTrack().getTavSpeed())); - if(typeStatistics.getStatTrack().getUpDistE()>0){ - ((TextView)vContainer.findViewById(R.id.td_textView_Updist3)).setText(String.format("%.2f",typeStatistics.getStatTrack().getUpDistE()/1000)); - ((TextView)vContainer.findViewById(R.id.td_textView_downDist3)).setText(String.format("%.2f",typeStatistics.getStatTrack().getDownDist()/1000)); - ((TextView)vContainer.findViewById(R.id.td_textView_maxEle3)).setText(String.format("%.0f",typeStatistics.getStatTrack().getMaxEle())); - ((TextView)vContainer.findViewById(R.id.td_textView_minEle3)).setText(String.format("%.0f",typeStatistics.getStatTrack().getMinEle())); - } - mKmTime3.setText(Utils.getTimeMS(typeStatistics.getStatTrack().getMinKmTime())); - } - - /* - * av track - */ - private void setTrackAV() - { - mTopSpeedText4.setText(String.format("%.2f",typeStatistics.getStatTrack().getAvtopSpeed())); - mSpeedText4.setText(String.format("%.2f",typeStatistics.getStatTrack().getAvavSpeed())); - mDistanceText4.setText(String.format("%.2f",typeStatistics.getStatTrack().getAvdist()/1000)); - mTotaleUpText4.setText(String.format("%.0f",typeStatistics.getStatTrack().getAveUpDist() )); - mTotaleDownText4.setText(String.format("%.0f", Math.abs(typeStatistics.getStatTrack().getAveDownDist()))); - mSportTimeText4.setText( Utils.getTimeCnt(typeStatistics.getStatTrack().getAvsportTime(),false)); -// mPausedTimeText4.setText(Utils.getTimeCnt( typeStatistics.getStatTrack().getAvpause(),false)); - mTotalTimeText4.setText(Utils.getTimeCnt(typeStatistics.getStatTrack().getAvtotalTime(),false)); -// mOffTimeText4.setText(Utils.getTimeCnt( typeStatistics.getStatTrack().getAvoffTime(),false)); - mRdText4.setText(String.format("%.2f",typeStatistics.getStatTrack().getAvmaxR()/1000)); - - mBurnText4.setText( String.format("%.2f",typeStatistics.getStatTrack().getAvBurn())); - mTavsText4.setText( String.format("%.2f",typeStatistics.getStatTrack().getAvTavSpeed())); - - if(typeStatistics.getStatTrack().getAvUpDist()>0){ - ((TextView)vContainer.findViewById(R.id.td_textView_Updist4)).setText(String.format("%.2f",typeStatistics.getStatTrack().getAvUpDist()/1000)); - ((TextView)vContainer.findViewById(R.id.td_textView_downDist4)).setText(String.format("%.2f",typeStatistics.getStatTrack().getAvDownDist()/1000)); - ((TextView)vContainer.findViewById(R.id.td_textView_maxEle4)).setText(String.format("%.0f",typeStatistics.getStatTrack().getAvMaxEle())); - ((TextView)vContainer.findViewById(R.id.td_textView_minEle4)).setText(String.format("%.0f",typeStatistics.getStatTrack().getAvMinEle())); - } - - mKmTime4.setText(Utils.getTimeMS(typeStatistics.getStatTrack().getAvKmTime())); - } - - private void setAVS_DistChart(){ - llcharts = (LinearLayout)vContainer.findViewById(R.id.st_distAvsChart); - llcharts.removeAllViews(); - showCharts(0); - } - - - private void setType_Chart(){ - llcharts = (LinearLayout)vContainer.findViewById(R.id.type_chart); - llcharts.removeAllViews(); - showCharts(1); - } - //type detail chart - private void setTypeSt_Chart(){ - llcharts = (LinearLayout)vContainer.findViewById(R.id.st_type_chart); - llcharts.removeAllViews(); - showCharts(2); - } - - private void setBasicData(){ - - - mCntText.setText(String.format("%s",typeStatistics.getSbs().size()));//typeStatistics.getStatTrack().getCnt())); - mSumDistText.setText(String.format("%.2f",typeStatistics.getStatTrack().getSumDist()/1000)); - mSumSpTimeText.setText(Utils.getTimeCnt(typeStatistics.getStatTrack().getSumSportTime(),false)); - mSumSumEupText.setText(String.format("%.0f",typeStatistics.getStatTrack().getSumEup() )); - mSumSumEdownText.setText(String.format("%.0f", Math.abs(typeStatistics.getStatTrack().getSumEdown()))); - mSumTimeText.setText(Utils.getTimeCnt(typeStatistics.getStatTrack().getSumTotalTime(),false)); - mSumCostText.setText(String.format("%.0f", typeStatistics.getStatTrack().getSumBurn())); - - - if(typeStatistics.getStatTrack().getSumUpDist()>0){ - ((TextView)vContainer.findViewById(R.id.ts_sum_updist)).setText(String.format("%.2f",typeStatistics.getStatTrack().getSumUpDist()/1000)); - ((TextView)vContainer.findViewById(R.id.ts_sum_downdist)).setText(String.format("%.2f",typeStatistics.getStatTrack().getSumDownDist()/1000)); - - } - -// mSumCostText.setText("--"); -// QLog.getLogger().d(dTAG, TAG+" dddddddddddddd STATIC UI typeStatistics.getStatTrack().getSumTotalTime(): " +typeStatistics.getStatTrack().getSumTotalTime()); -// QLog.getLogger().d(dTAG, TAG+" dddddddddddddd STATIC UI typeStatistics.getStatTrack().getSumOff(): " +typeStatistics.getStatTrack().getSumOff()); - - } - - - - - private TextView mStat_SumDistText; - private TextView mStat_SumTimeText; - private TextView mStat_SumSpTimeText; - private TextView mStat_SumSumEupText; - private TextView mStat_SumCostText; - private TextView mStat_SumAVSText; -// private TextView mStat_SumCountText; -// private TextView mStat_SumMostTypeText; -// private LinearLayout ll_statChart; - private ListView filelv; - private void initStatViews(){ - mStat_SumDistText = (TextView) vContainer.findViewById(R.id.sum_distance); - mStat_SumTimeText = (TextView) vContainer.findViewById(R.id.sum_total_time); - mStat_SumSpTimeText = (TextView) vContainer.findViewById(R.id.sum_sport_time); - mStat_SumSumEupText = (TextView) vContainer.findViewById(R.id.sum_eup); - mStat_SumCostText = (TextView) vContainer.findViewById(R.id.sum_Cost); - mStat_SumAVSText = (TextView) vContainer.findViewById(R.id.sum_avs); -// mStat_SumCountText = (TextView) vContainer.findViewById(R.id.sum_count); -// mStat_SumMostTypeText = (TextView) vContainer.findViewById(R.id.sum_mostType); -// ll_statChart =(LinearLayout)vContainer.findViewById(R.id.stat_chart); - - - - /*filelv = (ListView) vContainer.findViewById(R.id.gpxfile_list); - txt_importNote =(TextView) vContainer.findViewById(R.id.fm_notice); - mbtn_refresh =(Button)vContainer.findViewById(R.id.btn_refresh); - mbtn_refresh.setOnClickListener( new OnClickListener() - { - @Override - public void onClick(View v) - { - showGpxFileList(); - } - }); - - mbtn_import =(Button)vContainer.findViewById(R.id.btn_import); - mbtn_import.setOnClickListener( new OnClickListener() - { - @Override - public void onClick(View v) - { - pareseGPX(); - } - });*/ - } - - - private void setStatDesc(){ - /* setNoteMsg(); -// String msg=QiYouConstant.PV_USER_NIK_NAME+" 您还没有运动记录,马上开始吧!"; - String msg= "您还没有运动记录,马上开始吧!"; -// ll_note.setVisibility(View.VISIBLE); -// if(activity.app.isLastTrackExist()|| activity.app.mStatistics!=null && activity.app.mStatistics.getFirstTime()>0 ){ - if(activity.app.isLastTrackExist()|| activity.app.mStatistics!=null && activity.app.mStatistics.getCnt()>0 ){ -// ll_note.setVisibility(View.GONE); - msg =String.format("驴子从%s开始为您服务", Utils.getFormatedTime(activity.app.mStatistics.getFirstTime())); - } - if(TextUtils.isEmpty(notesMsg)) - mNoteText.setText(msg); */ -// showLocalNotes(null); -// ll_statChart.setVisibility(View.VISIBLE); - mStat_SumDistText.setText(String.format(" %.2f", activity.app.mStatistics.getSumDist()/1000)); - mStat_SumTimeText.setText(String.format(" %s", Utils.getTimeCnt(activity.app.mStatistics.getSumTotalTime(),false))); - mStat_SumSpTimeText.setText(String.format(" %s", Utils.getTimeCnt(activity.app.mStatistics.getSumSportTime(),false))); - mStat_SumSumEupText.setText(String.format(" %.1f", activity.app.mStatistics.getSumeUpDist()/1000)); // +activity.app.mStatistics.getSumDownDist())); - mStat_SumCostText.setText(String.format(" %.2f", activity.app.mStatistics.getSumCost()/1000)); - if(activity.app.mStatistics.getSumSportTime()>0) - mStat_SumAVSText.setText(String.format(" %.2f",3600*activity.app.mStatistics.getSumDist()/activity.app.mStatistics.getSumSportTime())); -// mStat_SumCountText.setText(String.valueOf(activity.app.mStatistics.getCnt())); -// mStat_SumMostTypeText.setText(((CItem)activity.app.mStatistics.getTypeUsedLst().get(0)).GetValue()); - - - - - - } - - - private TextView mRecordingDist; - private TextView mRecordingSporttime; - private TextView mRecordingAVS; - private TextView mRecordingBurn; - private TextView mRecordingSpd; - private LinearLayout recordingLL; - private TextView mRecordingNoSpd; - - @Override - public void updateUI(Location location, Boolean isOnPause) { - // TODO Auto-generated method stub -// if(location==null) return; -// setDetails(); - mRecordingDist.setText(String.format("%.2f", activity.app.getRecordingTrack().getTrackBean().getDistance()/1000f));; - mRecordingSporttime.setText( Utils.getTimeCnt(activity.app.getRecordingTrack().getTrackBean().getSportTime(),false)); - mRecordingAVS.setText(String.format("%.2f", activity.app.getRecordingTrack().getTrackBean().getAvs())); - mRecordingBurn.setText(String.format("%.2f", activity.app.getRecordingTrack().getTrackBean().getBurn())); - - String speed="定位中"; -// mRecordingSpd.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); - if(Utils.isLocOfGPS(location)){ - if(location.getSpeed()>0){ - speed =String.format("%.2f", location.getSpeed()*3.6f); -// mRecordingSpd.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END); - mRecordingNoSpd.setVisibility(View.GONE); - mRecordingSpd.setVisibility(View.VISIBLE); - mRecordingSpd.setText(speed); - return; - } - else - speed="静止"; - - }else if(!Utils.isGpsEnabled(activity)){ - speed="GPS关闭"; - } - if( activity.app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.PAUSED){ - speed="暂停"; - } -// if(location!=null)speed =String.format("%.2f", location.getSpeed()*3.6f); - mRecordingSpd.setVisibility(View.GONE); - mRecordingNoSpd.setVisibility(View.VISIBLE); - mRecordingNoSpd.setText(speed); - if(activity.app.mStatistics!=null && typeStatistics !=null) - setDetails(); - } - - private void setVersion(){ - Button updateBtn = (Button) vContainer.findViewById(R.id.readme_btnUpdate); - if(updateBtn==null)return; - updateBtn.setOnClickListener( new OnClickListener() - { - @Override - public void onClick(View v) - { - UpdateManager manager = new UpdateManager(activity.app); - // 检查软件更新 - manager.checkUpdate(); - } - }); - TextView versionName =(TextView)vContainer.findViewById(R.id.readme_version); - versionName.setText(UpdateManager.getVersionName(activity.app)); - - } - - - - - private int footNumber=0; - private boolean isLookingFootMark=false; - private void showMyfoot(){ - if(isLookingFootMark) return; - isLookingFootMark=true; - - if(footNumber>0)return; - ll_ftnote.setVisibility( View.VISIBLE ); - final String footmark = "[我曾经到过地方] "; - mftNoteText.setText(footmark +"正在为您寻找小脚印"); - footNumber=0; - handler = new Handler(){ - @Override - public void handleMessage(Message msg) { - isLookingFootMark=false; - if(msg.what==10){ - if(footNumber>0){ - mftNoteText.setText(String.format( "%s共找到%s只小脚印",footmark,footNumber)); - - zoomToSpan(); -// mMapView.refresh(); - } - else - mftNoteText.setText( footmark +"没有找到小脚印" ); - } - } - }; - -// gpFootPointsOverlay.removeAll(); - - new Thread(){ - @Override - public void run() { - HashMap gpsh= activity.app.mStatistics.getGpList(); - GPItem gp; - for(Integer i:gpsh.keySet()){ - gp= gpsh.get(i); - -// gpFootPointsOverlay.setData(drawFootPoint(gp,gp.getAh())); - -// QLog.getLogger().d(dTAG, String.format(" drawing bear, gp.getAh()%s,gp.getCnt() %s,gp.getLat() %s,gp.getLng()%s", gp.getAh(),gp.getCnt(),gp.getLat(),gp.getLng())); - mBaiduMap.addOverlay( drawFootPoint(gp,100)); - - } - addFootNumber(gpsh.size()); - -// String bearString=""; - QLog.getLogger().d(dTAG, "QiYouConstant.IS_PROCESSING_GEO_FOOTMARK: "+ QiYouConstant.IS_PROCESSING_GEO_FOOTMARK); - try { - while(QiYouConstant.IS_PROCESSING_GEO_FOOTMARK){ - Thread.sleep(1000); - - } - - /*bearString = Utils.readSDFile(QiYouConstant.BEAR_TEXT); - QLog.getLogger().d(dTAG, " bearString: "+ bearString); - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace();*/ - } - catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - /* if(TextUtils.isEmpty(bearString)){ -// mMapView.refresh(); - handler.sendEmptyMessage(10); - return; - }*/ - - /* - String[] gps = bearString.split(";"); - String[] latlon; - addFootNumber(gps.length); - gp = null; - for(String bear:gps){ - latlon=bear.split(","); - if(latlon.length==0)continue; - try{ -// gp= new GPItem(1,new GeoPoint(Double.valueOf(latlon[0]),Double.valueOf(latlon[1]))); - gp= new GPItem(1,Utils.getLatLng(Double.valueOf(latlon[0]),Double.valueOf(latlon[1])),0); - - }catch(NumberFormatException e) { - Utils.logStackTrace(e, TAG); - } - if(gp!=null){ -// gpFootPointsOverlay.setData(drawFootPoint(gp,10)); - QLog.getLogger().d(dTAG, " drawing "+ bear); - mBaiduMap.addOverlay( drawFootPoint(gp,10)); - } - } */ - -// mMapView.refresh(); - handler.sendEmptyMessage(10); - - }}.start(); - - - - - /* new Thread(){ - @Override - public void run() { - - String bearString=""; - try { - while(QiYouConstant.IS_PROCESSING_GEO_FOOTMARK){ - Thread.sleep(100); - } - - bearString = Utils.readSDFile(QiYouConstant.BEAR_TEXT); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if(TextUtils.isEmpty(bearString))return; - String[] gps = bearString.split(";"); - String[] latlon; - GPItem gp = null; - for(String bear:gps){ - latlon=bear.split(","); - if(latlon.length==0)continue; - try{ -// gp= new GPItem(1,new GeoPoint(Double.valueOf(latlon[0]),Double.valueOf(latlon[1]))); - gp= new GPItem(1,Utils.getGeoPoint(Double.valueOf(latlon[0]),Double.valueOf(latlon[1]))); - - }catch(NumberFormatException e) { - Utils.logStackTrace(e, TAG); - } - if(gp!=null) - gpFootPointsOverlay.setData(drawFootPoint(gp,5)); - } - - mMapView.refresh(); - }}.start(); */ - - - } - - - @Override - protected void zoomToSpan(){ - - double nwLat = -90 * 1000000; - double nwLng = 180 * 1000000; - double seLat = 90 * 1000000; - double seLng = -180 * 1000000; - // find bounding lats and lngs - LatLng point; - - - HashMap gps= activity.app.mStatistics.getGpList(); - if(gps.isEmpty())return; - GPItem gp; - for(Integer i:gps.keySet()){ - gp= gps.get(i); - if(gp==null)continue; -// point= gp.getGp(); -// point = Utils.getGeoPoint(gp.getLat(),gp.getLng()); - point = Utils.getLatLng(gp.getLat(),gp.getLng()); - if(point==null)continue; - nwLat = Math.max(nwLat, point.latitude); - nwLng = Math.min(nwLng, point.longitude); - seLat = Math.min(seLat, point.latitude ); - seLng = Math.max(seLng, point.longitude); - } - - - LatLngBounds.Builder builder = new LatLngBounds.Builder(); - -// builder.include( new LatLng(nwLat,nwLng) ); -// builder.include( new LatLng(seLat,seLng) ); - builder.include( new LatLng(nwLat,nwLng) ).include( new LatLng(seLat,seLng) ); - - mBaiduMap.setMapStatus(MapStatusUpdateFactory - .newLatLngBounds(builder.build())); - - /* - GeoPoint target = new GeoPoint((nwLat + seLat) / 2, (nwLng + seLng) / 2); - - int spanLatDelta = (int) (Math.abs(nwLat - seLat) ); - int spanLngDelta = (int) (Math.abs(seLng - nwLng) ); -// QLog.getLogger().d(dTAG, String.format(" spanLatDelta: %s ,spanLngDelta: %s " , spanLatDelta,spanLngDelta )); - - int latDelta= spanLatDelta/100*3; - latDelta =latDelta>12810?12810:latDelta; - int lngDelta= spanLngDelta/100*3; -// QLog.getLogger().d(dTAG, String.format(" latDelta: %s ,lngDelta: %s " , latDelta,lngDelta )); - lngDelta =lngDelta>12810?12810:lngDelta; - spanLatDelta+=latDelta; - spanLngDelta+=lngDelta;*/ -// QLog.getLogger().d(dTAG, String.format(" spanLatDelta latDelta: %s ,lngDelta: %s " , latDelta,lngDelta )); -// QLog.getLogger().dLog(dTAG, String.format(" after delta, spanLatDelta: %s ,spanLngDelta: %s " , spanLatDelta,spanLngDelta )); - -// mMapController.zoomToSpan(spanLatDelta , spanLngDelta ); -// mMapController.animateTo(target); -// mMapView.refresh(); - } - - - - void setUserInfo(){ - ((LinearLayout)vContainer.findViewById(R.id.ll_user_info)).setVisibility(View.VISIBLE); - if(activity.app.user.getUserbean().getId()<=0){ - setUserLinkSpanTxt(((TextView) vContainer.findViewById(R.id.textview_user_name)),-1,"登录"); - ((TextView) vContainer.findViewById(R.id.textView_user_score)).setVisibility(View.GONE); - return; - } - - setUserLinkSpanTxt(((TextView) vContainer.findViewById(R.id.textview_user_name)),activity.app.user.getUserbean().getId(),activity.app.user.getUserbean().getUserName()); -// ((TextView) vContainer.findViewById(R.id.textview_user_name)).setText(activity.app.user.getUserbean().getUserName()/*.getAccount()*/); - ((TextView) vContainer.findViewById(R.id.textView_user_score)).setText(activity.app.user.getUserbean().getScore()+""); -// ((TextView) vContainer.findViewById(R.id.textView_user_order)).setText(activity.app.user.getUserbean().getPaiming()+"");; -// ((TextView) vContainer.findViewById(R.id.textView_user_title)).setText(activity.app.user.getUserbean().getTitle());; - - } - - - - - - - - - //------------------------- more tab--------------------- - - private void initialMoreViews(){ - imgBtnEditUser= (ImageView)vContainer.findViewById(R.id.img_btnEdituser); - imgBtnEditUser.setOnClickListener(ButtonOnClickListener); - - - - btnMoreHistory =(Button)vContainer.findViewById(R.id.btn_more_history); - btnMoreHistory.setOnClickListener(ButtonOnClickListener); - - btnMoreConfigure =(Button)vContainer.findViewById(R.id.btn_more_configure); - btnMoreConfigure.setOnClickListener(ButtonOnClickListener); - - btnMoreOffline =(Button)vContainer.findViewById(R.id.btn_more_offlinemap); - btnMoreOffline.setOnClickListener(ButtonOnClickListener); - - int visible = QiYouConstant.DEVELOPER_MODE ? View.VISIBLE : View.GONE; - btnScan =(Button)vContainer.findViewById(R.id.btn_more_scan); - btnScan.setOnClickListener(ButtonOnClickListener); - btnScan.setVisibility(visible); - - btnMoreScore =(Button)vContainer.findViewById(R.id.btn_more_score); - btnMoreScore.setOnClickListener(ButtonOnClickListener); - btnMoreScore.setVisibility(visible); - - - - - -// ll_myinfo= (LinearLayout)vContainer.findViewById(R.id.ll_myinfo); -// ll_myinfo.setOnClickListener(ButtonOnClickListener); - /* ll_newact= (LinearLayout)vContainer.findViewById(R.id.ll_newact); - ll_newteam= (LinearLayout)vContainer.findViewById(R.id.ll_newteam); - ll_shuoshuo= (LinearLayout)vContainer.findViewById(R.id.ll_shuoshuo); - ll_trackList= (LinearLayout)vContainer.findViewById(R.id.ll_trackList); - ll_shuoshuo.setOnClickListener(ButtonOnClickListener); - ll_newteam.setOnClickListener(ButtonOnClickListener); - ll_newact.setOnClickListener(ButtonOnClickListener); - ll_trackList.setOnClickListener(ButtonOnClickListener);*/ - } - @Override - void showMyinfo(){ - - QLog.getLogger().d(dTAG, String.format("to show user detial %s",activity.app.user.getUserbean().getId())); - - if(activity.app.user.getUserbean().getId()>0){ -// activity.showUserDetails(null,activity.app.user.getUserbean().getId()); -// activity.showUserDetails(activity.app.user.getUserbean() ); - requestUserFromWeb(activity.app.user.getUserbean().getId()); - } - - else - activity.showLogin(); - -// Toast.makeText(activity, "hello this is myinfo",Toast.LENGTH_SHORT); - - } - - @Override - void showNewAction(){ - - activity.showActvity(new Activity_bean()); - } - @Override - void showNewTeam(){ - activity.showGroup(new Group_bean()); - } - - - - - - @Override - @TargetApi(Build.VERSION_CODES.FROYO) - void initialTabhostStyle(TabHost tabhost){ - int height= getResources().getDimensionPixelSize(R.dimen.tab_top_height); - - int width=-1; - TabWidget tabWidget = tabhost.getTabWidget(); - for (int i =0; i < tabWidget.getChildCount(); i++) { -// if( tabWidget.getChildAt(i).getId() == R.id.tab_toolbar)continue; - tabWidget.getChildAt(i).getLayoutParams().height = height; - tabWidget.getChildAt(i).getLayoutParams().width = width; - TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title); - if(tv==null){ - continue; - } - tv.setPadding(2,0,0,5); - if(i>0){ -// tv.setTextColor( getResources().getColorStateList(R.color.lightslategrey)); - tv.setTextColor( getResources().getColorStateList(R.color.darkgray)); -// tv.setTextSize(14); -// tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray); -// tv.setGravity(Gravity.CENTER_VERTICAL); -// tv.setBackgroundColor(Color.BLUE); - ImageView iv = new ImageView(activity); - iv.setScaleType(ImageView.ScaleType.CENTER); - - if(i==1){ - -// iv.setBackgroundResource(R.drawable.icon_chart); - iv.setImageResource(R.drawable.icon_chart); - try{ - ((LinearLayout)tabWidget.getChildAt(i)).setGravity(Gravity.CENTER_VERTICAL); - ((LinearLayout)tabWidget.getChildAt(i)).addView(iv,0); - }catch(ClassCastException e){ - - } - }else if(i==2){ -// ImageView iv = new ImageView(activity); -// iv.setBackgroundResource(R.drawable.icon_footmark); - iv.setImageResource(R.drawable.icon_footmark); - - tv.setPadding(0,0,0,5); - try{ - ((LinearLayout)tabWidget.getChildAt(i)).setGravity(Gravity.CENTER_VERTICAL); - ((LinearLayout)tabWidget.getChildAt(i)).addView(iv,0); - }catch(ClassCastException e){ - - } - } else if(i==3){ -// ImageView iv = new ImageView(activity); -// iv.setBackgroundResource(R.drawable.icon_wall); -// iv.setPadding(0,0,4,0); - tv.setPadding(4,0,0,5); - iv.setImageResource(R.drawable.icon_wall); - try{ - ((LinearLayout)tabWidget.getChildAt(i)).setGravity(Gravity.CENTER_VERTICAL); - ((LinearLayout)tabWidget.getChildAt(i)).addView(iv,0); - }catch(ClassCastException e){ - - } - } - - - }else{ - - - ImageView iv = new ImageView(activity); - iv.setBackgroundResource(R.drawable.icon_statistics); - try{ - ((LinearLayout)tabWidget.getChildAt(i)).setGravity(Gravity.CENTER_VERTICAL); - ((LinearLayout)tabWidget.getChildAt(i)).addView(iv,0); - }catch(ClassCastException e){} - - - /* - tv.setTextColor( getResources().getColorStateList(R.color.darkgray)); -// tv.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); -//// tv.setBackgroundColor(color.darkslategrey) ; -// tv.setGravity(Gravity.CENTER_VERTICAL); - - - if(FirstTabTextColor!=null){ - tv.setTextColor(FirstTabTextColor); - - ImageView iv = new ImageView(activity); - iv.setBackgroundResource(FirstTabBackGround); - - try{ - ((LinearLayout)tabWidget.getChildAt(i)).setGravity(Gravity.CENTER_VERTICAL); - ((LinearLayout)tabWidget.getChildAt(i)).addView(iv,0); - }catch(ClassCastException e){ - - } - } - -// tv.setBackgroundResource(color.darkslategrey); - */ - } - - } -// tabhost.getTabWidget().setStripEnabled(true); - - - } - - - - - - - - - - - - @Override - public void onResume() { - super.onResume(); -// initialStatTracks(); - - /*if( activity.app.isNewLogin){ - activity.app.isNewLogin=false; - this.doQuery(); - }*/ - setFTag(); - if(activity.app.isLastTrackExist()){ - recordingLL.setVisibility( View.VISIBLE ); - updateUI(null,false); - }else - recordingLL.setVisibility( View.GONE); - - activity.app.updateUIstatus(true); - updateUI(null,false); - - /*if(progressDialog!=null && progressDialog.isShowing() && !activity.app.statTrackLoading) - progressDialog.dismiss();*/ -// showGpxFileList(); - setUserInfo(); - - - } - @Override - public void onPause() { - - activity.app.updateUIstatus(false); - - super.onPause(); - } - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return true; - } - @Override - public void setTabOnFiling() { - - maxTabIndex = 2; - MAPVIEW_INDEX=2; - - } - - public int getFootNumber() { - return footNumber; - } - - public void addFootNumber(int footNumber) { - this.footNumber += footNumber; - } - - } - - - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackTabs_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackTabs_fragment.java deleted file mode 100644 index de8138f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackTabs_fragment.java +++ /dev/null @@ -1,2118 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.location.Location; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; -import android.view.ContextMenu; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; -import android.widget.AdapterView; -import android.widget.AdapterView.AdapterContextMenuInfo; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.ScrollView; -import android.widget.SimpleAdapter.ViewBinder; -import android.widget.TabHost; -import android.widget.TabHost.OnTabChangeListener; -import android.widget.TextView; -import android.widget.Toast; - -import com.baidu.mapapi.map.MyLocationData; -import com.baidu.mapapi.model.LatLng; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Media; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.service.TrackDbServiceBackground; -import com.qiyou.mb.android.ui.charts.AbstractChart; -import com.qiyou.mb.android.ui.charts.DistEleChartNoDown; -import com.qiyou.mb.android.ui.charts.DistKmSpeedChart; -import com.qiyou.mb.android.ui.charts.DistSpeedChart; -import com.qiyou.mb.android.utils.ImageLoader; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.mediaStatus; -import com.qiyou.mb.android.utils.enums.mediaType; -import com.qiyou.mb.android.utils.log.QLog; - -@TargetApi(Build.VERSION_CODES.FROYO) -public class TrackTabs_fragment extends WebList_fragment{// TrackMap_fragment { -// public static final String TAG ="com.qiyou.TrackTabs_fragment"; -// public static final String dTAG ="com.qiyou"; - @Override - public void setFTag(){ - TAG="com.qiyou.TrackTabs_fragment"; - } - public static String getFTag(){ - return "com.qiyou.TrackTabs_fragment"; - } - @Override - public String getCurrentTag(){ - return "com.qiyou.TrackTabs_fragment"; - } -// protected SimpleAdapter adapter; - QSimpleAdapter adapter; -// protected MainActivity activity; - ProgressDialog progressDialog ; -// MemorySoftCache picCache; -// ImageLoader IL; -// String trackId; - private List> mData; - private ListView lv = null; - private CheckBox chk_pic; - protected CheckBox chk_showChats; -// View vContainer; - private static final int ITEM_LOC = 1; - private static final int ITEM_LOC_SAVE_SCREEN = 2; -// private static final int ITEM_MODIFY = 2; - private static final int ITEM_ADDPIC = 5; - private static final int ITEM_DELETE = 3; - private static final int ITEM_COMMENT = 4; - - -// RadioGroup rdGroup; -// int fmLevel =0; - boolean showPicOnly ; - boolean isShowCharts ; -// ToggleButton tgShowPic; -// String[] imgUrls; - -// private Handler handler ; -// private ImageView fmMapImg; - protected boolean isShowEdit; - protected String tabData="数据"; - protected String tabMap="地图"; - protected String tabFootmark="足迹"; -// protected final String tabChart="图表"; - protected final String tabEdit="编辑"; - protected final String tabWaypoints="途经点"; - -// com.qiyou.mb.android.ui.fragments.InnerGridView cateLv ; - Button btnNewCate; - EditText editNewCate; - private TextView txtNotice; - -// Track mTrack; - protected LinearLayout llcharts ; - protected CheckBox chk_showGpx; - - -// Button btnExportFm; - public TrackTabs_fragment() { - // TODO Auto-generated constructor stub - } - -/* public static TrackTabs_fragment newInstance(String trackId) - { - TrackTabs_fragment f = new TrackTabs_fragment(); - Bundle args = new Bundle(); - args.putString(QiYouConstant.EXTRA_KEY_ID, trackId); - f.setArguments(args); - return f; - } - */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - setFTag(); - setWorkingTrack(); -// vContainer = inflater.inflate(R.layout.track_fragment, container, false); - initialViews(); -// initViewMap(); - initialTabhost(); - if(!activity.app.playBack) initialFootmark(); -// initialGestureDetector(); - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); -// if(mTrack_bean.getTrackId()>0) drawTrack(); -// drawTrack(); -// picCache = new MemorySoftCache(); -// activity = (MainActivity)getActivity(); -// activity.app.currentActiveFragment =TAG; - - getExtrArgs(); - -// final Activity activity =activity; - - - initalLvs(); - - - - } - - void getExtrArgs(){ - if (getArguments() != null) { -// String Id = getArguments().getString(QiYouConstant.EXTRA_KEY_ID); -// if(Id!=null)trackId =Integer.valueOf(Id); - trackId= getArguments().getInt(QiYouConstant.EXTRA_KEY_ID); - } - } - - - protected void initalLvs(){ - if(activity.app.playBack)return; - - IL = new ImageLoader(activity); - - // 设置在条目上单击监听器 - lv.setOnItemClickListener(itemListener); - // 设置长按事件 - registerForContextMenu(lv); - -// showData(true); -// if(!isPlayback)showFullMap(); -// setListAdapter(adapter); - - if(mTrack_bean==null)return; - - showTabs(mTrack_bean.getTrackId()>0 &&mTrack_bean.getTrackId() ==trackId); - setStaticMap(); - } - - - - void addNotes(List> mData,int level){ - if(txtNotice==null)return; - String notice=""; - if(mData==null || mData.size()==0 ){ - notice="还没有发现小脚印..."; - if(level ==1){ - notice ="没找到详细数据,连接WIFI后会自动生成详细地址数据..."; - }else if(level==2){ - /* if(activity.app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag())) - notice ="没找到照片...长按路点数据可以插入照片" ; - else*/ - notice ="没找到照片...快去拍些亮丽的片片吧" ; - - } - }else{ - notice ="提示: 长按可显示编辑项"; - if(level ==1 - &&( mTrack_bean.getStatus()==TrackStatus.FINISHED && mData.size()<4 - ||mTrack_bean.getStatus()!=TrackStatus.FINISHED && mData.size()<2 - ) - ){ - notice ="没找到详细数据,连接WIFI后会自动生成详细地址数据...";; - }else - if(level==2){ - if(mTrack_bean.getTrackId()>0) - notice ="提示: 点击图片可进入浏览模式,长按可显示编辑项" ; - else - notice ="提示: 长按可显示编辑项" ; - } - } - setNotice(notice); - } - - void setNotice(String notice){ - txtNotice.setText(notice); - } - - @Override - protected void showMapViews(){ - - super.showMapViews(); -// LinearLayout tm_ll_top_txt =(LinearLayout)vContainer.findViewById(R.id.tm_ll_top_txt); -// tm_ll_top_txt.setVisibility( View.VISIBLE ); -// - /* LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.ll_recording_data); -// tm_ll_top_txt.setVisibility(ll.getVisibility()==View.GONE?View.VISIBLE:View.GONE); - if(trackDetail!=null) trackDetail.setVisibility( View.GONE ); - if(btnLocation!=null) - btnLocation.setVisibility(View.GONE); - if(this.btnSaveScreen!=null) - btnSaveScreen.setVisibility(View.VISIBLE); - GridLayout grid_top_txt =(GridLayout)vContainer.findViewById(R.id.grid_top_txt); - if(grid_top_txt!=null)grid_top_txt.setVisibility( View.VISIBLE ); - ((TextView)this.vContainer.findViewById(R.id.tm_top_speed_title)).setText("均速");*/ -// takeMapScreenshot(); - - } - - CheckBox.OnCheckedChangeListener m_checkboxListener =new CheckBox.OnCheckedChangeListener(){ - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - // TODO Auto-generated method stub - - if(buttonView.getId()==R.id.fm_chk_pic) - { - showPicOnly = chk_pic.isChecked(); - switchFootmarkCharts(false); - showFootmarkData(true); - }else if(buttonView.getId()==R.id.fm_chk_charts && chk_showChats.isEnabled()){ - isShowCharts =chk_showChats.isChecked(); -// chk_pic.setEnabled(!isShowCharts); - switchFootmarkCharts(isShowCharts); - if(isShowCharts ){ - showCharts(); - } - - } - } - - - }; - - void switchFootmarkCharts(boolean isShowCharts){ - - if(chk_showChats.isChecked() && !isShowCharts){ - chk_showChats.setEnabled(false); - chk_showChats.setChecked(isShowCharts); - chk_showChats.setEnabled(true); - } - - chk_pic.setVisibility(isShowCharts?View.GONE:View.VISIBLE); - lv.setVisibility(isShowCharts?View.GONE:View.VISIBLE); - txtNotice.setVisibility(isShowCharts?View.GONE:View.VISIBLE); - ((ScrollView)vContainer.findViewById(R.id.td_scrollViewCharts)).setVisibility(isShowCharts?View.VISIBLE:View.GONE); - - } - void initialFootmark(){ - chk_pic = (CheckBox)vContainer.findViewById(R.id.fm_chk_pic); - - boolean showPickOnly = this.mTrack == null || !this.mTrack.isGpx(); - - chk_pic.setChecked(showPickOnly); - chk_pic.setOnCheckedChangeListener(m_checkboxListener); - - showPicOnly =chk_pic.isChecked(); - - - chk_showChats = (CheckBox)vContainer.findViewById(R.id.fm_chk_charts); - chk_showChats.setOnCheckedChangeListener(m_checkboxListener); -// if(trackId==activity.app.getRecordingTrack().getTrackBean().getTrackId() && -// activity.app.getRecordingTrack().getTrackBean().getStatus()== TrackStatus.RECORDING ){ - /* if(mTrack_bean.getStatus()== TrackStatus.RECORDING ){ - chk_showChats.setVisibility(View.VISIBLE); - }*/ - lv = (ListView) vContainer.findViewById(R.id.fm_list); -// fmMapImg =(ImageView)vContainer.findViewById(R.id.fm_staticMap); -// rdGroup = (RadioGroup)vContainer.findViewById(R.id.fm_rdGroup); -// rdGroup.setOnCheckedChangeListener(rdgChanged); - /*tgShowPic = (ToggleButton) vContainer.findViewById(R.id.fm_tgShowPic); - tgShowPic.setChecked(showPic); - tgShowPic.setOnClickListener(new Button.OnClickListener(){ - @Override - public void onClick(View v) { - // ToggleButton.isChecked() – 双状态按钮的按钮状态,根据状态作出对于的事件响应 - showPic = tgShowPic.isChecked(); - QLog.getLogger().d(dTAG, TAG+ " show pic? " +showPic); - showFootmarkData(true); - } - });*/ - txtNotice =(TextView)vContainer.findViewById(R.id.fm_notice); - /* textContainer =(ScrollView)vContainer.findViewById(R.id.td_scrollView); - if(textContainer!=null) - textContainer.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - });*/ - - - - } - - - - protected void onTabClicked(String tabId){ - // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+ tabId ); - activity.isMapActive=false; - - onMyTabChanged(tabId); -// if(tabId.equalsIgnoreCase(tabData)){ -// LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.tab_statistic); -// if(trackDetail!=null) trackDetail.setVisibility( View.GONE ); -// showFootmarkData(true); -// }else - Utils.hideSoftKeyboard(activity); //hide the input soft keys - if(tabId.equalsIgnoreCase(tabFootmark)){ -// LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.tab_trackingdata); -// if(trackDetail!=null) trackDetail.setVisibility( View.GONE ); -// tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null); - showFootmarkData(true); - if(isShowCharts ){ - showCharts(); - } - }else - if(tabId.equalsIgnoreCase(tabData)){ - // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+ "showMapViews()" ); - if(isPlayback)return; - - showMapViews(); -// LinearLayout tabFootmark =(LinearLayout)vContainer.findViewById(R.id.tab_statistic); -// if(tabFootmark!=null) tabFootmark.setVisibility( View.GONE ); - showMapButtons(); -// showCharts(); - // showBasicButtons(); - }/*else - if(tabId.equalsIgnoreCase(tabChart)){ - QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+ "showCharts(2)" ); -// showCharts(0); - showCharts(1); - showCharts(2); -// showMapButtons(); -// showBasicButtons(); - }*/ - else - if(tabId.equalsIgnoreCase(tabMap)){ - activity.isMapActive=true; - // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+ "drawTrack()" ); -// showMapButtons(); - /* if(mTrack_bean.getStatus()==TrackStatus.RECORDING && !canDrawTrack){ - canDrawTrack=true; - isDrawingTrack=false; -// updateUI(null, false); - updateGraphics(null, false); - }*/ - if(mTrack_bean.getStatus()==TrackStatus.RECORDING){ - redrawTrack(); - } - updateMapMarkers(); -// updateUI(null, false); - -// new Thread(){ -// -// @Override -// public void run() { -// drawTrack(); -// }}.start(); -// - } - else - if(tabId.equalsIgnoreCase(tabEdit)){ - // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+ "tabEdit" ); - - validEditButtons(); - setTrackDesc(); - - } - -// else -// if(tabId.equalsIgnoreCase(tabWaypoints)){ -// // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+ "tabWaypoints" ); -// if(mMapView!=null) -// mMapView.refresh(); -// -// } - } - - protected void showCharts(){ - if(mTrack.getTrackBean().getType()==TrackType.GPX && mTrack.getTrackBean().getSvrNumber()==0) - return; - showCharts(0); - showCharts(1); - showCharts(2); - } - - protected void updateMapMarkers(){ - - } - - protected void redrawTrack(){ - // QLog.getLogger().d(dTAG, TAG+ " canDrawTrack? "+ canDrawTrack ); - -// if(!canDrawTrack) - { - canDrawTrack=true; - isDrawingTrack=false; -// updateUI(null, false); - } - drawTrack(); -// drawGpx(); -// updateGraphics(null, false); - } - - protected void initialTabhost(){ - -// TabHost host = (TabHost)vContainer.findViewById(R.id.tabhost); -// host.setup(); - tabhost = (TabHost)vContainer.findViewById(R.id.tabhost); - tabhost.setup(); - // be used as tabId. - //homeSpec.setIndicator(null, getResources().getDrawable(R.drawable.empty_photo)); - - if(!activity.app.playBack){ - TabHost.TabSpec footmarkTab = tabhost.newTabSpec(tabFootmark); - //garbageSpec.setIndicator(null, getResources().getDrawable(R.drawable.empty_photo)); - footmarkTab.setContent(R.id.tab_footmark); - footmarkTab.setIndicator(tabFootmark); - tabhost.addTab(footmarkTab); - }else{ - LinearLayout tabFootmark =(LinearLayout)vContainer.findViewById(R.id.tab_footmark); - if(tabFootmark!=null) tabFootmark.setVisibility( View.GONE ); - } - - -// if(!activity.app.playBack){ - if(isShowEdit){ - /* TabHost.TabSpec editSpec = tabhost.newTabSpec(tabEdit); -// garbageSpec.setIndicator(null, getResources().getDrawable(R.drawable.empty_photo)); - editSpec.setContent(R.id.tab_edit); - editSpec.setIndicator(tabEdit); - tabhost.addTab(editSpec);*/ - }else{ -// ((LinearLayout)vContainer.findViewById(R.id.tab_chart)).setVisibility( View.GONE ); -// ((LinearLayout)vContainer.findViewById(R.id.tab_edit)).setVisibility( View.GONE ); - - } - TabHost.TabSpec mapTab = tabhost.newTabSpec(tabMap); // This param will - mapTab.setIndicator(tabMap); - mapTab.setContent(R.id.tab_map); - tabhost.addTab(mapTab); - - - - if ( !this.isPlayback && mTrack_bean!=null && mTrack_bean.getSvrNumber() > 0){ - - bbsTab = getResources().getString(R.string.tab_bbs);//"云端"; - tabBbs = tabhost.newTabSpec(bbsTab); - tabBbs.setIndicator(bbsTab/*, getResources().getDrawable(R.drawable.icon_user,null)*/); - tabBbs.setContent(R.id.tab_bbs); - tabhost.addTab(tabBbs); - - BBScate =BBSCate.TRACK.toInt() ; - BBSSubcate = mTrack_bean.getSvrNumber(); - BBSSubcateOwner = mTrack_bean.getUserid(); - BBSsubCateName = mTrack_bean.getName(); - } - - - /* TabWidget tabWidget = tabhost.getTabWidget(); - for (int i =0; i < tabWidget.getChildCount(); i++) { - tabWidget.getChildAt(i).getLayoutParams().height = 55; - tabWidget.getChildAt(i).getLayoutParams().width = 65; -// TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title); -// tv.setTextSize(15); -// tv.setTextColor(this.getResources().getColorStateList(android.R.color.white)); - }*/ - - - - initialTabhostStyle(tabhost); - - - tabhost.setOnTabChangedListener(new OnTabChangeListener() { - @Override - public void onTabChanged(String tabId) { - /* if(tabId.equalsIgnoreCase(tabFootmark)){ - tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null); - - - } */ - onTabClicked(tabId); - }} - ); - - } - @Override - void switchTabOptions(int queryType){ - - if (lvWeb == null) { - return; - } - lvWeb.setVisibility(View.GONE); - int tabcnt = tabhost.getTabWidget().getTabCount(); - isBBSQuery = queryType == 3; - } - - protected void drawTrack(){ -// mTrack_bean = activity.app.getCurrentTrack().getTrackBean(); - // QLog.getLogger().d(dTAG, TAG+ " begin to draw track "+ "drawTrack()" ); - - - /* mTrack.getTrackBean().setTrksegs(null); - mTrack.getTrackBean().setRoadWps(null) ; - String trackString=mTrack.toString(); - QLog.getLogger().dLog(dTAG, trackString); - QLog.getLogger().dLog(dTAG, mTrack.getTrackBean().getStartWp().toJsonWp()); - */ - - - - - setWorkingTrack(); - //TODO: check why release apk has no start/lastwp/maxwp - - /* if(mTrack_bean.getStartWp().getWb().getLatitude()==0 &&mTrack_bean.getRoadWps().size()>0){ - mTrack_bean.getStartWp().setWb(mTrack_bean.getRoadWps().get(0)); - mTrack_bean.getLastWp().setWb(mTrack_bean.getRoadWps().get(mTrack_bean.getRoadWps().size()-1)); - }*/ - - updateGraphics(null,false); - - if(!activity.app.playBack) - drawGpx(); - - locationToTrackEnd(); - - } - - protected void locationToTrackEnd(){ - QLog.getLogger().d(dTAG, TAG+ "................drawTrack............ :"+ "locationToTrackEnd()" ); - if(mTrack_bean.getTrackId()<=0)return; - Waypoint_bean wb ;//=mTrack_bean.getMaxDistWp().getWb(); -// wb =mTrack_bean.getMaxDistWp().getWb(); - wb =mTrack_bean.getLastWp().getWb(); - - if(mTrack_bean.getStatus()==TrackStatus.RECORDING - && activity.app.getRecordingTrack().getTrackBean().getTrackId() ==mTrack_bean.getTrackId() - && activity.app.getRecordingTrack().getTrackBean().getStartTime() ==mTrack_bean.getStartTime() - && activity.app.getLocationCached().size()>0 - ){ - Location loc =activity.app.getLocationCached().get(Integer.valueOf(activity.app.getLocationCached().size()-1));//activity.app.lastLocation; -// loc =loc==null?activity.app.getLocationCached().get(Integer.valueOf(activity.app.getLocationCached().size()-1)):loc; - if(loc!=null &&loc.getLatitude()>0 && wb.getTime() draw track end icon"); - setEndIcon(getLatLng(wb)); - /*float nwLat = mTrack_bean.getStartWp().getWb().getLatitude(); - float seLat =mTrack_bean.getMaxDistWp().getWb().getLatitude(); - float seLng = mTrack_bean.getMaxDistWp().getWb().getLongitude(); - float nwLng = mTrack_bean.getStartWp().getWb().getLongitude(); - - final int spanLatDelta = (int) (Math.abs(nwLat - seLat) * 1.1); - final int spanLngDelta = (int) (Math.abs(seLng - nwLng) * 1.1); - - mMapController.zoomToSpan(spanLatDelta, spanLngDelta); - mMapController.zoomToSpan(spanLatDelta, spanLngDelta); - */ - zoomToSpan(null); -// mMapController.animateTo(new GeoPoint( (int) (locData.latitude * 1e6), (int) (locData.longitude * 1e6))); - -// mMapView.refresh(); - /* - mMapController.animateTo(new GeoPoint( (int) (locData.latitude * 1e6), (int) (locData.longitude * 1e6))); - mMapView.refresh(); - */ - top_dist.setText( String.format("%.2f", mTrack_bean.getDistance()/1000.00)); - top_sptime.setText(Utils.getTimeCnt(mTrack_bean.getSportTime(), false) ); -// top_speed.setText("_._"); - if(mSpeedText!=null){ - top_speed.setText(mSpeedText.getText()); - return; - } - float avs =isPlayback?activity.app.getCurrentTrack().getTrackBean().getAvs():mTrack_bean.getAvs(); -// top_speed.setText((avs>0?String.format("%.2f",avs)+"(均速)":"--") ); - top_speed.setText((avs>0?String.format("%.2f",avs):"--") ); - - - } - - - /** - * Fits the map with the passed in points so all points are visible. - * @param mapController MapView controller - * @param points list of points you want the map to contain - */ - /*private Handler handler; - - protected void zoomToSpa1n() { - - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - if (msg.obj != null) { - - CenterGeoPointModel centerGeoPointModel = (CenterGeoPointModel) msg.obj; - - // fit map to points - - mMapView.getController().animateTo( centerGeoPointModel.getCenterGeoPoint()); - - mMapView.getController().zoomToSpan( centerGeoPointModel.getSpanLatDelta() , centerGeoPointModel.getSpanLngDelta() ); -// mMapView.getController().zoomToSpan( centerGeoPointModel.getSpanLatDelta() , centerGeoPointModel.getSpanLngDelta() ); - mMapView.refresh(); - float nwLat = mTrack_bean.getStartWp().getWb().getLatitude(); - float seLat =mTrack_bean.getMaxDistWp().getWb().getLatitude(); - float seLng = mTrack_bean.getMaxDistWp().getWb().getLongitude(); - float nwLng = mTrack_bean.getStartWp().getWb().getLongitude(); - - int spanLatDelta = (int) (Math.abs(nwLat - seLat)* 1e6 * 1.1); - int spanLngDelta = (int) (Math.abs(seLng - nwLng)* 1e6 * 1.1); - mMapView.getController().zoomToSpan(spanLatDelta, spanLngDelta); - GeoPoint center = new GeoPoint( (int)((nwLat + seLat)* 1e6 / 2), (int)((nwLng + seLng)* 1e6 / 2)); - mMapController.animateTo(center); - mMapView.refresh(); - - // set min and max for two points - - } - - - - } }; - - new Thread() { - - public void run() { - - try { - - Thread.sleep(1000); - - } catch (Exception e) { - - } - - int nwLat = -90 * 1000000; - int nwLng = 180 * 1000000; - int seLat = 90 * 1000000; - int seLng = -180 * 1000000; - // find bounding lats and lngs - GeoPoint point; - for(Waypoint_bean wb:mTrack_bean.getRoadWps()){ -// for (GeoPoint point : points) { - if(wb==null)continue; - point=getGeoPoint(wb); - nwLat = Math.max(nwLat, point.getLatitudeE6()); - nwLng = Math.min(nwLng, point.getLongitudeE6()); - seLat = Math.min(seLat, point.getLatitudeE6()); - seLng = Math.max(seLng, point.getLongitudeE6()); - } - GeoPoint center = new GeoPoint((nwLat + seLat) / 2, (nwLng + seLng) / 2); - // add padding in each direction - int spanLatDelta = (int) (Math.abs(nwLat - seLat) ); - int spanLngDelta = (int) (Math.abs(seLng - nwLng) ); - QLog.getLogger().d(dTAG, String.format(" spanLatDelta: %s ,spanLngDelta: %s " , spanLatDelta,spanLngDelta )); - // fit map to points - - Message msg = handler.obtainMessage(); - - msg.obj = new CenterGeoPointModel(spanLatDelta, spanLngDelta, center); - - msg.what = 1; - - handler.sendMessage(msg); - - try { - - Thread.sleep(1000); - - } catch (Exception e) { - - } - handler.sendMessage(msg); -// - }; - - }.start(); - - - } - - class CenterGeoPointModel { - - GeoPoint centerGeoPoint; - - int spanLatDelta; - - int spanLngDelta; - - public CenterGeoPointModel() { - - // TODO Auto-generated constructor stub - - } - - public CenterGeoPointModel(int spanLatDelta, int spanLngDelta, - - GeoPoint centerGeoPoint) { - - this.spanLatDelta = spanLatDelta; - - this.spanLngDelta = spanLngDelta; - - this.centerGeoPoint = centerGeoPoint; - - } - - public GeoPoint getCenterGeoPoint() { - - return centerGeoPoint; - - } - - public void setCenterGeoPoint(GeoPoint centerGeoPoint) { - - this.centerGeoPoint = centerGeoPoint; - - } - - public int getSpanLatDelta() { - - return spanLatDelta; - - } - - public void setSpanLatDelta(int spanLatDelta) { - - this.spanLatDelta = spanLatDelta; - - } - - public int getSpanLngDelta() { - - return spanLngDelta; - - } - - public void setSpanLngDelta(int spanLngDelta) { - - this.spanLngDelta = spanLngDelta; - - } - - } -*/ - - - /* - * get footmark with specified levels. - */ - void getFootmark(){ -// showPic = fmLevel!=1 && tgShowPic.isChecked(); -// mData = activity.app.getCurrentTrack().getFootmark(fmLevel, showPic); - int fmLevel =showPicOnly?2:0; - try{ - mData = mTrack.getFootmark(fmLevel, true); - }catch (Exception e){ - Utils.logStackTrace(e, TAG); - } - if(mData==null){ - mData = new ArrayList>(); - } - addNotes(mData,fmLevel); - } - - void getPicUrls(){ -// if(imgUrls==null) -// imgUrls= activity.app.getCurrentTrack().getPicList(); -// imgUrls= mTrack.getPicList(); -// ValidUrls=mTrack. getWebPicList(0,true);//TODO: to remove. - - - ValidUrls=mTrack.getValidPicList(true); - ValidThumbUrls=mTrack.getValidPicList(false); - - } - - - - - - - protected void showFootmarkData(boolean reLoad){ -// if(!activity.app.playBack &&mTrack.getTrackBean().getTrackId()<=0)return; -// showPic = fmLevel!=1 && tgShowPic.isChecked(); -// if( mTrack.getTrackBean().getStartWp()==null &&(chk_pici !showPic || mTrack.getTrackBean().getMdWps().size()==0 )) return; - if(mTrack_bean.getType()!=TrackType.GPX && mTrack.getTrackBean().getStartWp()==null &&( mTrack.getTrackBean().getMdWps().size()==0 )) return; -// (fmLevel!=2 || fmLevel ==2 && showPic && mTrack.getTrackBean().getMdWps().size()==0 ))return; - - - - if(reLoad)getFootmark(); - - - - - - /* if(fmLevel==2 && mData.size()>0){ - - HashMap data = new HashMap(); - data.put("title","点击图片可进入大图浏览模式" ) ; - data.put("picUrl",null); - data.put("picCmnt",null); - mData.add(0,data); - }*/ - - -// adapter = new SimpleAdapter(activity,mData); - - adapter = new QSimpleAdapter(activity,mData,R.layout.footmark_list_detail, - new String[]{"title","uri","cmnt","time"}, - new int[]{R.id.fm_wp,R.id.fm_img,R.id.fm_imgCmnt,R.id.fm_time}); - - adapter.setViewBinder( new ViewBinder(){ - @Override - public boolean setViewValue(View view, Object data,String textRepresentation) { - - view.setVisibility(View.VISIBLE); - if(data ==null || TextUtils.isEmpty(data.toString())){ - view.setVisibility(View.GONE); - return true; - } - else - if( view instanceof com.qiyou.mb.android.utils.image.QimageView && data instanceof String){ - com.qiyou.mb.android.utils.image.QimageView iv = (com.qiyou.mb.android.utils.image.QimageView) view; - -// iv.getLayoutParams().width= QiYouConstant.SUBNAIL_PIC_SIZE; -// iv.getLayoutParams().height=iv.getLayoutParams().width*QiYouConstant.PV_INT_SCREEN_HEIGHT/QiYouConstant.PV_INT_SCREEN_WIDTH; - QLog.getLogger().dLog(dTAG, " binding footmark pic: "+ data.toString()); - /*if(chk_pic.isChecked()) - IL.DisplayImage((String) data,iv); - iv.setVisibility(chk_pic.isChecked()?View.VISIBLE:View.GONE);*/ - IL.DisplayImage((String) data,iv); - -// iv.setImageBitmap((Bitmap) IL.); - return true; - } else if(view.getId()==R.id.fm_time){ - - view.setVisibility(View.GONE); - return false; //if return true then will no value set to the view. - } - return false; - } - }); - - - lv.setAdapter(adapter); - adapter.setSelectItem(selectedFoodmarkItem); - lv.setSelection(selectedFoodmarkItem); - -// lv.smoothScrollToPosition(selectedFoodmarkItem); -// lv.smoothScrollToPositionFromTop(selectedFoodmarkItem, 50); - } - - - - /* @Override - public void onListItemClick(ListView l, View v, int position, long theid) { - super.onListItemClick(l, v, position, theid); - // activity.app.setCurrentTrack(null); - // Find the ID and Reference of the selected track. - - HashMap a=(HashMap) l.getItemAtPosition(position); - - l.getSelectedView().setBackgroundColor(Color.DKGRAY); - - - - - }*/ - - - - // 条目上单击处理方法. - OnItemClickListener itemListener = new OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, - long id) { - - adapter.setSelectItem(position); - adapter.notifyDataSetInvalidated(); - -// if(fmLevel==2 && mTrack_bean.getTrackId()>0 ){ - if(showPicOnly && mTrack_bean.getTrackId()>0 ){ - getPicUrls(); -// imageBrower(position,imgUrls); - if(ValidUrls.length>0) -// imageBrower(position,ValidUrls);ValidThumbUrls - imageBrower(position,ValidThumbUrls); - } - - - } - - - }; - - private void imageBrower(int position, String[] urls) { - - activity.showImagePagerFragment(position,urls); - - - } - - - // 长按时显示的菜单 - @Override - public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { -/* menu.setHeaderTitle("请选择操作"); - menu.add(0, ITEM_LOC, 0, "地图定位"); - menu.add(0, ITEM_LOC_SAVE_SCREEN, 1, "地图截屏"); -// menu.add(0, ITEM_MODIFY, 1, "编辑"); - menu.add(0, ITEM_DELETE, 2, "删除图片"); - menu.add(0, ITEM_COMMENT, 3, "添加说明");*/ - - menu.setHeaderTitle("请选择操作"); - menu.add(0, ITEM_LOC, 0, "地图定位"); - if(isWebRequest)return; - menu.add(0, ITEM_LOC_SAVE_SCREEN, 1, "地图截屏"); -// menu.add(0, ITEM_MODIFY, 1, "编辑"); - menu.add(0, ITEM_ADDPIC, 2, "添加图片"); - menu.add(0, ITEM_DELETE, 3, "删除图片"); - menu.add(0, ITEM_COMMENT, 4, "添加说明"); - } - - - /*因为在一个Activity中都使用onMenuItemSelected和onContextItemSelected时会冲突, - 也就是说,当有长按弹出菜单的时候,点击菜单的选项响应的是onMenuItemSelected(),如果被 - 点击的Item Id不在 onMenuItemSelected中,事件就不会响应,此时不会再调用onContextItemSelected。 - 这样的话,我们再onContextItemSelected中定义的事件就不会执行,这就是很多人遇到的“onContextItemSelected失效”的原因. - 这个时候,需要在onContextItemSelected做相应的判断,如果执行的事件不在onMenuItemSelected中,就执行onContextItemSelected。 - http://blog.csdn.net/kavensu/article/details/8045041 - */ - - - int selectedFoodmarkItem=-1; - @Override - public boolean onContextItemSelected(MenuItem item) { - final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item - .getMenuInfo(); - // info.targetView得到list.xml中的LinearLayout对象. -// String stuId = ((TextView) info.targetView.findViewById(R.id.fm_wp)).getText().toString(); -// if (!TextUtils.isEmpty(stuId)) { -// int id = Integer.parseInt(stuId); - boolean isSaveScreen=false; - - final boolean isMd =info.targetView.findViewById(R.id.fm_img).getVisibility() ==View.VISIBLE; -// isMd =!TextUtils.isEmpty(stuId); - final String time = ((TextView) info.targetView.findViewById(R.id.fm_time)).getText().toString(); - QLog.getLogger().d(dTAG, TAG+ " time: " +time); - String comment = ((TextView) info.targetView.findViewById(R.id.fm_imgCmnt)).getText().toString(); - selectedFoodmarkItem= info.position; - if(TextUtils.isEmpty(time))return false; - String[] times=time.split(","); - if(times==null ||times.length==0)return false; - - final long targetTime=Long.valueOf(times[times.length-1]); - final long targetCmntTime=Long.valueOf(times[0]); -// final long targetTime=Long.valueOf(times[1]); - switch (item.getItemId()) { - case ITEM_LOC: -// if(info.position==0)break; - // 编辑数据 -// boolean isMd;// =((ImageView) info.targetView.findViewById(R.id.fm_img)).getVisibility() ==View.VISIBLE;// .getDrawable()==null; -// stuId = ((TextView) info.targetView.findViewById(R.id.fm_wp)).getText().toString(); - isSaveScreen=false; - if(!TextUtils.isEmpty(time)) { - locateInMap(time,isMd,isSaveScreen); - } - break; - case ITEM_LOC_SAVE_SCREEN: - isSaveScreen=true; - btnSaveScreen.setVisibility(View.VISIBLE); -// this.btnSaveScreen.setWidth(btnSaveScreen.getWidth()*2); -// this.btnSaveScreen.setHeight(btnSaveScreen.getHeight()*4); - if(!TextUtils.isEmpty(time)) { - locateInMap(time,isMd,isSaveScreen); - } - break; -// case ITEM_MODIFY: -// // 编辑数据 -// toastShow("编辑" + stuId); -// -// break; - case ITEM_DELETE: - // 删除数据 - if(!isMd) return false; -// ArrayList wbs = (isMd? mTrack_bean.getMdWps(): mTrack_bean.getRoadWps()); - /*CopyOnWriteArrayList wbs = mTrack_bean.getMdWps() ; */ - ArrayList wbs = mTrack_bean.getMdWps() ; - QLog.getLogger().d(dTAG, TAG+" udpate wps comment, is MD? "+ isMd); - - for(Waypoint_bean wb :wbs){ - if(wb==null)continue; - if(isMd){ - for(Media md: wb.getMedias()){ - if(md.getTime()==targetTime){ - md.setStatus(mediaStatus.DELETED); - break; - } - } - } -// else if(wb.getTime()==targetTime){ -// wb.setComment( inputServer.getText().toString()); -// QLog.getLogger().d(dTAG, TAG+" udpate wps comment, wb comment:? "+ wb.getComment()); -// //TODO:persist the change. -// break; -// } - - } - - showFootmarkData(true); -// if(isMd) -// mTrack.setMdWps(wbs); -// else -// mTrack.setBearWps(wbs); - - updateWPS(isMd); - - break; - - case ITEM_COMMENT: - // 删除数据 - - - final EditText inputServer = new EditText(activity); - inputServer.setText(comment); - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setTitle("输入说明").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer) - .setNegativeButton("取消", null); - builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int which) { - -// ((TextView) info.targetView.findViewById(R.id.fm_imgCmnt)).setText(inputServer.getText().toString()); - - - - /*CopyOnWriteArrayList wbs = (isMd? mTrack_bean.getMdWps(): mTrack_bean.getRoadWps());*/ - ArrayList wbs = (isMd? mTrack_bean.getMdWps(): mTrack_bean.getRoadWps()); - - // QLog.getLogger().d(dTAG, TAG+" udpate wps comment, is MD? "+ isMd); - - for(Waypoint_bean wb :wbs){ - if(wb==null)continue; - if(isMd){ - for(Media md: wb.getMedias()){ - if(md.getTime()==targetTime){ - md.setComment( inputServer.getText().toString()); - break; - } - } - } - else if(wb.getTime()==targetCmntTime/*targetTime*/){ - wb.setComment( inputServer.getText().toString()); - QLog.getLogger().d(dTAG, TAG+" udpate wps comment, wb comment:? "+ wb.getComment()); - //TODO:persist the change. - break; - } - - } - - showFootmarkData(true); -// if(isMd) -// mTrack.setMdWps(wbs); -// else -// mTrack.setBearWps(wbs); - updateWPS(isMd); - - } - }); - builder.show(); - - - return false; - - case ITEM_ADDPIC: - - getWbsInBetween(time); //get the mdWp - /* if(mTrack_bean.getType()!=TrackType.GPX){ - locateInMap(time,isMd,isSaveScreen); - }*/ - - if(mdWp!=null){ - Waypoint wp = new Waypoint(); - wp.getWb().setLatitude( mdWp.getWb().getLatitude()); - wp.getWb().setLongitude( mdWp.getWb().getLongitude()); - wp.getWb().setTime(mdWp.getWb().getTime()); - wp.getWb().setSumDist( mdWp.getWb().getSumDist()); - wp.getWb().setSpeed( mdWp.getWb().getSpeed()); - wp.getWb().setElevation( mdWp.getWb().getElevation()); - mdWp=wp; - } - - showPicPicker(); - - return false; - default: - break; - } - - - - /* boolean isMd =info.targetView.findViewById(R.id.fm_img).getVisibility() ==View.VISIBLE; -// isMd =!TextUtils.isEmpty(stuId); - String time = ((TextView) info.targetView.findViewById(R.id.fm_time)).getText().toString(); - QLog.getLogger().d(dTAG, TAG+ " time: " +time); - if(!TextUtils.isEmpty(time)) { - locateInMap(time,isMd,isSaveScreen); - } - selectedFoodmarkItem= info.position;*/ - - -// } -// showData(false); - return false; - } - - /* - protected void showPicPicker(){ - Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT - intent.addCategory(Intent.CATEGORY_OPENABLE); - intent.setType("image/jpeg"); - if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){ - startActivityForResult(intent, SELECT_PIC_KITKAT); - }else{ - startActivityForResult(intent, SELECT_PIC); - } - } - - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - - super.onActivityResult(requestCode, resultCode, data); - if(requestCode ==SELECT_PIC_KITKAT ||requestCode ==SELECT_PIC) - if (resultCode == Activity.RESULT_OK) { -// picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH); -// Log.i(TAG, "最终选择的图片="+picPath); -// Bitmap bm = BitmapFactory.decodeFile(picPath); -// imageView.setImageBitmap(bm); - - Uri photoUri = data.getData(); - String path= Utils.getPath(activity,photoUri); - setMD(path,System.currentTimeMillis(),mdWp,mediaType.PIC); - - } - } - */ - - void updateWPS(boolean isMd){ - Intent serviceIntent = new Intent(activity, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_UPDATE_WAYPOINTS, mTrack_bean.getTrackId()); - serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_IS_MD, isMd); - activity.startService(serviceIntent); - } - -// public void toastShow(String text) { -// Toast.makeText( activity , text, 1000).show(); -// } -// - - /* //绑定一个匿名监听器 - OnCheckedChangeListener rdgChanged = new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(RadioGroup arg0, int arg1) { - // TODO Auto-generated method stub - //获取变更后的选中项的ID - int radioButtonId = arg0.getCheckedRadioButtonId(); - //根据ID获取RadioButton的实例 -// RadioButton rb = (RadioButton)activity.findViewById(radioButtonId); - - if(radioButtonId ==R.id.fm_rdStandard){ -// fmLevel=0; -// tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null); - }else if(radioButtonId ==R.id.fm_rdDetail){ -// fmLevel=1; -// tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null); - } - else if(radioButtonId ==R.id.fm_rdPic){ -// fmLevel =2; -// tgShowPic.setChecked(true); -// tgShowPic.setEnabled(false); - - } - else if(radioButtonId ==R.id.fm_rdPicOnly){ - fmLevel =3; - showPic =true; - } - - showFootmarkData(true); - - //更新文本内容,以符合选中项 - - } - }; - */ - @Override - public void updateUI(Location location, Boolean isOnPause){ - /*if(activity.app.currentActiveFragment.equalsIgnoreCase(TrackTabs_fragment.getFTag()) &&!activity.app.playBack) { -// top_dist.setText( String.format("%.2f", mTrack_bean.getDistance()/1000.00)); -// top_sptime.setText(Utils.getTimeCnt(mTrack_bean.getSportTime(), false) ); - return; - }*/ - - super.updateUI(location,isOnPause); - } - - - /* class myadapter extends SimpleAdapter{ - - public myadapter(Context context, List> data, - int resource, String[] from, int[] to) { - super(context, data, resource, from, to); - // TODO Auto-generated constructor stub - } - int[] colors={Color.WHITE,Color.LTGRAY}; - int selectedColor=Color.GRAY; - @Override - public View getView(int position, View convertView, ViewGroup parent){ - View v =super.getView(position, convertView, parent); - v.setBackgroundColor(colors[position%2]); - if (position == selectItem) { - v.setBackgroundColor(selectedColor); - } - return v; - } - public void setSelectItem(int selectItem) { - this.selectItem = selectItem; - } - private int selectItem=-1; - - }*/ - - @Override - protected void setWorkingTrack(){ - mTrack =activity.app.getCurrentTrack(); - mTrack_bean = mTrack.getTrackBean(); - // QLog.getLogger().d(dTAG, " TrackId id:" +trackId +",mTrack_bean id is "+ mTrack_bean.getTrackId()); - } - - - - private List getWbsInBetween(String time){ - String[] times=time.split(","); - long startTime=Long.valueOf(times[0]); - long endTime =times.length>1? Long.valueOf(times[1]):startTime; - // QLog.getLogger().d(dTAG, " startTime:" +Utils.getFormatedTime(startTime) +",endTime id is "+ Utils.getFormatedTime(endTime)); - - - List bwbs =new ArrayList(); - for(Waypoint_bean wb:mTrack_bean.getTrkseg()){ - if(wb==null)continue; - - if(startTime==endTime && wb.getTime()>= endTime){ - bwbs.add(wb); - break; - }else - if(endTime>startTime && wb.getTime()<= endTime && wb.getTime()>=startTime){ - bwbs.add(wb); - // QLog.getLogger().d(dTAG, " wb.getTime():" +Utils.getFormatedTime(wb.getTime())); - } - } - - if(bwbs.size()>0){ - mdWp =new Waypoint(); - mdWp.setWb(bwbs.get(bwbs.size()-1)); - } - return bwbs; - } - - - protected void locateInMap(String time, boolean isMd,boolean isSaveScreen){ - - if(mMapView==null)return; - - if(TextUtils.isEmpty(time))return; - /* String[] times=time.split(","); - long startTime=Long.valueOf(times[0]); - long endTime =times.length>1? Long.valueOf(times[1]):startTime; - QLog.getLogger().d(dTAG, " startTime:" +Utils.getFormatedTime(startTime) +",endTime id is "+ Utils.getFormatedTime(endTime)); -*/// int turnFlag=-100; - Location loc = null; - -// ArrayList wbs =isMd?mTrack_bean.getMdWps():mTrack_bean.getRoadWps(); - - /* List bwbs =new ArrayList(); - for(Waypoint_bean wb:mTrack_bean.getTrkseg()){ - if(wb==null)continue; - - if(startTime==endTime && wb.getTime()>= endTime){ - bwbs.add(wb); - break; - }else - if(endTime>startTime && wb.getTime()<= endTime && wb.getTime()>=startTime){ - bwbs.add(wb); - QLog.getLogger().d(dTAG, " wb.getTime():" +Utils.getFormatedTime(wb.getTime())); - } - }*/ - - List bwbs =getWbsInBetween(time); - - Location endLoc = null; - if(bwbs.size()>=2){ - - drawBearLine(bwbs); - - endLoc= new Location(QiYouConstant.LOCATION_RD_LOC); - endLoc.setLatitude(Utils.getbdLat(bwbs.get(bwbs.size()-1).getLatitude(),bwbs.get(bwbs.size()-1).getLongitude())); - endLoc.setLongitude(Utils.getbdLon(bwbs.get(bwbs.size()-1).getLatitude(),bwbs.get(bwbs.size()-1).getLongitude())); - endLoc.setBearing(bwbs.get(bwbs.size()-1).getBearing()); - endLoc.setAccuracy(bwbs.get(bwbs.size()-1).getAccuracy()); - endLoc.setSpeed(1); - } - else if(bwbs.size()==0) - return; -// screenShotDist =(int) bwbs.get(bwbs.size()-1).getSumDist(); -// mdWp =new Waypoint(); -// mdWp.setWb(bwbs.get(bwbs.size()-1)); -// QLog.getLogger().d(dTAG, TAG+String.format(" get start rd waypoint distanceis %s",screenShotDist)); - loc = new Location(QiYouConstant.LOCATION_RD_LOC); - loc.setLatitude(Utils.getbdLat(bwbs.get(0).getLatitude(),bwbs.get(0).getLongitude())); - loc.setLongitude(Utils.getbdLon(bwbs.get(0).getLatitude(),bwbs.get(0).getLongitude())); -// loc.setBearing(bwbs.get(0).getBearing()); - loc.setAccuracy(bwbs.get(0).getAccuracy()); - loc.setSpeed(1); - - - TabHost host = (TabHost)vContainer.findViewById(R.id.tabhost); - host.setCurrentTabByTag(tabMap); - canLocationMap=true; - - - -// GeoPoint sgp =new GeoPoint((int) (loc.getLatitude()*1E6), (int) (loc.getLongitude()*1E6)); - - LatLng sgp =new LatLng( loc.getLatitude() , loc.getLongitude() ); - - setGeoIcon(sgp,bearStartMarker,R.drawable.icon_bstart); - - String[] times=time.split(","); - long startTime=Long.valueOf(times[0]); - long endTime =times.length>1? Long.valueOf(times[1]):startTime; - - if(startTime==endTime ) - locationInMap(loc); - - if(endLoc!=null){ -// GeoPoint egp =new GeoPoint((int) (endLoc.getLatitude()*1E6), (int) (endLoc.getLongitude()*1E6)); - LatLng egp =new LatLng( endLoc.getLatitude() , endLoc.getLongitude() ); - - setGeoIcon(egp,bearEndMarker,R.drawable.icon_bend); - - locationInMap(endLoc); - } - - /* if(gpFmPointsOverlay==null) - gpFmPointsOverlay =new GraphicsOverlay(mMapView); - gpFmPointsOverlay.setData(drawRoadbookPoint(gp,turnFlag)); - if(!mMapView.getOverlays().contains(gpFmPointsOverlay)) - mMapView.getOverlays().add(gpFmPointsOverlay);*/ - - - - -// mMapView.getCurrentMap(); - if(isSaveScreen) { - Toast.makeText(activity, "提示:截图前,请先调整地图到所需比例、角度,点击'截屏'按钮。", Toast.LENGTH_LONG).show(); -// saveScreen(); - } - } - - - - private void drawBearLine(final List al){ - - /* if(gpBearLinesOverlay==null){ - gpBearLinesOverlay= new GraphicsOverlay(mMapView); - }else{ - gpBearLinesOverlay.getAllGraphics().clear(); - } - mMapView.getOverlays().remove(gpBearLinesOverlay);*/ - new Thread(){ - @Override - public void run() { - - boolean isAsist=!isPlayback && mTrack_bean.getType()!=TrackType.GPX; - if(al.size()<=2) return; - ArrayList gpal= new ArrayList(); - long lastTime =0; - if(gpBearLinesOverlay ==null){ - gpBearLinesOverlay = new LineOverlay(mBaiduMap); - } - gpBearLinesOverlay.removeFromMap(); - gpBearLinesOverlay.getOverlayOptions().clear(); -// synchronized(al) - { - for(Waypoint_bean wb:al){ //java.util.ConcurrentModificationException @Synchronized// there is lock conflict with playback service. use clone to resove. - - if(wb ==null)continue; -// if(wb.getRoadBear()==0)continue; //to only draw bearing points -// QLog.getLogger().d(dTAG,TAG+" time between two waypoints:"+ (wb.getTime()-lastTime)); - if(wb.getTime()0 && wb.getTime() -lastTime > QiYouConstant.MAX_GPS_SPAN*60){ -// QLog.getLogger().d(dTAG,TAG + " QiYouConstant.MAX_GPS_SPAN:"+QiYouConstant.MAX_GPS_SPAN -// + "QiYouConstant.MAX_GPS_SPAN*60:"+QiYouConstant.MAX_GPS_SPAN*60 -// + "QiYouConstant.MAX_GEO_TIME:"+QiYouConstant.MAX_GEO_TIME -// +" time between two waypoints:"+ (wb.getTime()-lastTime)); -// gpBearLinesOverlay.setData(drawLine(getGPs(gpal),isAsist)); -// mBaiduMap.addOverlay(drawLine( gpal,isAsist)); - gpBearLinesOverlay.getOverlayOptions().add(drawLine( gpal,isAsist)); - gpal = new ArrayList(); - gpal.add(gp); - - } else - gpal.add(gp); - - lastTime =wb.getTime(); //to only draw bearing points - - } - -// mBaiduMap.addOverlay(drawLine( gpal,isAsist)); - gpBearLinesOverlay.getOverlayOptions().add(drawLine( gpal,isAsist)); - } - gpBearLinesOverlay.addToMap(); -// gpBearLinesOverlay.setData(drawLine(getGPs(gpal),isAsist)); - - // QLog.getLogger().d(dTAG,TAG+" Draw track finished, it is playback track? " + drawPlayBackTrack); - -// mMapView.getOverlays().add(gpBearLinesOverlay); -// mMapView.refresh(); - //finished the track line, set the flag to true; - }}.start(); - } - - - @Override - protected void showCharts( int chartType){ - if(mTrack ==null)return; - ArrayList trs = new ArrayList(); -// String[] tmp =new String[]{}; -// if(TextUtils.isEmpty(mTrack.getTrackBean().getName()))mTrack.getTrackBean().setName("本次"); - trs.add(mTrack ); - int llid=0; - if(chartType ==0){ - llid=isShowCharts?R.id.td_charts_speedkm:R.id.td_charts_1; - llcharts = (LinearLayout)vContainer.findViewById(llid); - getDistSpeedKmChart(trs); -// return; - } -// geEleCharts(trs); -// geEledBarChart(trs); -// geEleDChart(trs); - else if(chartType ==1){ - - llid=isShowCharts?R.id.td_charts_ele:R.id.td_charts_2; - - llcharts = (LinearLayout)vContainer.findViewById(llid); - getDistEleChart(trs); -// return; - } - else if(chartType ==2){ - - llid=isShowCharts?R.id.td_charts_speed:R.id.td_charts_3; - - llcharts = (LinearLayout)vContainer.findViewById(llid); - getDistSpeedChart(trs); -// return; - } - - - /* if(llcharts!=null){ -// case R.id.td_btnShowChartSpeed1:{ showSpeedKmChart(1) ;break;} -// case R.id.td_btnShowChartKm1:{ showSpeedKmChart(2) ;break;} -// case R.id.td_btnShowChartEle1:{ showSpeedKmChart(3) ;break;} - final int chartToShow=chartType==0?2:chartType==1?3:2; - llcharts.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - showSpeedKmChart( chartToShow); - } - }); - - }*/ - - - - } - - void getDistSpeedChart(ArrayList trs){ - if(mTrack==null) return; - geChart(trs,new DistSpeedChart()); - } - - void getDistSpeedKmChart(ArrayList trs){ - if(mTrack==null) return; - geChart(trs,new DistKmSpeedChart()); - } - - void getDistEleChart(ArrayList trs) - { - if(mTrack==null) return; - -// geChart(trs,new DistEleChart()); - geChart(trs,new DistEleChartNoDown());//no ele down - - - } - /*void geBarCharts(ArrayList trs) - { - if(mTrack==null) return; - geChart(trs,new DistanceSpeedBarChart()); - } - - void getDistCharts(ArrayList trs) - { - if(mTrack==null) return; - geChart(trs,new DistanceChart()); - - } - - void geEleCharts(ArrayList trs) - { - if(mTrack==null) return; - - geChart(trs,new EleChart()); - - - } - - void geEleDChart(ArrayList trs) - { - if(mTrack==null) return; - geChart(trs,new EleDChart()); - - } - void geEledBarChart(ArrayList trs) - { - if(mTrack==null) return; - geChart(trs,new EledBarChart()); - - }*/ - void geChart(ArrayList trs,AbstractChart chart){ - - if(mTrack==null) return; - chart.setTrs(trs); - showCharts(chart.getChartView(activity)); - - } - - - void showCharts(View v) - { - try{ - if(llcharts==null)return; - if(llcharts.getChildCount()>0) - llcharts.removeAllViews(); //this is must. - int height=500; - height =QiYouConstant.PV_INT_SCREEN_WIDTH/2; -// int height=LayoutParams.MATCH_PARENT; - v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,height)); //set the layout, or will not show out - llcharts.addView(v); - }catch (Exception e) - { - Utils.logStackTrace(e, TAG); - } - - } - - - - @Override - void showTabs(boolean isVisible ){ -/* - if(trackId==0)return; - if(tabhost==null)return; - - String title=isVisible?tabData:trackId>0?"数据加载中。。。":tabData;//"定位成功后将自动开始"; - - TextView textview = (TextView)tabhost.getTabWidget().getChildAt(0).findViewById(android.R.id.title); -// textview.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); - textview.setText(title); - int visible = isVisible?View.VISIBLE:View.GONE; - for(int i=1;i0){ - screenShotDist=0; - return; - }*/ - - if(wp!=null &&wp.getWb().getMedias().size()==0){ - wp=null; - return; - } - if(mTrack_bean.getStatus()!=TrackStatus.RECORDING){ - redrawTrack(); - } - if(mTrack_bean.getType()==TrackType.GPX){ return;} - - //for camer a new pic - selectedFoodmarkItem =adapter.getCount()-1; - adapter.setSelectItem(selectedFoodmarkItem); - lv.setSelection(selectedFoodmarkItem); - - - - - } - - protected void setStaticMap(){ - /*if(fmMapImg==null)return; - IL.DisplayImage(mTrack.getStaticMap(),fmMapImg); - if(mTrack.isStaticMapExist()){ - IL.DisplayImage(mTrack.getStaticMap(),fmMapImg); - } - else - fmMapImg.setVisibility(View.GONE);*/ - - } - - protected CheckBox.OnCheckedChangeListener gpxCheckboxListener =new CheckBox.OnCheckedChangeListener(){ - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - QLog.getLogger().d(dTAG, "gpx_checkbox checked?" +chk_showGpx.isChecked()); - if(mTrack_bean==null || mTrack_bean.getTrackId()<=0)return; - activity.app.setGpxShowingTracks(String.valueOf( mTrack_bean.getTrackId()), chk_showGpx.isChecked()); - if(chk_showGpx.isChecked() &&mTrack!=null){ - activity.app.getTrackCache().put(Integer.valueOf(mTrack_bean.getTrackId()), mTrack); - } - } - - }; - - @Override - protected void setTrackDesc(){ - super.setTrackDesc(); - - showCategoryList(cateLv,textContainer); - if(btnNewCate!=null) - this.btnNewCate.setEnabled(trackId>0); - if(btnSave!=null) - this.btnSave.setEnabled(trackId>0); - td_btn_export.setEnabled(trackId>0); - - } - - @Override - public void onResume() { - activity.app.isRouting=false; - super.onResume(); - tabOnresume(); - } - - void tabOnresume(){ -// activity.app.currentActiveFragment =getFTag(); - switchButtonStatus(); - showMapViews(); -// mTrack_bean = activity.app.getCurrentTrack().getTrackBean(); - setWorkingTrack(); -// drawTrack=true; -// drawTrack(); -// mMapView.onResume(); -// if(txtNotice!=null) -// txtNotice.setVisibility((mTrack_bean==null||mTrack_bean.getTrackId()>0)?View.VISIBLE:View.GONE); - -// editNewCate.setSelection(0); -// redrawTrack(); - - } - - @Override - public void onPause() { - - super.onPause(); - } - @Override - public void onDestroy() { - super.onDestroy(); - } - - - - protected void updateGpxEle(){ - - int minDist=200; - - int size =(int) ((mTrack_bean.getDistance())/minDist); - if(size>50) - size=50; - - String gpoints=Utils.buildPathPoints(mTrack_bean.getTrkseg(),mTrack,false,size); - - if(TextUtils.isEmpty(gpoints))return ; - - /* - https://maps.googleapis.com/maps/api/elevation/json - ?locations=39.7391536,-104.9847034|36.455556,-116.866667&key=API_KEY - * - */ - - - String eleUrl="https://maps.googleapis.com/maps/api/elevation/json?locations="; - - eleUrl+=gpoints+"&key="+QiYouConstant.GG_API_KEY+"&sensor=true"; - -// eleUrl="https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034|36.455556,-116.866667&key="+QiYouConstant.GG_API_KEY; -// eleUrl="http://maps.googleapis.com/maps/api/elevation/json?key=AIzaSyBAey0WNbuvc2WeEbCOsGEpp2WW0iw77u0&sensor=true"; - httpsGet(null,eleUrl); - /* - HttpResponse response =activity.app.httpsExecute(eleUrl); - - - if(response==null)return; - - if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ - QLog.getLogger().dLog(dTAG, TAG, " not get result from googleapi for ele."); - return; - } - try { - String strResult = EntityUtils.toString(response.getEntity()); - QLog.getLogger().dLog(dTAG, TAG, " get result from googleapi for ele:"+strResult); - GoogleEleResult ger = null; - - Gson gson = new Gson(); - try{ - if(!TextUtils.isEmpty(strResult)){ - ger = gson.fromJson(strResult, GoogleEleResult.class); - } - }catch(Exception e){ - Utils.logStackTrace(e, dTAG); - return; - } - int lasti=0; - Waypoint_bean wb; - for(LocationEle le:ger.getResults()){ - - while(lasti map = new HashMap(); - JSONObject jsonObj = jsonArr.getJSONObject(i); - map.put("address", jsonObj.getString("formatted_address")); - map.put("icon", jsonObj.getString("icon")); - map.put("name", jsonObj.getString("name")); - System.out.println("查询得到的数据address=" + jsonObj.getString("formatted_address")); - JSONObject locationJsonObj = jsonObj.getJSONObject("geometry").getJSONObject("location"); - map.put("latitude", locationJsonObj.getString("lat")); - map.put("longitude", locationJsonObj.getString("lng")); - listMaps.add(map); - } - }*/ - - - -/* - -@TargetApi(Build.VERSION_CODES.KITKAT) -public void genPDF(){ - - int sysVersion = VERSION.SDK_INT; - - if(sysVersion<19)return; - - // create a new document - PdfDocument document = new PdfDocument(); - - // crate a page description - PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create(); - - // start a page - Page page = document.startPage(pageInfo); - - // draw something on the page - View content = getContentView(); - content.draw(page.getCanvas()); - - // finish the page - document.finishPage(page); -// . . . -// // add more pages -// . . . - // write the document content - document.writeTo(getOutputStream()); - - //close the document - document.close(); - // Create a shiny new (but blank) PDF document in memory - PdfDocument document = new PdfDocument(); - - // crate a page description - PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create(); - - // create a new page from the PageInfo - Page page = document.startPage(pageInfo); - - // repaint the user's text into the page -// View content = findViewById(R.id.textArea); - lv.draw(page.getCanvas()); - // do final processing of the page - document.finishPage(page); - - - } - */ - - -public void createPDF() -{ - /*Document doc = new Document(); - - - try { - String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/droidText"; - - File dir = new File(path); - if(!dir.exists()) - dir.mkdirs(); - - Log.d("PDFCreator", "PDF Path: " + path); - - - File file = new File(dir, "sample.pdf"); - FileOutputStream fOut = new FileOutputStream(file); - - PdfWriter.getInstance(doc, fOut); - - //open the document - doc.open(); - - - Paragraph p1 = new Paragraph("Hi! I am generating my first PDF using DroidText"); - Font paraFont= new Font(Font.COURIER); - p1.setAlignment(Paragraph.ALIGN_CENTER); - p1.setFont(paraFont); - - //add paragraph to document - doc.add(p1); - - Paragraph p2 = new Paragraph("This is an example of a simple paragraph"); - Font paraFont2= new Font(Font.COURIER,14.0f,Color.GREEN); - p2.setAlignment(Paragraph.ALIGN_CENTER); - p2.setFont(paraFont2); - - doc.add(p2); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - Bitmap bitmap = BitmapFactory.decodeResource(activity.getBaseContext().getResources(), R.drawable.ic_launcher); - bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream); - Image myImg = Image.getInstance(stream.toByteArray()); - myImg.setAlignment(Image.MIDDLE); - - //add image to document - doc.add(myImg); - - //set footer - Phrase footerText = new Phrase("This is an example of a footer"); - HeaderFooter pdfFooter = new HeaderFooter(footerText, false); - doc.setFooter(pdfFooter); - - - - } catch (DocumentException de) { - Log.e("PDFCreator", "DocumentException:" + de); - } catch (IOException e) { - Log.e("PDFCreator", "ioException:" + e); - } - finally - { - doc.close(); - }*/ - -} - - - - - - -@Override -void processTabQuery(){ - switchTabOptions(currentTab); - if (isBBSQuery){ - super.processTabQuery(); - } - -} //截断 weblist - - - - - - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Track_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Track_fragment.java deleted file mode 100644 index 13927f0..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/Track_fragment.java +++ /dev/null @@ -1,278 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.os.Bundle; -import android.support.v7.widget.GridLayout; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageButton; -import android.widget.LinearLayout; -import android.widget.TabHost; -import android.widget.TextView; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.WorkingTrackType; - -public class Track_fragment extends TrackTabs_fragment implements IlocationFragment { -// public static final String TAG ="com.qiyou.track_fragment"; -// public static final String dTAG ="com.qiyou"; - @Override - public void setFTag(){ - TAG="com.qiyou.track_fragment"; - } - public static String getFTag(){ - return "com.qiyou.track_fragment"; - } - @Override - public String getCurrentTag(){ - -// QLog.getLogger().e(dTAG,TAG+" Track_fragment, app.currentActiveFragment: "+activity.app.currentActiveFragment); - activity.updateActionBarTitle(R.string.frg_tracking); - return "com.qiyou.track_fragment"; - - - } - - public Track_fragment() { - // TODO Auto-generated constructor stub - workingTrackType= WorkingTrackType.RECORDING; - } - - - - - - public static Track_fragment newInstance(int trackId) - { - - Track_fragment f = new Track_fragment(); - Bundle args = new Bundle(); - args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId); - f.setArguments(args); - return f; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - isShowEdit=false; - if(activity==null){ - activity = (com.qiyou.mb.android.ui.MainActivity)getActivity(); - } - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - vContainer = inflater.inflate(R.layout.track_fragment, container, false); - super. onCreateView( inflater, container, savedInstanceState); - mTrack =activity.app.getRecordingTrack(); -// vContainer = inflater.inflate(R.layout.track_fragment, container, false); -// initialViews(); -// initialTabhost(); -// initialFootmark(); - - initialNaviControlles(); - if(!isPlayback) - chk_showChats.setChecked(true); - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); -// if(!isPlayback)showFullMap(); -// showData(true); - } - - - @Override - protected void initialViews(){ - super.initialViews(); - - td_btnShowChartKm1 = (ImageButton) vContainer.findViewById(R.id.td_btnShowChartKm1); - if(td_btnShowChartKm1!=null) - td_btnShowChartKm1.setOnClickListener(ButtonOnClickListener); - td_btnShowChartSpeed1 = (ImageButton) vContainer.findViewById(R.id.td_btnShowChartSpeed1); - if(td_btnShowChartSpeed1!=null) - td_btnShowChartSpeed1.setOnClickListener(ButtonOnClickListener); - td_btnShowChartEle1 = (ImageButton) vContainer.findViewById(R.id.td_btnShowChartEle1); - if(td_btnShowChartEle1!=null) - td_btnShowChartEle1.setOnClickListener(ButtonOnClickListener); - - btnMapLive.setVisibility(View.VISIBLE); - btnLiveList.setVisibility(View.VISIBLE); - btnMapLoadRoadbook.setVisibility(View.VISIBLE); - - } - @Override - protected void initViewMap() { - - initialMapview(); - initialSportMapViews(); - - } - - - @Override - protected void showMapViews(){ - - super.showMapViews(); -// LinearLayout tm_ll_top_txt =(LinearLayout)vContainer.findViewById(R.id.tm_ll_top_txt); -// tm_ll_top_txt.setVisibility( View.VISIBLE ); - GridLayout grid_top_txt =(GridLayout)vContainer.findViewById(R.id.grid_top_txt); - grid_top_txt.setVisibility( View.VISIBLE ); - if(tabhost!=null && tabhost.getCurrentTabTag().equalsIgnoreCase(tabData)){ - LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.ll_recording_data); - // tm_ll_top_txt.setVisibility(ll.getVisibility()==View.GONE?View.VISIBLE:View.GONE); - trackDetail.setVisibility( View.VISIBLE ); - } - - if(btnLocation!=null)btnLocation.setVisibility(View.VISIBLE); - ((TextView)this.vContainer.findViewById(R.id.tm_top_speed_title)).setText("时速"); -// takeMapScreenshot(); - vContainer.findViewById(R.id.ll_right_btns).setVisibility(View.VISIBLE); - - - this.btnMapLive.setImageResource(QiYouConstant.PV_BL_SHARE_LOCATION? - R.drawable.icon_radio:R.drawable.icon_radio_in); - - // 开启定位图层 - mBaiduMap.setMyLocationEnabled(true); - } - - - @Override - protected void initialTabhost(){ - tabData="运动"; - tabhost = (TabHost)vContainer.findViewById(R.id.tabhost); - tabhost.setup(); - TabHost.TabSpec dataTab = tabhost.newTabSpec(tabData); // This param will be used as tabId. - dataTab.setIndicator(tabData); - dataTab.setContent(R.id.ll_recording_data); - tabhost.addTab(dataTab); - super.initialTabhost(); - initialTabhostStyle(tabhost); - } - - @Override - protected void setWorkingTrack(){ - mTrack =activity.app.getRecordingTrack(); - mTrack_bean = mTrack.getTrackBean(); - } - @Override - protected void updateMapMarkers(){ - /* if( activity.app.lastLocation==null || System.currentTimeMillis()-activity.app.lastLocation.getTime() > QiYouConstant.MAX_GPS_OFF_TIME*5){ - mMapController.setRotation(360); - mMapView.refresh(); - }*/ - - } - - - protected void initialNaviControlles(){ - btnPlaySpeech = (ImageButton) vContainer.findViewById(R.id.navi_btnSpeech); - btnPlaySpeech.setOnClickListener(ButtonOnClickListener); - btnNaviStop = (ImageButton) vContainer.findViewById(R.id.navi_btnStop); - btnNaviStop.setOnClickListener(ButtonOnClickListener); - btnNaviPause = (ImageButton) vContainer.findViewById(R.id.navi_btnPause); - btnNaviPause.setOnClickListener(ButtonOnClickListener); - -// btnPlaySpeech.setImageResource(QiYouConstant.CAN_SPEAK&&QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2?R.drawable.icon_voice:R.drawable.icon_novoice); - - } - - @Override - void stopNavi(){ - - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setTitle("结束导航?").setIcon(android.R.drawable.ic_dialog_info) - .setNegativeButton("取消", null); - builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int which) { - - activity.app.isNaving=false; - ll_navi_progress.setVisibility(View.GONE); - activity.stopNaviService(); - - } - }); - builder.show(); - - - - - - } - @Override - void startPauseNavi(){ - activity.app.isNavPaused =! activity.app.isNavPaused; - - if ( activity.app.isNavPaused) { - txt_nav_info.setText("导航暂停"); - btnNaviPause.setImageResource(R.drawable.icon_plresume); - - } else { - btnNaviPause.setImageResource(R.drawable.icon_plpause); - txt_nav_info.setText("导航继续"); - activity.app.speech("导航继续",1); - } - - - } - - - - - - @Override - public void onResume() { - super.onResume(); - perfomRotate(361); -// activity.updateTabVisibility(false); -// showFullMap(); -// activity.app.currentActiveFragment =getFTag(); -// mTrack_bean = activity.app.getRecordingTrack().getTrackBean(); -// setWorkingTrack(); -// mTrack =activity.app.getRecordingTrack(); -// mMapView.onResume(); -// drawTrack= true; -// if(!isDrawingTrack) isDrawingTrack =false; - -// if(canLocationMap)updateUI(activity.app.lastLocation, false); -// updateMapMarkers() ; - } - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void onPause() { - - super.onPause(); - } - @Override - public void onDestroy() { - super.onDestroy(); - } - @Override - public void setTabOnFiling() { - MAPVIEW_INDEX=2; - maxTabIndex = isShowEdit?3:2; - - } - @Override - protected void setSelectedTab(){ - super.setSelectedTab(); - if( mTrack_bean.getStatus()==TrackStatus.RECORDING &¤tTab==MAPVIEW_INDEX) - redrawTrack(); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackingBasic_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackingBasic_fragment.java deleted file mode 100644 index 955f813..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/TrackingBasic_fragment.java +++ /dev/null @@ -1,2471 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Typeface; -import android.location.Location; -import android.location.LocationManager; -import android.net.Uri; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import android.os.Message; -import android.provider.MediaStore; -import android.text.InputFilter; -import android.text.InputType; -import android.text.TextUtils; -import android.text.format.DateFormat; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; -import android.view.inputmethod.InputMethodManager; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.Spinner; -import android.widget.TextView; -import android.widget.Toast; - -import com.baidu.mapapi.map.BaiduMap; -import com.baidu.mapapi.map.MapView; -import com.baidu.mapapi.map.MyLocationData; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Media; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.service.LocationMornitorService; -import com.qiyou.mb.android.service.TrackDbServiceBackground; -import com.qiyou.mb.android.ui.ChartSpeedKm; -import com.qiyou.mb.android.utils.Exportdb; -import com.qiyou.mb.android.utils.TrackInterface; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.base.IlocationFragment; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.WorkingTrackType; -import com.qiyou.mb.android.utils.enums.mediaType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.image.QimageView; -import com.qiyou.mb.android.utils.log.QLog; -import com.umeng.analytics.MobclickAgent; - -import java.io.File; -import java.util.Calendar; -import java.util.List; -import java.util.Locale; - -//import android.widget.ImageView; -//import com.qiyou.mb.android.utils.TrackInterface.Exporter; - -public class TrackingBasic_fragment extends Querybase_fragment implements IlocationFragment { -// public static final String TAG ="com.qiyou.TrackingBasic_fragment"; -// public static final String dTAG ="com.qiyou"; - @Override - public void setFTag(){ - TAG="com.qiyou.TrackingBasic_fragment"; - } - - protected int currentLayout; - /** - * MapView 是地图主控件 - */ - -// protected ImageLoader IL; - protected MyLocationData locData = null; - /* MyLocationData locData = new MyLocationData.Builder() - .accuracy(location.getRadius()) - // 此处设置开发者获取到的方向信息,顺时针0-360 - .direction(100).latitude(location.getLatitude()) - .longitude(location.getLongitude()).build(); -mBaiduMap.setMyLocationData(locData);*/ - protected Boolean mIsPaused =false; -// Boolean isActive= false; - protected boolean isPlayback =false; -// protected MainActivity activity; -// protected Track mTrack =null;; -// protected Track_bean mTrack_bean =null; - protected Location currentLocation; - protected Location lastLocation; - protected final long update_interval = QiYouConstant.MAX_GPS_SPAN/2*5; -// protected boolean mapviewInitialized =false; -// protected boolean canFinish ; -// ProgressDialog progressDialog ; - private Handler handler ; -// boolean firstLoad; -// protected /*MyLocationOverlay*/ MyLocationData myLocationOverlay = null; - protected LinearLayout liveList; - int alpha=100; - final String CANCEL="取消"; - final String COMPLETE="结束"; - final String CONFIRM ="请再次点击确认"; - WorkingTrackType workingTrackType; - boolean isStartPlay =false; - boolean isPlayPause =false; - boolean isPlaying=false; - protected QimageView staticMapImg; - protected View shareView; - protected Boolean canLocationMap =true;//true; - protected Boolean canRotationMap =true;//true; - public TrackingBasic_fragment() { - // TODO Auto-generated constructor stub - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - -// activity =(MainActivity)getActivity(); - -// if(activity.app!=null)activity.app.currentActiveFragment =TAG; -// currentLayout =R.layout.trackingbasic_fragment; - QLog.getLogger().d(dTAG,TAG+" "+ "onCreate"); -// drawTrack=true; - - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - -// if(vContainer==null) -// vContainer = inflater.inflate(R.layout.trackingbasic_fragment, container, false); - firstLoad=true; - vContainer = inflater.inflate(currentLayout, container, false); - initialViews( ); - mornitorLocations(); -// initialLLViews(); - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - // QLog.getLogger().d(dTAG,TAG+" "+ "onCreateView(), isPlayback: " + activity.app.playBack ); - - trackOnActivityCreated(); - - } - - void trackOnActivityCreated(){ - - setWorkingTrack(); - updateUI(null, false); -// vContainer = inflater.inflate(R.layout.trackingmap_fragment, container, false); - isPlayback = isPlayback||activity.app.playBack; - - if(QiYouConstant.PV_LAST_LAT>0 ){ -// locData.latitude = Utils.getbdLat(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON); -// locData.longitude = Utils.getbdLon(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON); - locData = new MyLocationData.Builder() - .latitude(Utils.getbdLat(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON)) - .longitude(Utils.getbdLon(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON)).build(); - } -// locData = new LocationData(); - - -// if(activity.app.isLastTrackExist()&&btnFinish!=null){ -// btnFinish.setVisibility(View.GONE); -// } - setFinishButtonVisibility(false); - - if(workingTrackType==WorkingTrackType.RECORDING){ - trackId = activity.app.settings.getInt(QiYouConstant.PK_INT_LAST_UNFINISHED_TRACKID,-1); - long lastStart =activity.app.settings.getLong(QiYouConstant.PK_LONG_LAST_TRACK_START,-1); - // QLog.getLogger().dLog(dTAG,TAG+" "+String.format( "onActivityCreated(), trackId:%s ,startTime: %s" , trackId,Utils.getFormatedTime(lastStart)) ); - - - if(lastStart>0 && trackId<=0 ){//&& activity.app.canRecord()){ - // activity.app.initialNewTrack(QiYouConstant.TRACK_TYPE_BIKE); - activity.app.initialNewTrack(TrackType.BIKE); - }else - if(!isPlaying && trackId >0 && activity.app.recordingTrack!=null - && activity.app.recordingTrack.getTrackBean().getTrackId() !=trackId){//01-20 18:59:15.886 18491 18491 E AndroidRuntime: Caused by: java.lang.NullPointerException - - setFinishButtonVisibility(false); - - // progressDialog = ProgressDialog.show(activity, "请稍等...", "获取数据中...", true); - activity.app.restoreLastTracking(); - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog - // progressDialog.dismiss(); - - //更新UI - // switchButtonStatus(); - - if(msg.what==1){ - // Toast.makeText(activity, "查询超时...获取记录数据失败",Toast.LENGTH_SHORT).show(); - setTabhostTitle(); - // setFinishButtonVisibility(true); - - // textview.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); - // textview.setText(title); - - if(btnFinish!=null) { -// btnFinish.setVisibility(View.VISIBLE); - setFinishButtonVisibility(true); - } - }else - { - - setSelectedTrackType(); - - // QLog.getLogger().d(dTAG,TAG+" onActivityCreated(), app.restoreLastTracking()-----done. " ); - -// setTrackDesc(); - showTabs(true); - mIsPaused = mTrack_bean.getStatus() == TrackStatus.PAUSED; - } - updateUI(null,false ) ; - validEditButtons(); -// setTrackDesc(); - }}; - - - new Thread(){ - - @Override - public void run() { - //需要花时间计算的方法 - int topWaiting=0; - // QLog.getLogger().d(dTAG, TAG+ " mTrack_bean.getTrackId():"+mTrack_bean.getTrackId()+", trackId:"+trackId); - while( mTrack_bean.getTrackId() !=trackId){ - try { - // QLog.getLogger().d(dTAG, TAG+ " mTrack_bean.getTrackId():"+mTrack_bean.getTrackId()+", trackId:"+trackId); - Thread.sleep(50); - topWaiting+=50; - if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB ) - { - handler.sendEmptyMessage(1); - return; - // break; - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - - - //向handler发消息 - handler.sendEmptyMessage(0); - }}.start(); - - // Bundle args = new Bundle(); - // args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId); - // setArguments(args); - - Location loc =activity.app.lastLocation ==null?activity.app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER ):activity.app.lastLocation; - if(loc==null||locData==null)return; -// locData.latitude =loc.getLatitude(); -// locData.longitude=loc.getLongitude(); - - locData = new MyLocationData.Builder() - .latitude(loc.getLatitude()) - .longitude(loc.getLongitude()).build(); - -// updateUI(loc,false ) ; - updateUI(null,false ) ; - // QLog.getLogger().d(dTAG,TAG+" "+ "onActivityCreated(), app.restoreLastTracking() " ); - - return; - } - - - } - - if(QiYouConstant.PV_LAST_LAT>0 ){ -// locData.latitude = Utils.getbdLat(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON); -// locData.longitude = Utils.getbdLon(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON); - locData = new MyLocationData.Builder() - .latitude(Utils.getbdLat(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON)) - .longitude(Utils.getbdLon(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON)).build(); - } - - /* if(isPlayback) - { - this.drawTrack(activity.app.currentTrack.getTrackBean()); - playbackTrackDrawed =true; - }*/ - } - - -// private Chronometer tm_chronometer_sport; -// private Chronometer tm_chronometer_pause; - private ProgressBar navi_progress; - protected MapView mMapView = null; - protected TextView mTrackId; - protected TextView mTrackStartTime; - protected TextView mSpeedText; - protected TextView mSportTimeText; - protected TextView mDistanceText; - protected TextView mEleText; - protected TextView mPauseTimeText; -// protected TextView mEleText_up; -// protected TextView mEleText_down; - protected TextView tm_textView_bearing; - protected TextView mTopSpeedText; - protected TextView mAVSspeedText; -// protected TextView mOfftimeText; - protected TextView mCostText; - protected TextView top_sptime;//tm_textView_top_sptime - protected TextView top_dist;//tm_textView_top_dist - protected TextView top_speed; - protected TextView totalTimeText; -// protected TextView maxRText; - protected TextView mTAVSText; - - protected TextView mTrackType; - - protected EditText mNameEdit; - protected TextView mTrackStarTimeText; - protected TextView mTrackEndTimeText; - protected EditText mDescEdit; - protected EditText mCommentEdit; - - - protected Button btnFinish; - protected Button btnPause; -// protected Button btnViewMap; - protected Button btnCamera; - protected ImageButton btnKmpoints; - protected ImageButton btnMapLive; - protected ImageButton btnLiveList; - protected ImageButton btnMapLoadRoadbook; - // protected Button btnTurnPoints; - protected ImageButton btnPlay; - -// protected ImageButton btnPlay; - protected ImageButton btnPlayPause; - protected ImageButton btnPlaySpeech; - - protected ImageButton btnNaviStop; - protected ImageButton btnNaviPause; -// protected Button btnPlayMap; -// protected Button btnPlayPauseMap; -// protected Button btnFullScreen; - protected ImageButton btnLocation; - protected ImageButton btnRotation; - protected ImageButton btnAutoZoom; - protected ImageButton btnSaveScreen; - protected ImageButton btnSataliteMap;//tm_btnSatalite - protected Button btnChartSpeed; - protected Button btnChartDist; - protected Button btnChartEle; - protected Button td_btnPlayback; - protected Button btnNavi; - protected Button btnSNav; - protected Button btnReverse; - protected Button td_btnContinue; - protected Button td_btnShowChartKm; - protected Button td_btnShowChartSpeed; - protected Button td_btnShowChartEle; - protected ImageButton td_btnShowChartKm1; - protected ImageButton td_btnShowChartSpeed1; - protected ImageButton td_btnShowChartEle1; - protected Button td_btn_export; - protected Button btnSave; - protected Button btnDel; - protected Button btnUpload; - protected Button btnShare; - protected Button btnImport; - - protected ImageButton btnMapWayinstruction; - protected ImageButton btnMapPicture; - -// private TextView td_edit_Type; - protected TextView td_track_sumary; - - - -// private LinearLayout ll_note; - private LinearLayout ll_speed_title ; - private LinearLayout ll_recording_control; - private LinearLayout ll_play_control ; - protected LinearLayout ll_navi_progress ; - protected TextView txt_nav_info; - private void initialLLViews(){ - ll_note =(LinearLayout)vContainer.findViewById(R.id.ll_note); - ll_speed_title =(LinearLayout)vContainer.findViewById(R.id.ll_speed_title); - ll_recording_control =(LinearLayout)vContainer.findViewById(R.id.ll_recording_control); - ll_play_control =(LinearLayout)vContainer.findViewById(R.id.ll_playback_control); - ll_navi_progress =(LinearLayout)vContainer.findViewById(R.id.ll_Navi_control); - txt_nav_info=(TextView)vContainer.findViewById(R.id.txt_nav_info); - } - - private void validLLViews(){ -// return; mSpeedText!=null && - - if(ll_note==null|| isPlaying ||mTrack_bean==null )return; - if(mIsPaused){ - mSpeedText.setText(R.string.tracking_pause); - } -// if(mTrack_bean==null)return; -// if(ll_note==null)initialLLViews(); - -// if(mNoteText==null) return; - - boolean showNotes =!Utils.isGpsEnabled(activity)||mTrack_bean.getTrackId()==0; - showNotes= showNotes && !mIsPaused || activity.app.isShowSlidTabs(); - - ll_note.setVisibility(showNotes?View.VISIBLE:View.GONE); - ll_speed_title.setVisibility(showNotes?View.GONE:View.VISIBLE); - if(!showNotes)return; - -// if(mTrack_bean.getTrackId()>0)return; - if(!Utils.isGpsPermited(activity)){ - mNoteText.setText(R.string.permitGPS); - mSpeedText.setText(R.string.GPSNotPermited); - return; - }else - if(!Utils.isGpsEnabled(activity)) { -// ((TextView)vContainer.findViewById(R.id.text_no_gps)).setText(R.string.GPSOFF); - mNoteText.setText(R.string.enableGPS); - mSpeedText.setText(R.string.GPSOFF); - } - else{ - if(activity.app.isShowSlidTabs()){ - mNoteText.setText("提示:往右滑动屏幕可以切换到地图界面"); - return; - } - - mSpeedText.setText(R.string.no_sat_singal); -// ((TextView)vContainer.findViewById(R.id.text_no_gps)).setText(R.string.noSatlite); - mNoteText.setText(R.string.noSatliteDesc); - } - - } - - protected void initialViews( ) - { - -// tm_chronometer_sport =(Chronometer) vContainer.findViewById(R.id.tbs_chronometer_sport); -// tm_chronometer_pause =(Chronometer) vContainer.findViewById(R.id.tbs_chronometer_pause); -// if(workingTrackType!=WorkingTrackType.DETAIL && workingTrackType!=WorkingTrackType.GPX ){ - if(workingTrackType==WorkingTrackType.RECORDING || workingTrackType==WorkingTrackType.PLAYBACK ){ - - navi_progress =(ProgressBar)vContainer.findViewById(R.id.navi_progress); - mTrackId = (TextView) vContainer.findViewById(R.id.tbs_textView_id); - mTrackStartTime = (TextView) vContainer.findViewById(R.id.tbs_textView_starttime); - tm_textView_bearing = (TextView) vContainer.findViewById(R.id.tbs_textView_bearing); - mSpeedText = (TextView) vContainer.findViewById(R.id.tbs_textView_Speed); - mSportTimeText = (TextView) vContainer.findViewById(R.id.tbs_textView_Time); - mDistanceText = (TextView) vContainer.findViewById(R.id.tbs_textView_Distance); - mEleText = (TextView) vContainer.findViewById(R.id.tbs_textView_ele); -// mEleText_up = (TextView) vContainer.findViewById(R.id.tbs_textView_eleUp); - // mEleText_down = (TextView) vContainer.findViewById(R.id.tbs_textView_eleDown); - mPauseTimeText = (TextView) vContainer.findViewById(R.id.tbs_textView_pause); - mTopSpeedText = (TextView) vContainer.findViewById(R.id.tbs_textView_topspeed); - mAVSspeedText = (TextView) vContainer.findViewById(R.id.tbs_textView_avs); - mCostText = (TextView) vContainer.findViewById(R.id.tbs_textView_cost); -// mTrackType =(TextView) vContainer.findViewById(R.id.tbs_textView_trackType); - // mOfftimeText = (TextView) vContainer.findViewById(R.id.tbs_textView_offtime); -// maxRText= (TextView) vContainer.findViewById(R.id.tbs_textView_maxR); - totalTimeText= (TextView) vContainer.findViewById(R.id.tbs_textView_totalTime); - mTAVSText = (TextView) vContainer.findViewById(R.id.tbs_textView_tavs); - mNoteText = (TextView) vContainer.findViewById(R.id.text_note); - // td_edit_Type= (TextView) vContainer.findViewById(R.id.td_edit_Type); - // mNameEdit= (EditText) vContainer.findViewById(R.id.td_edit_Name); - // mSummaryText = (TextView) vContainer.findViewById(R.id.td_textView_TrackSummary); - // mRoadBookText = (TextView) vContainer.findViewById(R.id.td_textView_roadbook);// - // mCommentEdit = (EditText) vContainer.findViewById(R.id.td_edit_comment); - // mDescEdit = (EditText) vContainer.findViewById(R.id.td_edit_desc); - mTrackStarTimeText = (TextView) vContainer.findViewById(R.id.td_textView_Startime); - mTrackEndTimeText = (TextView) vContainer.findViewById(R.id.td_textView_EndTime); - - - - btnPause = (Button) vContainer.findViewById(R.id.tbs_btnPauseTtrack); - - // btnViewMap = (Button) vContainer.findViewById(R.id.tbs_btnViewMap); - - // btnKmpoints=(Button) vContainer.findViewById(R.id.tbs_btnKMpoints); - // btnTurnPoints=(Button) vContainer.findViewById(R.id.tbs_btnTurnPoints); - // btnSaveScreen=(Button) vContainer.findViewById(R.id.tm_btnSaveScreen); - btnPlayPause = (ImageButton) vContainer.findViewById(R.id.pl_btnPauseTtrack); - btnPlay = (ImageButton) vContainer.findViewById(R.id.pl_btnPlayTtrack); - - btnFinish = (Button) vContainer.findViewById(R.id.tbs_btnFinishTtrack); - - - - // btnPlay = (ImageButton) vContainer.findViewById(R.id.pl_btnPlayTtrack); - // btnPlayPauseMap = (Button) vContainer.findViewById(R.id.pl_PauseTtrackMap); - // btnPlayMap = (Button) vContainer.findViewById(R.id.pl_PlayTtrackMap); - if(btnPlay!=null){ - btnPlay.setOnClickListener(ButtonOnClickListener); - btnPlayPause.setOnClickListener(ButtonOnClickListener); - btnPause.setOnClickListener(ButtonOnClickListener); - btnFinish.setOnClickListener(ButtonOnClickListener); - } - - // btnPlayPauseMap.setOnClickListener(ButtonOnClickListener); - // btnPlayMap.setOnClickListener(ButtonOnClickListener); -// btnSave = (Button) vContainer.findViewById(R.id.td_btnSaveTtrack); -// btnSave.setOnClickListener(ButtonOnClickListener); -// - // btnViewMap.setOnClickListener(ButtonOnClickListener); -// btnCamera =(Button) vContainer.findViewById(R.id.tbs_btnCamera); -// btnCamera.setOnClickListener(ButtonOnClickListener); - - //开始/停止按钮 - // btnPause.setOnClickListener( ButtonOnClickListener); - - - - // btnViewCompareChart = (Button) vContainer.findViewById(R.id.td_btnViewCompareChart); - // btnViewCurrentChart = (Button) vContainer.findViewById(R.id.td_btnViewCurrentChart); - - - - } - - - td_btn_export=(Button) vContainer.findViewById(R.id.td_btn_export); - if(td_btn_export!=null){ - td_btn_export.setOnClickListener(ButtonOnClickListener); - } - - mTrackType =(TextView) vContainer.findViewById(R.id.tbs_textView_trackType); - btnCamera =(Button) vContainer.findViewById(R.id.tbs_btnCamera); - if(btnCamera!=null)btnCamera.setOnClickListener(ButtonOnClickListener); - - /*td_btnShowChartKm = (Button) vContainer.findViewById(R.id.td_btnShowChartKm); - if(td_btnShowChartKm!=null) - td_btnShowChartKm.setOnClickListener(ButtonOnClickListener); - td_btnShowChartSpeed = (Button) vContainer.findViewById(R.id.td_btnShowChartSpeed); - if(td_btnShowChartSpeed!=null) - td_btnShowChartSpeed.setOnClickListener(ButtonOnClickListener); - td_btnShowChartEle = (Button) vContainer.findViewById(R.id.td_btnShowChartEle); - if(td_btnShowChartEle!=null) - td_btnShowChartEle.setOnClickListener(ButtonOnClickListener);*/ - - - initialChartViews(); - initTrackTypeSpin(); - initialLLViews(); - - - } - - protected void initialChartViews(){ - -// btnChartSpeed=(Button) vContainer.findViewById(R.id.td_btnChartSpeed); -// btnChartEle=(Button) vContainer.findViewById(R.id.td_btnChartEle); -// btnChartDist=(Button) vContainer.findViewById(R.id.td_btnChartDist); -// btnChartSpeed.setOnClickListener(ButtonOnClickListener); -// btnChartEle.setOnClickListener(ButtonOnClickListener); -// btnChartDist.setOnClickListener(ButtonOnClickListener); - } - - protected OnClickListener ButtonOnClickListener = new OnClickListener() { - @Override - public void onClick(View view) { - switch (view.getId() ){ - case R.id.tbs_btnFinishTtrack: {finishRecordingTrack();break;} -// case R.id.tbs_btnPauseTtrack:{pauseRecordingTrack() ;break;}camerPics() - case R.id.tbs_btnPauseTtrack:{camerPics() ; break;} - case R.id.tbs_btnCamera:{camerPics();break;} -// case R.id.tbs_btnViewMap:{ activity.showTrackDetailMap(null);;break;} - case R.id.tbs_btnKMpoints:{showPoints(1);break;} -// case R.id.tbs_btnTurnPoints:{showPoints(0);break;} -// case R.id.tm_btnFullscreen:{showMapViews();break;} - case R.id.tm_btnLocaiton:{locationInMap(null);break;} - case R.id.tm_btnRotaiton:{roationMap();break;} - case R.id.tm_btnAutozoom:{autoZoomMap();break;} - case R.id.pl_btnPlayTtrack: {startStopPlay(); break;} - case R.id.pl_btnSpeech: {playSpeech(); break;} - case R.id.navi_btnSpeech: {playSpeech(); break;} - - case R.id.pl_btnPauseTtrack:{playbackPause();break;} - case R.id.tm_btnSaveScreen:{saveScreen();break;} - case R.id.tm_btnSatalite:{showSatelliteMap();break;} -// case R.id.pl_PauseTtrackMap:{playbackPause();break;} -// case R.id.pl_PlayTtrackMap:{startStopPlay();break;} -// case R.id.td_btnChartSpeed:{ showCharts(2) ;break;} -// case R.id.td_btnChartEle:{ showCharts(1) ;break;} -// case R.id.td_btnChartDist:{ showCharts(0) ;break;} - case R.id.td_btnPlayback:{playBack() ;break;} - case R.id.td_btnNavi:{startNavi(false) ;break;} - case R.id.rt_btnSNav:{startNavi(true) ;break;} -// case R.id.td_btn_roadbook:{buildRoadBook(true) ;break;} - case R.id.td_btn_export:{exportTrack() ;break;} - case R.id.td_btnContinue:{ continueTrack() ;break;} - case R.id.td_btnShowChartSpeed:{ showSpeedKmChart(1) ;break;} - case R.id.td_btnShowChartKm:{ showSpeedKmChart(2) ;break;} - case R.id.td_btnShowChartEle:{ showSpeedKmChart(3) ;break;} - case R.id.td_btnImport: {importTrack(); break;} - case R.id.td_btnShowChartSpeed1:{ showSpeedKmChart(1) ;break;} - case R.id.td_btnShowChartKm1:{ showSpeedKmChart(2) ;break;} - case R.id.td_btnShowChartEle1:{ showSpeedKmChart(3) ;break;} - - case R.id.td_btnSaveTtrack: {saveTrack(false);break;} - case R.id.td_btnDelTtrack: {updateTrackAvstatus();break;} - case R.id.td_btnUploadTtrack: {uploadTrack(mTrack);break;} - case R.id.td_btnDeleteTtrack: {deleteWebTrack(mTrack);break;} - - - case R.id.td_btnShareTtrack: {shareTrack(mTrack);break;} - case R.id.rt_btnStart:{ setRouteStart() ;break;} - case R.id.rt_btnEnd: {setRouteEnd();break;} - case R.id.rt_btnWps: {setRouteWps();break;} - case R.id.rt_btnTent: {setRouteTent();break;} - case R.id.rt_btnRest: {setRouteRest();break;} - case R.id.rt_btnCheck: {setRouteCheck();break;} - case R.id.rt_btnHand: {setRouteHand();break;} - case R.id.rt_btnCalculate:{routeSearch() ;break;} - case R.id.rt_btnReset: {routeReset();break;} - case R.id.rt_btnSave: {routeSave();break;} - case R.id.tbs_btnwayinstruction: {showWayinstructions();break;} - case R.id.tbs_btnpicture: {showMapPicture();break;} - case R.id.navi_btnStop: {stopNavi();break;} - case R.id.navi_btnPause: {startPauseNavi();break;} - case R.id.rt_btnReverse: {reverseRoute();break;} - case R.id.act_btn_loadRoadbook:{loadRoadBook();break;} - case R.id.btn_location_confirm:{pickLocation();break;} - case R.id.img_btnEdituser:{showMyinfo();break;} -// case R.id.ll_newact:{showNewAction();break;} -// case R.id.ll_newteam:{showNewTeam();break;} -// case R.id.ll_shuoshuo:{activity.showNoteList();break;} -// case R.id.ll_trackList:{activity.showLocalTrackList();break;} -// case R.id.ll_start_place:{pickGeoPlace(view.getId() );break;} -// case R.id.ll_end_place:{pickGeoPlace(view.getId() );break;} - case R.id.act_txt_endGeo_picker:{pickGeoPlace(view.getId() );break;} - case R.id.act_txt_startGeo_picker:{pickGeoPlace(view.getId() );break;} - case R.id.btn_submitAct:{submitSvrObj();break;} - case R.id.btn_SaveAct:{saveSvrObj();break;} - case R.id.act_btn_delRoadbook:{delActBook();break;} - case R.id.act_btn_join:{joinSvrObj();break;} - case R.id.act_btn_refresh:{refresh();break;} - case R.id.act_txt_startGeo_share:{shareEndUrl(R.id.act_txt_startGeo_share);break;} - case R.id.act_txt_endGeo_share:{shareEndUrl(R.id.act_txt_endGeo_share);break;} - case R.id.st_btn_query: { doQuery() ; break; } - case R.id.btn_CateQuery: { doCatesQuery(); break; } - case R.id.btn_WebQuery: { initialWebQuery(); break; } -// case R.id.btn_webpageup: { webPageup(); break; } -// case R.id.btn_webpagedown: { webPagedown(); break; } -// case R.id.loadMoreButton: { loadingMore() ;break;} - case R.id.share_btn_refresh: { doLiveQuery(); break; } - case R.id.share_btn_list: { showShareListOnMap(); break; } - case R.id.share_btn_query: { queryFromShareList(); break; } - case R.id.map_btnLoadRoadbook: { loadRoadBookInMap(); break; } - case R.id.map_btnLive: { switchLive(); break; } - case R.id.map_btnSharelist: { switchLiveList(); break; } - - case R.id.btnHeadDetail: { showObjDetail(); break; } - case R.id.imgTopBanner: { showPicPicker(); break; } - case R.id.user_abulm: { showPicPicker(); break; } - case R.id.act_btn_share: { shareObj(); break; } - case R.id.usr_btn_logout: { logout(); break; } - case R.id.btn_more_history:{activity.showLocalTrackList();break; } - case R.id.btn_more_configure:{activity. startPrefActivity(); break; } - case R.id.btn_more_offlinemap:{activity.showOffline();break;} - case R.id.btn_more_scan:{activity.showScanner();break;} - case R.id.act_btn_qcode:{generateQcode();break;} - - } - - } - }; - void deleteWebTrack(Track track ){ - - if (track.getTrackBean().getSvrNumber() > 0 && track.getTrackBean().getUserid() == activity.app.user.getUserbean().getId()){ - final TrackAvStatus status = TrackAvStatus.DELETED; - mTrack_bean.setAvStatus(status); - - AlertDialog.Builder builder = new Builder(activity); - builder.setMessage("确认删除吗?"); - builder.setTitle("提示"); - builder.setCancelable(false); - builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - - updateTrackStatus(mTrack_bean.getSvrNumber(),status); - - - } - }); - builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - }); - builder.create().show(); - - - - } - - } - void shareObj(){}; - void showObjDetail(){} - void importTrack(){} - void generateQcode(){} - void switchLiveList(){ - liveList =(LinearLayout)vContainer.findViewById(R.id.ll_liveList) ; - LinearLayout leftBtns=(LinearLayout)vContainer.findViewById(R.id.ll_left_btns) ; - boolean toShowLive= liveList.getVisibility()==View.GONE; - liveList.setVisibility(toShowLive?View.VISIBLE:View.GONE); - vContainer.findViewById(R.id.share_ll_list).setVisibility(liveList.getVisibility()); - leftBtns.setVisibility(toShowLive?View.GONE:View.VISIBLE); - // to switch roate/autolocation - - /* if(canLocationMap){ - canLocationMap =!toShowLive; - } - if(canRotationMap){ - canRotationMap =!toShowLive; - } - */ - - if(toShowLive){// hiding list - canLocationMap =false; - canRotationMap =false; - doLiveQuery(); - } - - - if(!toShowLive){// hiding list - roationMap(); - locationInMap(null); - clearLiveItems(); - } - - - btnLiveList.setImageResource(toShowLive? - R.drawable.icon_livelist:R.drawable.icon_livelistoff); - - } - void clearLiveItems(){ - - } - - @Override - RequestParams buildLiveQueryParames(){ - RequestParams params = new RequestParams(); -// final int GEO_CITY_TYPE=2; - -// if(activity.currentAcitiviy==null) return null; - params.add("userId", String.valueOf(activity.app.user.getUserbean().getId())); - params.add("from", String.valueOf(lastMaxLiveTime)); - params.add("isCycle", String.valueOf(true)); - QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - - void switchLive(){ - - QiYouConstant.PV_BL_SHARE_LOCATION = !QiYouConstant.PV_BL_SHARE_LOCATION; - - this.btnMapLive.setImageResource(QiYouConstant.PV_BL_SHARE_LOCATION? - R.drawable.icon_radio:R.drawable.icon_radio_in); - - vContainer.findViewById(R.id.ll_liveshareMsg).setVisibility( View.GONE); - - String msg= QiYouConstant.PV_BL_SHARE_LOCATION? - "直播开始":"直播关闭"; - this.showNotes(msg, true); - - if(!QiYouConstant.PV_BL_SHARE_LOCATION) { - activity.app.saveShareLocationOption(); - return; - } - - - - final EditText inputServer = new EditText(activity); - inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)}); - inputServer.setText(QiYouConstant.PV_STR_SHARE_MSG ); - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setTitle("位置共享,直播说说").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer); -// .setNegativeButton("取消", null); - - /* builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - });*/ - - - builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - - - QiYouConstant.PV_STR_SHARE_MSG = inputServer.getText().toString(); - ((TextView)vContainer.findViewById(R.id.txt_livesharemsg)).setText(QiYouConstant.PV_STR_SHARE_MSG); - vContainer.findViewById(R.id.ll_liveshareMsg).setVisibility(View.VISIBLE); - activity.app.saveShareLocationOption(); - } - }); - builder.show(); - - if (activity.app.user.getUserbean().getId() == 0){ - activity.showLogin(); - - } - } - void loadRoadBookInMap(){ - - - final EditText inputServer = new EditText(activity); - inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20) }); - inputServer.setInputType(InputType.TYPE_CLASS_NUMBER); - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setTitle("请输入云端路书编号").setIcon(R.drawable.icon_roadbook).setView(inputServer) - .setNegativeButton("取消", null); - builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int which) { - - - String s= inputServer.getText().toString(); - if(!TextUtils.isEmpty(s)){ - try{ - int i =Integer.parseInt(s.trim()); - requestTrackFromWeb(i); - Toast.makeText(activity, "正在加载云端路书,路书加载完毕后可以进行路书编辑、导入本地、导航等操作",Toast.LENGTH_LONG).show(); - }catch(Exception e){ - inputServer.setText(""); - showNotes("路书编号输入错误",true); - } - } else{ - showNotes("路书编号输入错误",true); - } - - } - }); - builder.show(); - - - - } - void shareEndUrl(int viewId){} - void refresh(){} - void joinSvrObj(){} - void delActBook(){} - void submitSvrObj(){} - void saveSvrObj(){} - void showNewAction(){} - void showNewTeam(){} - void showMyinfo(){} - void pickLocation(){} - void stopNavi(){} - void reverseRoute(){} - void startPauseNavi(){} - void loadRoadBook(){} - - void pickGeoPlace(int textViewId){ - - - - - - } - void showSpeedKmChart(int type){ - if(mTrack_bean==null)return; - Intent intent = new Intent(activity, ChartSpeedKm.class); - Bundle bundle=new Bundle(); - bundle.putInt("type", type); - bundle.putInt("id", mTrack_bean.getTrackId()); - bundle.putInt("id", trackId); - intent.putExtras(bundle); - activity.startActivity(intent); - - }; - - private void playSpeech(){ - QiYouConstant.PV_INT_NAVI_SPEAK_MODEL=QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2?2:1; - QiYouConstant.CAN_SPEAK=!QiYouConstant.CAN_SPEAK ||QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2; - - setSpeechIcon(); - if(!QiYouConstant.CAN_SPEAK){ - activity.app.stopSpeech(); - } -// else{ -// activity.app.resumeSpeech(); -// } - - } - private void setSpeechIcon(){ - if(btnPlaySpeech!=null){ - QiYouConstant.CAN_SPEAK=QiYouConstant.CAN_SPEAK && Utils.checkSpeechServiceInstall(activity); -// btnPlaySpeech.setImageResource(QiYouConstant.CAN_SPEAK?R.drawable.icon_voice:R.drawable.icon_novoice); - btnPlaySpeech.setImageResource(QiYouConstant.CAN_SPEAK&&QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2?R.drawable.icon_voice:R.drawable.icon_novoice); - - if(!Utils.checkSpeechServiceInstall(activity)){ - Toast toast= Toast.makeText(activity, "语音播报不可用,请安装《讯飞语音+》", Toast.LENGTH_LONG ); - toast.show(); - if(txt_nav_info!=null) - txt_nav_info.setText("导航语音不可用,请安装《讯飞语音+》"); - } -// btnPlaySpeech.setEnabled( Utils.checkSpeechServiceInstall(activity)); - } - } - - protected void showWayinstructions(){} - protected void showMapPicture(){} - - boolean canShowSatellite=false; - protected void showSatelliteMap(){ - if(mMapView==null)return; - canShowSatellite=!canShowSatellite; -// mMapView.setSatellite(canShowSatellite); - mMapView.getMap().setMapType(canShowSatellite?BaiduMap.MAP_TYPE_SATELLITE:BaiduMap.MAP_TYPE_NORMAL); -// btnSataliteMap.setText(canShowSatellite?"平面":"卫星"); - btnSataliteMap.setImageResource(canShowSatellite?R.drawable.flatmap:R.drawable.satellite); - - } - - protected void autoZoomMap(){} - protected void setRouteStart(){} - protected void setRouteWps(){} - protected void setRouteTent(){} - protected void setRouteRest(){} - protected void setRouteCheck(){} - protected void setRouteHand(){} - protected void setRouteEnd(){} - protected void routeSearch(){} - protected void routeReset(){} - protected void routeSave(){} - protected void roationMap(){} - protected void updateTrackAvstatus(){} - - protected void showPoints(final int which){} - protected void showMapViews(){} - protected void locationInMap(Location loc){} - protected void startStopPlay(){} - protected void playbackPause(){} - protected void showCharts(int type){} - protected void playBack(){}; - - protected void startNavi(boolean isSimulation){ - activity.startNaviService(trackId,isSimulation); - /* new Thread(){ - - @Override - public void run() { - activity.startNaviService(trackId,false); - - }}.start(); - */ - - } - - protected void continueTrack(){}; - void showTabs(boolean isVisible ){} - boolean needConfirmToFinish=false; - protected void finishRecordingTrack(){ -// if( !(activity.app.recordingTrack!=null &&activity.app.recordingTrack.getTrackBean().getTrackId()>0)) return; -// btnFinish.setText("结束中。。。"); - needConfirmToFinish =!needConfirmToFinish; - -// final String confirmExist=CONFIRM+(trackId>0?COMPLETE:CANCEL)+"? "; - final String confirmExist=CONFIRM+(trackId>0?COMPLETE:CANCEL)+" "; - setBtnButtonText(confirmExist); -// btnPause.setVisibility(View.GONE); - handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog -// progressDialog.dismiss(); - - if(msg.what==10){ //not confirmed in 5 sec - btnFinish.setEnabled(true); - needConfirmToFinish=false; - updateFinshButonText(); - btnPause.setVisibility(View.VISIBLE); - return; - } - else if(msg.what==20){ //confirmed - btnPause.setVisibility(View.GONE); - needConfirmToFinish=false; - btnFinish.setText((trackId>0?"正在"+COMPLETE:CANCEL)); - btnFinish.setEnabled(false); - btnCamera.setVisibility(View.GONE); - - - new Thread(){ - - @Override - public void run() { - - if(canFinish()){ -// saveScreen(); - long st=System.currentTimeMillis(); -// activity.app.getCurrentTrack().getTrackBean().getType().toInt() , activity.app.getCurrentTrack().getTrackBean().getTrackId() - int trackType =mTrack_bean.getType().toInt(); - int trackId= mTrack_bean.getTrackId(); - activity.finishRecording(); - // QLog.getLogger().dLog(dTAG, "activity.finishRecording() cost time:" +(System.currentTimeMillis()-st)); - if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2) - activity.app.speech("运动结束",1); - int ttwaiting=0; - /*while(ttwaiting<3000 && (activity.app.recordingTrack!=null || activity.app.isLastTrackExist())){*/ - while(ttwaiting<2000 && ( activity.app.isLastTrackExist())){ - try { - Thread.sleep(100); - ttwaiting+=100; - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - // QLog.getLogger().dLog(dTAG, " ttwaiting: " +ttwaiting); - // QLog.getLogger().dLog(dTAG, "before show detail cost time:" +(System.currentTimeMillis()-st)); - activity.showTrackDetail(trackType,trackId ); - }else{ - if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2) - activity.app.speech("运动取消",1); - activity.cancelRecording(); - handler.sendEmptyMessage(30); - } - - - }}.start(); - - -// activity.updateTabTitle(); - } - else if(msg.what==30){ - - activity.updateTabVisibility(true); - - } - - else - { - setBtnButtonText(confirmExist +msg.what); - - } - - - }}; - - - - if(needConfirmToFinish){ -// btnFinish.setText("确认结束?"); - activity.clearRecordingCache(); - new Thread(){ - @Override - public void run() { - int totalWaiting=0; - boolean cleaned=false; - - while(needConfirmToFinish ||!cleaned){ -// setBtnButtonText("确认结束?"); - if(totalWaiting<=5000){ - totalWaiting+=1000; - try{ - - Thread.sleep(1000); - cleaned=true; //make sure the clearRecordingCache() processed -// setBtnButtonText("确认结束? "+totalWaiting/5); - handler.sendEmptyMessage(6- totalWaiting/1000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - else{ - handler.sendEmptyMessage(10); - return; - } - - - } - handler.sendEmptyMessage(20); - }}.start(); - - - return; - } - - } - - - void setBtnButtonText(String text){ - btnFinish.setText(text); - } - - /* protected void pauseRecordingTrack(){ - - mIsPaused = this.mTrack_bean.getStatus() ==TrackStatus.PAUSED; - activity.pausingTrack(!mIsPaused); - if (mIsPaused) { - activity.app.speech("运动继续",2); -// mIsPaused = true; -// activity.pausingTrack(QiYouConstant.TRACK_STATUS_TRACKING); - btnPause.setText("暂停"); - - } else { - - activity.app.speech("运动暂停",2); - btnPause.setText("继续"); - } - - mIsPaused=!mIsPaused; - updateUI(new Location("pause"),false); - - }*/ - - protected Spinner spTrackType; - private ArrayAdapter spAdapter; - class QArrayAdapter extends ArrayAdapter{ - - - public QArrayAdapter(Context context, int textViewResourceId, - List cateList) { - super(context, textViewResourceId, cateList); - // TODO Auto-generated constructor stub - } - @Override - public View getDropDownView(int position, View convertView, - ViewGroup parent) { - TextView v = (TextView) super.getView(position, convertView, - parent); - // v.setMinimumHeight((int) (200* - // getResources().getDisplayMetrics().density)); - - v.setBackgroundResource(R.drawable.linearlayout_horizontal); - - // v.setTextAppearance(activity, R.style.ll_text_view_1); - v.setPadding(5, 8, 5, 8); - int selected = spTrackType.getSelectedItemPosition(); - if (position == selected) { - v.setTypeface(null, Typeface.BOLD); - v.setBackgroundResource(R.drawable.head_linearlayout); - } - // - // v.getPaint().setFlags(0); - // v.setTypeface(null, Typeface.BOLD); - // LayoutParams lp = new LayoutParams(); - - v.setLayoutParams(new android.widget.AbsListView.LayoutParams( - LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); - return v; - } - - /* - @Override - public View getDropDownView(int position, View convertView, ViewGroup parent) { - TextView v =(TextView) super.getView(position, convertView, parent); -// v.setMinimumHeight((int) (200* getResources().getDisplayMetrics().density)); - - v.setBackgroundResource(R.drawable.linearlayout); - -// v.setTextAppearance(activity, R.style.ll_text_view_1); - v.setPadding(5, 8, 5, 8); - int selected = spTrackType.getSelectedItemPosition(); - if(position == selected){ - v.setBackgroundResource(R.drawable.note_linearlayout); - } -// -// v.getPaint().setFlags(0); -// v.setTypeface(null, Typeface.BOLD); -// LayoutParams lp = new LayoutParams(); - - v.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); - return v; - } - */ - - - } - - void initTrackTypeSpin(){ - spTrackType = (Spinner)vContainer.findViewById(R.id.SpinnerTrackType); - if(spTrackType==null)return; - int spinner=workingTrackType==WorkingTrackType.RECORDING?R.layout.thinspinner:R.layout.myspinner; - //将可选内容与ArrayAdapter连接起来 -// spAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.trackType, android.R.layout.simple_spinner_item);\ - spAdapter = QArrayAdapter.createFromResource( getActivity(), Utils.getTrackType()/*R.array.trackType*/, spinner/*R.layout.myspinner*/) ; - - //设置下拉列表的风格 - spAdapter.setDropDownViewResource(R.layout.spinner_item); - - //将adapter2 添加到spinner中 - spTrackType.setAdapter(spAdapter); - - //添加事件Spinner事件监听 - spTrackType.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); - - //设置默认值 -// spTrackType.setVisibility(View.VISIBLE); - - } - protected int oTrackType; //track's original type - class SpinnerXMLSelectedListener implements OnItemSelectedListener{ - @Override - public void onItemSelected(AdapterView spinner, View textView, int spID, - long arg3) { - - if(!firstLoad) - switch (spinner.getId() ){ - case R.id.SpinnerTrackType: { - if(activity.app.playBack)return; -// trackType =spID; - /*oTrackType =activity.app.getRecordingTrack().getTrackBean().getType().toInt(); - activity.app.getRecordingTrack().getTrackBean().setType(TrackType.valueOf(spID)); - activity.app.setLastTracktype(); - mTrackType.setText(spTrackType.getSelectedItem().toString());*/ - oTrackType =mTrack_bean.getType().toInt(); - mTrack_bean.setType(TrackType.valueOf(spID)); - activity.app.setLastTracktype(); - if(mTrackType!=null) - mTrackType.setText(spTrackType.getSelectedItem().toString()); - } - - break; - - case R.id.sp_Web_inputType: { - - webSpinnerSelected(spID); - - - break; - } - - } - else - firstLoad =false; -// isSwitchWebInputOnly =false; - } - - @Override - public void onNothingSelected(AdapterView arg0) { - // TODO Auto-generated method stub - - } - - } - - - void setSelectedTrackType(){ - try{ - if(spTrackType==null)return; - int type=0; - isPlayback =activity.app.getRecordingTrack().getTrackBean().getType().toInt()==TrackType.COPY.toInt(); - if(!isPlayback){ - type = activity.app.getLastTracktype(); - type =type < activity.app.getRecordingTrack().getTrackBean().getType().toInt()? - activity.app.getRecordingTrack().getTrackBean().getType().toInt():type; - }else { - type =type0){ - if(isPlaying ) - topspd =topspd0 -// ||mTrack_bean!=null && - || isPlaying - ){ - - double dist =isPlaying? - location==null?0:(location.getExtras()!=null?location.getExtras().getFloat("dist"):0 ) - :activity.app.sumDist>=mTrack_bean.getDistance() ? - activity.app.sumDist:mTrack_bean.getDistance(); - - mDistanceText.setText( String.format("%.2f", dist/1000f)); - //set ele sumup -// mEleText_up.setText(String.format("%.0f", mTrack_bean.getEsumUp())); -// mEleText_down.setText(String.format("%.2f",recordingTrack.geteDownDist())); - trackId =isPlaying?activity.app.getCurrentTrack().getTrackBean().getTrackId():mTrack_bean.getTrackId(); - mTrackId.setText(String.valueOf(trackId)); - updateFinshButonText(); - long tracktime =isPlaying?location==null?0:(location.getExtras()!=null?location.getExtras().getLong("wptime"):0 ):mTrack_bean.getStartTime(); - - if(isPlaying){ - playbackSumPausetime +=location==null?0:location.getExtras().getLong("pausetime"); - playbackSumOfftime +=location==null?0:location.getExtras().getLong("offtime"); - lastsptime = location==null?0:(location.getExtras()!=null?location.getExtras().getLong("sptime"):0); - mSportTimeText.setText(Utils.getTimeCnt(lastsptime,true)) ; - mPauseTimeText.setText(Utils.getTimeCnt( playbackSumPausetime+playbackSumOfftime ,true)) ; - mTrack_bean.setSportTime(lastsptime); - totalTime =playbackSumOfftime+playbackSumPausetime+lastsptime; - maxR =location==null?0:(location.getExtras()!=null?location.getExtras().getFloat("maxR"):0); - } else - updateTimeView( speed); - - - - if(tracktime>0) - mTrackStartTime.setText(Utils.getFormatedTime(tracktime)); - - double avs =3600*dist/lastsptime; - avs=avs>(isPlaying?topspd:mTrack_bean.getTopSpeed())?0:avs; - mAVSspeedText.setText(avs>0?String.format("%.2f",avs):"--"); - - double tavs=totalTime>0?(float) ( 3600*dist/totalTime):0; - tavs=tavs>avs?avs:tavs; - mTAVSText.setText(tavs>0?String.format("%.2f",tavs):"--"); - -// mOfftimeText.setText(Utils.getTimeCnt(isPlaying?playbackSumOfftime:mTrack_bean.getOffTime(),false));; - - - //set maxR -// maxRText.setText( String.format("%.2f",isPlaying?maxR: mTrack_bean.getMaxR()/1000f)); - - totalTimeText.setText(Utils.getTimeCnt( totalTime)) ; -// long pausetime= totalTime -sptime ;//-mTrack_bean.getOffTime(); -// if(location!=null && location.getSpeed()==0 ||TextUtils.isEmpty(mPauseTimeText.getText())){ - -// mTopSpeedText.setText(String.format("%.2f",isPlaying?topspd:mTrack_bean.getTopSpeed())); - mTopSpeedText.setText(String.format("%.2f",isPlaying?topspd:mTrack_bean.getTopSpeed())); - if(canShowTabs){ - showTabs(true); - canShowTabs=false; - } - - this.mCostText.setText(String.format("%.2f", isPlaying?Utils.getCalories(activity.app.getCurrentTrack().getTrackBean().getType(),avs,lastsptime,0): mTrack.getCalBurn())); - - }else - setWorkingTrack(); - - mIsPaused = mTrack_bean.getStatus() == TrackStatus.PAUSED; - -// mTrack_bean = activity.app.getRecordingTrack().getTrackBean(); - if(location ==null)return; - tm_textView_bearing.setVisibility(View.GONE); - boolean isGPSloc =Utils.isLocOfGPS(location); -// if(isGPSloc){ -// activity.app.lastGPStime=System.currentTimeMillis() ;//location.getTime(); -// QLog.getLogger().d(dTAG,TAG+" "+ "MORNITOR_LOCATION_SERVICE activity.app.lastGPStime:" +activity.app.lastGPStime); -// QLog.getLogger().d(dTAG,TAG+"MORNITOR_LOCATION_SERVICE System.currentTimeMillis() " + System.currentTimeMillis() ); -// // QLog.getLogger().dLog(TAG," Location is here 0111 "); -// } - - if(location.getSpeed()>0){ - speed = location.getSpeed()*3.6f ; -// mTopSpeedText.setText(String.format("%.2f",mTrack_bean.getTopSpeed()));//make sure the showing topspeed is the ever toppest. -// mTopSpeedText.setText(String.format("%.2f",isPlaying?topspd:mTrack_bean.getTopSpeed())); - mSpeedText.setText( String.format("%.2f",speed)) ; -// mSpeedText.setText(String.valueOf(location.getSpeed()*3.6f)) ; -// tm_textView_bearing.setText(String.valueOf(location.getBearing())); - tm_textView_bearing.setVisibility(View.VISIBLE); - tm_textView_bearing.setText(Utils.getBearMsg(location.getBearing(),true)); - mEleText.setText( String.format("%.0f", location.getAltitude())); - }else { - if(isPlaying){ - mSpeedText.setText( "回放就绪") ; - } - else - if(isGPSloc &&(isOnPause || location.getSpeed()==0)) { - if("--".equals(mEleText.getText().toString()) || TextUtils.isEmpty(mEleText.getText().toString())) - mEleText.setText( String.format("%.0f", location.getAltitude())); - - // mSpeedText.setText(isPausing?R.string.tracking_pause:R.string.tracking_auto_pause); - mSpeedText.setText(R.string.tracking_auto_pause); - // tm_textView_bearing.setVisibility(View.GONE); - // tm_textView_bearing.setText(""); -// mEleText.setText( "--"); - if(top_speed!=null) { -// top_speed.setText(String.format("%.2f", mTrack_bean.getAvs()));//+"(均速)"); - top_speed.setText(mSpeedText.getText()); - } - - }else { - mEleText.setText( "--"); - if(!mIsPaused && !Utils.isGpsEnabled(activity)){ - mSpeedText.setText(R.string.GPSOFF); - if(top_speed!=null) { - top_speed.setText(mSpeedText.getText()); - } - // tm_textView_bearing.setVisibility(View.GONE); - } else { - if(mIsPaused|| !isGPSloc || !location.hasSpeed() ){ - mSpeedText.setText(mIsPaused?R.string.tracking_pause: - Utils.isGpsPermited(activity)? R.string.no_sat_singal:R.string.GPSNotPermited); - if(top_speed!=null) { -// top_speed.setText( mAVSspeedText.getText()+"(均速)" ); -// top_speed.setText( mAVSspeedText.getText() ); - top_speed.setText(mSpeedText.getText()); - } - } - } - } - - } - - /*if(TextUtils.isEmpty(mSpeedText.getText())){ - mSpeedText.setText(mIsPaused?R.string.tracking_pause:R.string.no_sat_singal); - }*/ - if(top_dist!=null||top_sptime!=null||top_speed!=null) { - - top_dist.setText(mDistanceText.getText() );// = (TextView) vContainer.findViewById(R.id.tm_textView_top_dist); - - top_sptime.setText(mSportTimeText.getText() ); -// if(location!=null) - top_speed.setText(mSpeedText.getText()); -// else -// top_speed.setText("_._"); - } - -// if(!isPlaying || isPlaying &&location!=null &&location.getExtras()!=null) { - updateMapView(location); -// } - - -// mIsPaused =true; - - // if(isOnPause && mapviewInitialized) { - - - - -// }catch(Exception e) -// { -// Log.e(dTAG,TAG+" updateui error."); -// Utils.logStackTrace(e, dTAG); -// } - -// validLLViews(); -// activity.app.updateStatistics(); - } - - private void updateTimeView(float speed){ - -// QLog.getLogger().d(dTAG, TAG+" get totalTime,mIsPaused"+mIsPaused +"--------------------------------->"); - if(mTrack_bean.getStartTime()==0)return; - - long manualPaused =activity.app.getPausedTime(false); -// totalTime=mIsPaused?mTrack_bean.getTotalTime():System.currentTimeMillis() -mTrack_bean.getStartTime()-manualPaused; -// totalTime = System.currentTimeMillis() -mTrack_bean.getStartTime()-manualPaused; -// totalTime =totalTime<=0?lastsptime+lastpausetime:totalTime; - totalTime = System.currentTimeMillis() -mTrack_bean.getStartTime()-manualPaused; - totalTime =totalTime-lastsptime>0?totalTime:System.currentTimeMillis() -mTrack_bean.getStartTime(); - -// QLog.getLogger().dLog(dTAG, TAG+" get totalTime,mTrack_bean.getStartTime()"+Utils.getFormatedTime(mTrack_bean.getStartTime()) ); -// QLog.getLogger().dLog(dTAG, TAG+" get totalTime:"+totalTime+Utils.getTimeCnt(totalTime) +" ,manualPaused:"+Utils.getTimeCnt(manualPaused)); -// totalTime = mTrack_bean.getStartTime()>0 && totalTime>0? totalTime :0; - if(speed>0){ - lastsptime = totalTime - lastpausetime; -// lastsptime=lastsptime>=0?lastsptime:0; - }else if(speed==0 ||TextUtils.isEmpty(mPauseTimeText.getText())){ - lastpausetime =totalTime - lastsptime; - mPauseTimeText.setText(Utils.getTimeCnt( lastpausetime,true)) ; - } - - mSportTimeText.setText(Utils.getTimeCnt(lastsptime,true)) ; - // QLog.getLogger().d(dTAG, TAG+" get totalTime:"+Utils.getTimeCnt(totalTime) +" ,manualPaused:"+Utils.getTimeCnt(manualPaused)); - // QLog.getLogger().d(dTAG, TAG+" get totalTime:"+Utils.getTimeCnt(totalTime) +" get lastsptime:"+ lastsptime +" get lastpuasetime:"+ lastsptime+ " mTrack_bean.getStartTime():" +mTrack_bean.getStartTime()); - - totalTime=totalTime0; - } - - protected void switchButtonStatus(){ - - // QLog.getLogger().d(dTAG,TAG+" "+"xxxxxxxxxx xxxxxxxxxxxx switchButtonStatus.xxxxxxxxxxxxxxxxxxxxxx" ); - - /* if( btnPause!=null && activity.app.recordingTrack!=null){ - if(activity.app.recordingTrack.getTrackBean().getStatus() == TrackStatus.PAUSED) - btnPause.setText("继续"); - else - btnPause.setText("暂停"); - int visibility =activity.app.recordingTrack.getTrackBean().getTrackId()>0?View.VISIBLE:View.GONE; - btnPause.setVisibility(visibility); - } */ -// -// if( activity.app.recordingTrack!=null && activity.app.recordingTrack.getTrackBean().getTrackId()==0) -// tm_btnCamera.setVisibility(View.GONE); - if(activity.app.playBack){ - - showPlaybackButtons(); - return; - } - else - showMapButtons(); -// else{ -// if(activity.app.currentActiveFragment.equalsIgnoreCase(TrackingBasic_fragment.TAG) ){ -// showBasicButtons(); -// -// -// }else -// if(activity.app.currentActiveFragment.equalsIgnoreCase(Tracking_fragment.TAG) ){ -// showMapButtons(); -// } -// -// if(btnPause!=null) -// btnPause.setVisibility(View.GONE); -// - /* if(btnPlayPause!=null) - btnPlayPause.setVisibility(View.GONE); - - if(btnPlay!=null) - btnPlay.setVisibility(View.GONE); */ - - if(btnFinish!=null){ - -// canFinish =activity.app.recordingTrack!=null &&activity.app.recordingTrack.getTrackBean().getTrackId()>0; -// btnFinish.setEnabled(canFinish); -// String title=(String) btnFinish.getText(); - String title =canFinish()?"结束":"取消"; - btnFinish.setText(title); - } - - validEditButtons(); -// } - -// } - - } - - /*protected void showBasicButtons(){ - if( btnTurnPoints!=null) - btnTurnPoints.setVisibility(View.GONE); -// if( btnFullScreen!=null) -// btnFullScreen.setVisibility(View.GONE); - if( btnLocation!=null) - btnLocation.setVisibility(View.GONE); - if( btnKmpoints!=null) - btnKmpoints.setVisibility(View.GONE); -// if(this.btnViewMap!=null) -// btnViewMap.setVisibility(View.GONE); - if(this.btnSaveScreen!=null) - btnSaveScreen.setVisibility(View.GONE); - }*/ - - protected void showMapButtons(){ - -// if( btnTurnPoints!=null) -// btnTurnPoints.setVisibility(View.GONE); -// if(this.btnFullScreen!=null) -// btnFullScreen.setVisibility(View.VISIBLE); - if(this.btnLocation!=null){ - btnLocation.setVisibility(View.VISIBLE); - btnLocation.getBackground().setAlpha(alpha); - } - if(this.btnKmpoints!=null){ - btnKmpoints.setVisibility(View.VISIBLE); - btnKmpoints.getBackground().setAlpha(alpha); - } - if(this.btnRotation!=null){ - btnRotation.setVisibility(View.VISIBLE); - btnRotation.getBackground().setAlpha(alpha); - } - - if(this.btnAutoZoom!=null){ - btnAutoZoom.setVisibility(View.VISIBLE); - btnAutoZoom.getBackground().setAlpha(alpha); - } - - -// if(this.btnViewMap!=null) -// btnViewMap.setVisibility(View.GONE); - if(this.btnSaveScreen!=null){ - btnSaveScreen.setVisibility(View.VISIBLE); - btnSaveScreen.getBackground().setAlpha(alpha); - } - - if(this.btnSataliteMap!=null){ - btnSataliteMap.setVisibility(View.VISIBLE); - btnSataliteMap.getBackground().setAlpha(alpha); - } - - - setFinishButtonVisibility(true); -// if( btnFinish!=null) -// btnFinish.setVisibility(View.VISIBLE); - /*if(this.btnCamera!=null) - btnCamera.setVisibility(View.VISIBLE); */ - if(this.btnCamera!=null){ - boolean visible =trackId==activity.app.getRecordingTrack().getTrackBean().getTrackId(); - visible =visible && activity.app.getRecordingTrack().getTrackBean().getStatus()!=TrackStatus.FINISHED; - visible=visible&& mTrack_bean.getType()!=TrackType.GPX; - btnCamera.setVisibility(visible?View.VISIBLE:View.GONE); - } - -// if(btnPlayPause!=null) -// btnPlayPause.setVisibility(View.GONE); -// -// if(btnPlay!=null){ -// btnPlay.setVisibility(View.GONE); -// } - if( ll_recording_control!=null)ll_recording_control.setVisibility(View.VISIBLE); - if( ll_play_control!=null)ll_play_control.setVisibility(View.GONE); - if( ll_navi_progress!=null){ - ll_navi_progress.setVisibility(activity.app.isNaving?View.VISIBLE:View.GONE); - } - if( btnPlaySpeech!=null) - btnPlaySpeech.setImageResource(QiYouConstant.CAN_SPEAK&&QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2?R.drawable.icon_voice:R.drawable.icon_novoice); - - } - - - protected void showPlaybackButtons(){ - - if(this.btnLocation!=null) - btnLocation.setVisibility(View.GONE); - - if(this.btnRotation!=null) - btnRotation.setVisibility(View.VISIBLE); - - if(this.btnAutoZoom!=null) - btnAutoZoom.setVisibility(View.VISIBLE); - - if(btnFinish!=null) - btnFinish.setVisibility(View.GONE); - - if(btnPause!=null) - btnPause.setVisibility(View.GONE); - - if(this.btnCamera!=null) - btnCamera.setVisibility(View.GONE); - -// if(btnPlayPause!=null) -// btnPlayPause.setVisibility(View.VISIBLE); -// -// if(btnPlay!=null ){ -// btnPlay.setVisibility(View.VISIBLE); -// } - if(ll_recording_control!=null) - ll_recording_control.setVisibility(View.GONE); - if(ll_play_control!=null) - ll_play_control.setVisibility(View.VISIBLE); - - -// if(btnPlayPauseMap!=null){ -// btnPlayPauseMap.setVisibility(View.VISIBLE); -// btnPlayPauseMap.getBackground().setAlpha(alpha); -// } -// if(btnPlayMap!=null){ -// btnPlayMap.setVisibility(View.VISIBLE); -// btnPlayMap.getBackground().setAlpha(alpha); -// } - - if(this.btnKmpoints!=null){ - btnKmpoints.setVisibility(View.VISIBLE); - btnKmpoints.getBackground().setAlpha(alpha); - } - -// if(this.btnViewMap!=null) -// btnViewMap.setVisibility(View.GONE); - if(this.btnSaveScreen!=null){ - btnSaveScreen.setVisibility(View.GONE); -// btnSaveScreen.getBackground().setAlpha(alpha); - } - - if(this.btnSataliteMap!=null){ - btnSataliteMap.setVisibility(View.VISIBLE); - btnSataliteMap.getBackground().setAlpha(alpha); - } - - - } - - - - - - - protected void mornitorLocations(){ - - if ( !isPlaying) { - Intent broadcastIntent = new Intent(activity,LocationMornitorService.class); // monitor the location - activity.startService(broadcastIntent); - } - } - - @Override - protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){ - if(!TextUtils.isEmpty(picName )) { - - mTrack.setMd(picName, wp, mdType); - doSave(); - createSmallPic(picName,QiYouConstant.WEB_PIC_SIZE, - buildPicWaterMarkTitle(wp!=null?wp.getWb().getSumDist():mTrack_bean.getLastWp().getWb().getSumDist(),time)); -// QLog.getLogger().d(dTAG,TAG+" "+ "onActivityResult(), medias with wp is " +wp.toJsonWp() ); -// activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.parse(picName))); - - Bitmap bitmap = BitmapFactory.decodeFile(picName); - MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap, "爱骑驴" , "爱骑驴"); - - Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); - Uri uri = Uri.fromFile(new File(picName)); - intent.setData(uri); - activity.sendBroadcast(intent); - - /* activity.msc.connect(); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - URL url = null; - try { - url = picName.toURL(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - - activity.msc.scanFile(picName, null); - activity.msc.disconnect();*/ - } - - } - - protected void saveScreen(){ } - - - - - - -// @Override -// protected void onRestoreInstanceState(Bundle savedInstanceState) { -// super.onRestoreInstanceState(savedInstanceState); -// mMapView.onRestoreInstanceState(savedInstanceState); -// } - - - protected void setFinishButtonVisibility(boolean isVisible){ - - if(btnFinish==null)return; - - - if(!isVisible || - activity.app.playBack|| - activity.app.isLastTrackExist()&& trackId>0 && mTrack_bean.getTrackId() !=trackId -// ||btnPlay!=null &&btnPlay.getVisibility()==View.VISIBLE - ){ - btnFinish.setVisibility(View.GONE); - - } - else{ - btnFinish.setVisibility(View.VISIBLE); - - } - - btnPause.setVisibility(btnFinish.getVisibility()); - } - - - protected void updateFinshButonText(){ -// if(isPlaying ||btnPlay!=null &&btnPlay.getVisibility()==View.VISIBLE)return; - if(isPlaying )return; -// if( btnFinish!=null && btnFinish.getText().equals("取消") && trackId>0){ - if( btnFinish!=null && !needConfirmToFinish){ - // String title =canFinish()?"结束":"取消"; -// btnFinish.setVisibility(View.VISIBLE); - String text=trackId>0?COMPLETE:CANCEL; - btnFinish.setVisibility(View.VISIBLE); - btnFinish.setText(text); - - } - } - - - protected void setWorkingTrack(){ -// mTrack =new Track(); -// mTrack_bean =mTrack.getTrackBean(); - } - - void shareTrack(Track track){ - -// if( isWebRequest && track.getTrackBean().getUserid()!= activity.app.user.getUserbean().getId() )return; - - super.shareTrack(track); - if(track.getTrackBean().getSvrNumber()==0)return; - mTrackId.setText(String.valueOf(track.getTrackBean().getSvrNumber())); - saveTrack(true); - if(track.getTrackBean().getTrackId()>0){ - String title ="爱骑驴 "+ track.getTrackBean().getType().toCHString()+" 分享:" - +track.getTrackBean().getName(); - /* String content = "运动简报:" + track.getSummary() - +(TextUtils.isEmpty(track.getTrackBean().getDescription())?"":"\n"+ track.getTrackBean().getDescription()); */ - - String fomat=track.getTrackBean().geteUpDist()>0?"距离 %.1f公里, 用时 %s\n爬高 %.0f米":"距离 %.1f公里, 用时 %s"; - String content = String.format(fomat - , track.getTrackBean().getDistance()/1000 - , Utils.getTimeCnt(track.getTrackBean().getSportTime(),false) - , track.getTrackBean().geteUpDist() - - ); - - String targetUrl = QiYouConstant.BASE_URL; - if(track.getTrackBean().getSvrNumber()>0){ - targetUrl+= "track/"+track.getTrackBean().getSvrNumber(); - - } - -// String imageUrl =track.getStaticMap(); - String imageUrl =track.getStaticMapUrl(); -// staticMapImg.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); - -// hide4share(View.VISIBLE); - -// hide4share(View.GONE); - activity.doShareTrack(title, content, imageUrl, Utils.getBitmapFromView(shareView),targetUrl); - MobclickAgent.onEvent(activity,"shareTrack"); -// staticMapImg.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); -// hide4share(View.VISIBLE); -// hide4share(View.GONE); - }else - { - activity.defaultShare(); - } - isForShare=false; - } - - private void hide4share(int Visibility){ - - /* if(td_btnShowChartSpeed!=null) - td_btnShowChartSpeed.setVisibility(Visibility); - if(td_btnShowChartKm!=null) - td_btnShowChartKm.setVisibility(Visibility); -// if(td_btnShowChartKm1!=null) -// td_btnShowChartKm1.setVisibility(Visibility); -// if(td_btnShowChartSpeed1!=null) -// td_btnShowChartSpeed1.setVisibility(Visibility); - if(td_btnShowChartEle!=null) - td_btnShowChartEle.setVisibility(Visibility);*/ - if( vContainer.findViewById(R.id.ll_showShareTitle)==null) return; - - vContainer.findViewById(R.id.ll_showShareTitle).setVisibility(Visibility); - - /* vContainer.findViewById(R.id.ll_ShowChartEle).setVisibility(Visibility); - vContainer.findViewById(R.id.ll_ShowChartSpeed).setVisibility(Visibility); - vContainer.findViewById(R.id.ll_ShowChartKm).setVisibility(Visibility);*/ - -// try { -// Thread.sleep(500); -// } catch (InterruptedException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } - } - - boolean isCateChangesSaved=false; - private void saveTrack(boolean isSilence) { - isCateChangesSaved=false; - saveNewCate(); - boolean isChanged; - Utils.hideSoftKeyboard(activity); - isChanged = !mCommentEdit.getText().toString().equalsIgnoreCase(mTrack_bean.getComment()); - isChanged = isChanged || !mDescEdit.getText().toString().equalsIgnoreCase(mTrack_bean.getDescription()); - isChanged = isChanged || !mNameEdit.getText().toString().equalsIgnoreCase(mTrack_bean.getName()); - isChanged = isChanged ||oTrackType!=mTrack_bean.getType().toInt(); - - if(!isChanged ){ - if(!isCateChangesSaved) - if(!isSilence) - Toast.makeText(activity,"没有变更需要保存。", Toast.LENGTH_SHORT).show(); - return; - } - - getTrackDetailUpdated(); - - doSave(); - - if(oTrackType!=mTrack_bean.getType().toInt()){ - activity.app.getStaticsTracks(); - } - - - if(!isSilence) - Toast.makeText(activity,"变更已成功保存。", Toast.LENGTH_SHORT).show(); - } - - protected void saveNewCate(){} - protected void doSave(){ - Intent serviceIntent = new Intent(activity, TrackDbServiceBackground.class); - serviceIntent.putExtra(QiYouConstant.UPDATE_TRACK, mTrack_bean.getTrackId()); - // serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_FORCEREFRESH, true); - activity.startService(serviceIntent); - } - - - private void getTrackDetailUpdated(){ - mTrack_bean.setName(mNameEdit.getText().toString()); - mTrack_bean.setComment(mCommentEdit.getText().toString()); - mTrack_bean.setDescription(mDescEdit.getText().toString()); - - } - - - - protected void validEditButtons(){ - -// setTrackDesc(); - - } - - void initialEditViews(){ - if(mNameEdit!=null)return; - mNameEdit= (EditText) vContainer.findViewById(R.id.td_edit_Name); - mNameEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)}); - mCommentEdit = (EditText) vContainer.findViewById(R.id.td_edit_comment); - mCommentEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)}); - mDescEdit = (EditText) vContainer.findViewById(R.id.td_edit_desc); - mDescEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)}); - td_track_sumary = (TextView) vContainer.findViewById(R.id.td_track_sumary); - btnSave = (Button) vContainer.findViewById(R.id.td_btnSaveTtrack); - if(btnSave!=null){ - btnSave.setOnClickListener(ButtonOnClickListener); - } - mNameEdit.setSelectAllOnFocus(true); -// mNameEdit.setOnFocusChangeListener(onFocusChangeListener); -// mCommentEdit.setOnFocusChangeListener(onFocusChangeListener); -// mDescEdit.setOnFocusChangeListener(onFocusChangeListener); - } - - -// OnFocusChangeListener onFocusChangeListener =new View.OnFocusChangeListener() { -// @Override -// public void onFocusChange(View v, boolean hasFocus) { -// activity.isShowingInput =hasFocus; -// -// } -// } ; -// - - - protected void setTrackDesc(){ - - - QLog.getLogger().d(dTAG,TAG+" begin to set summary....... " ); - - - - initialEditViews(); -// if(mTrack_bean ==null || mTrack_bean.getTrackId()==0)return; - if(mTrack_bean ==null)return; -// final String td_textView_name = currentTrack.getTrackBean().getName(); -// final String td_track_sumary =TextUtils.isEmpty(mTrack_bean.getDescription())? mTrack.getSummary():mTrack_bean.getDescription(); - -// mCommentEdit.setText(mTrack_bean.getComment()); - mDescEdit.setText(mTrack_bean.getDescription()); - if(mNameEdit!=null && !TextUtils.isEmpty(mTrack_bean.getName())) - mNameEdit.setText(mTrack_bean.getName()); - - String summary=""; - if(mTrack_bean.getType()==TrackType.GPX){ - - - -// float avspeed=3600f*activity.app.mStatistics.getSumDist()/activity.app.mStatistics.getSumSportTime(); -// avspeed =Float.isNaN(avspeed)||avspeed==0?15:avspeed; - float avspeed= activity.app.getAVS(); - /* float hours=mTrack_bean.getDistance()/1000/avspeed; - float totalHours= (float) (hours*1.2f +((int)(hours*1.2/12))*12) ; - - summary = String.format("来自于%s\n路线总长%s,预计骑行用时%.1f小时,预计全程历时%.1f小时,预计消耗热量%.1f卡路里", - mTrack_bean.getCreator(), - Utils.getFormatedDistance(mTrack_bean.getDistance()), - hours, - totalHours , - mTrack.getCalBurn() - );*/ - long hours=(long) (mTrack_bean.getDistance()/avspeed*3600); - long totalHours= (long) (hours*1.2 +((int)(hours/1000/3600/16))*12*3600*1000) ; - String geoinfoString= - mTrack_bean.getStartWp().getWb().getGeo()!=null && mTrack_bean.getLastWp().getWb().getGeo()!=null? - String.format("从%s出发到%s,",mTrack_bean.getStartWp().getWb().getGeo().toString(","), - mTrack_bean.getLastWp().getWb().getGeo().toString(mTrack_bean.getStartWp().getWb().getGeo(),",") ):""; - - summary = String.format("来自于%s\n%s路线总长%s,预计骑行用时%s,预计全程历时%s,预计消耗热量%.1f卡路里", - mTrack_bean.getCreator(), - geoinfoString, - Utils.getFormatedDistance(mTrack_bean.getDistance()), - Utils.getTimeCnt4Read(hours,false), - Utils.getTimeCnt4Read(totalHours,false) , - mTrack.getCalBurn() - ); - }else - summary= mTrack.getSummary(); - if(td_track_sumary!=null) - td_track_sumary.setText(summary); - -// QLog.getLogger().d(dTAG,TAG+" end set summary....... " ); -// QLog.getLogger().d(dTAG,TAG+" set summary. VISIBLE...... " + (td_track_sumary.getVisibility()==View.VISIBLE)); -// QLog.getLogger().d(dTAG,TAG+" set summary....... " +td_track_sumary.getText()); - - } - - - protected void exportTrack(){ - - if(mTrack_bean ==null||mTrack_bean.getTrackId()==0)return; - String mDestXmlFilename = QiYouConstant.EXP_PATH + "GPX_"+ mTrack_bean.getName()+".gpx"; - final ProgressDialog progressDialog =ProgressDialog.show(activity, "请稍等...", "正在导出GPX数据至文件\n"+mDestXmlFilename, true); - td_btn_export.setEnabled(false); - -// Toast.makeText(activity,"正在导出数据...请稍候",Toast.LENGTH_LONG ).show(); -// try { -// new TrackInterface().exportGPX(activity,mTrack); -// } catch (IOException e) { -// // TODO Auto-generated catch block -// Utils.logStackTrace(e,dTAG); -// } - -// final TextView txtNote=(TextView)vContainer.findViewById(R.id.export_notice); - final Handler handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog - progressDialog.dismiss(); -// if(txtNote!=null)txtNote.setVisibility(View.VISIBLE); - //更新UI -// switchButtonStatus(); - td_btn_export.setEnabled(true); - String gpxFile =msg.getData().getString("exportgpx"); - if(TextUtils.isEmpty(gpxFile)){ -// Toast.makeText(activity,"数据导出出现错误,导出失败。",Toast.LENGTH_SHORT ).show(); -// if(txtNote!=null)txtNote.setText("数据导出出现错误,导出失败。"); - showNotes("数据导出出现错误,导出失败。"); - }else - { -// Toast.makeText(activity,"数据已导出至 "+gpxFile,Toast.LENGTH_LONG ).show(); -// if(txtNote!=null)txtNote.setText("数据已导出至 "+gpxFile); - showNotes("数据已导出至 "+gpxFile); - } - }}; - - new Thread(){ - @Override - public void run() { - String gpx =new TrackInterface().exportGPX(activity,mTrack); - Message msg= Message.obtain(handler);// .obtain(handler, 1); - Bundle bd =new Bundle(); - bd.putString("exportgpx", gpx); - msg.setData(bd); - handler.sendMessage(msg); - - }}.start(); - - - - - - - if(!QiYouConstant.DEVELOPER_MODE) return; - - if(mTrack ==null)return; - String[] ids = new String[2]; - ids[0] = String.valueOf(-1); - ids[1] = String.valueOf(mTrack_bean.getTrackId()); - Exportdb eb = new Exportdb(activity); - eb.ExportTracks(ids); - - } - void setTabhostTitle(){ - if(tabhost!=null) - ((TextView)tabhost.getTabWidget().getChildAt(0).findViewById(android.R.id.title)).setText("查询超时,请重试..."); - } - - protected boolean isCustWaypoint(Waypoint_bean wb){ - // QLog.getLogger().d(TAG, " is it a custWp? -----------------------------------------------" ); - // QLog.getLogger().d(TAG, "is it a custWp? wb.getTurnFlag():"+ wb.getTurnFlag()); - // QLog.getLogger().d(TAG, "is it a custWp? mwb.getName():"+wb.getName()+", road book:"+wb.getRoadBook()); -// QLog.getLogger().d(TAG, " is it a custWp? (!TextUtils.isEmpty(wb.getName()))"+(!TextUtils.isEmpty(wb.getName()))); -// int ispass=wb.getRoadBook().indexOf("到达【途经点") ; -// QLog.getLogger().d(TAG, " is it a custWp? wb.getRoadBook().indexOf( )>0 ?" +ispass); - -// QLog.getLogger().d(TAG, " is it a custWp?"+((!TextUtils.isEmpty(wb.getName()))&&wb.getRoadBook().indexOf("到达【途经点")>0)); - -// return ((!TextUtils.isEmpty(wb.getName()))&&wb.getRoadBook().indexOf("到达【途经点")==0); - - /*return wb.getTurnFlag().toInt()==wpFlag.CUST.toInt() - ||wb.getTurnFlag().toInt()==wpFlag.TENT.toInt() - ||wb.getTurnFlag().toInt()==wpFlag.REST.toInt();*/ - return wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt(); -// TextUtils.isEmpty(wb.getName())&&wb.getRoadBook().indexOf("到达【途经点")<0 - } - - - @Override - public void onResume() { - /** - * MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume() - */ - - - if(mTrack_bean==null){ - super.onResume(); - return; - } - -// if(mTrack_bean!=null) - mIsPaused = mTrack_bean.getStatus() ==TrackStatus.PAUSED; - - setSelectedTrackType(); - - if( mTrack_bean.getTrackId()>0 && mPauseTimeText!=null &&!isPlaying){ - if(mTrack_bean.getSportTime()>lastsptime){ - lastsptime=mTrack_bean.getSportTime(); - } - - if(mIsPaused){ - activity.app.restartPause(); - } - - updateTimeView(0); - } - activity.app.updateUIstatus(true); - - updateUI(null, false); //TODO: review if it can be deleted - - mornitorLocations(); - // QLog.getLogger().d(dTAG,TAG+" "+"onResume, and trying to draw whole track." ); - - setSpeechIcon(); - - super.onResume(); - } - - - - /* (non-Javadoc) - * @see android.support.v4.app.Fragment#onPause() - */ - @Override - public void onPause() { - /** - * MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause() - */ - - activity.app.updateUIstatus(false); - - lastLocation =null; - currentLocation = null; - -// mRunning = false; - QLog.getLogger().d(dTAG,TAG+" "+"onPause" ); - super.onPause(); - } - - - @Override - public void onDestroy() { -// activity.updateTabVisibility(true); - super.onDestroy(); - } - - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - } - - - @Override - public String getCurrentTag() { - // TODO Auto-generated method stub - return TAG; - } - - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - - } - - @Override - public void doQuery() { - // TODO Auto-generated method stub - - } - -// String lastNavMsg=""; - @Override - public void navInfo(final Location location ) { - // TODO Auto-generated method stub - if(ll_note==null)return; - if(location==null)return; - Bundle bd =location.getExtras(); - if(bd==null)return; - if(navi_progress!=null){ - int progress = bd.getInt( QiYouConstant.NEW_NAVIFO_DIST_PROGRESS); - navi_progress.setProgress(progress); - } -// String msg =location.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG); - if(txt_nav_info!=null) - txt_nav_info.setText(bd.getString( QiYouConstant.NEW_NAVIFO_MSG)); - - new Handler().post(new Runnable(){ - @Override - public void run() { -// - showNaviPaoPao( location); - } - }); - - - - /*if(!msg.equalsIgnoreCase(lastNavMsg)){ -// ll_note.setVisibility(View.VISIBLE); - txt_nav_info.setText(location.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG)); - showNaviPaoPao( location); - lastNavMsg=msg; - }else - return;*/ - } - - protected void showNaviPaoPao(Location location){} - -} -/*Handler myHandler = new Handler() { - public void handleMessage(Message msg) { - updateUIHere(); - } -} - -new Thread() { - public void run() { - doStuff(); // 执行耗时操作 - Message msg = myHandler.obtainMessage(); - Bundle b = new Bundle(); - b.putString("key", "value"); - m.setData(b); // 向消息中添加数据 - myHandler.sendMessage(m); // 向Handler发送消息,更新UI - } -}.start();*/ - - - - - \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/UserDetails.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/UserDetails.java deleted file mode 100644 index 2e3177f..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/UserDetails.java +++ /dev/null @@ -1,509 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.EditText; -import android.widget.TextView; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.basic.GEO_bean; -import com.qiyou.mb.android.beans.basic.Media; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.beans.basic.Waypoint; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.enums.mediaType; -import com.qiyou.mb.android.utils.exception.NoWebObjectException; -import com.qiyou.mb.android.utils.image.QroundimageView; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; -import com.umeng.analytics.MobclickAgent; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.FileNotFoundException; - -public class UserDetails extends GroupDetail /*TrackingBasic_fragment*/ { -/* @Override - public String getCurrentTag() { - // TODO Auto-generated method stub - setFTag(); - return TAG; - }*/ - - @Override - public void setFTag() { - // TODO Auto-generated method stub - TAG="com.qiyou.UserDetails"; -// FirstTabTextColor= getResources().getColorStateList(R.color.red); -// FirstTabBackGround=R.drawable.icon_user; - } - - public static String getFTag() { - return "com.qiyou.UserDetails"; - - } - -// public class UserProfile extends TrackList_fragment { -// protected int currentLayout; -// int userId; - private User_bean user; - private Button btnLogout; - public static UserDetails newInstance(User_bean user/*,int userId*/) - { - - UserDetails f = new UserDetails(); - f.user=user; - - return f; - } - public static UserDetails newInstance() - { - - UserDetails f = new UserDetails(); - - - return f; - } - - - public void setCurrentUser(User_bean user){ - this.user =user; - -// initialWebQuery(); - } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - super.BBScate = BBSCate.USER.toInt(); - } - - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - vContainer = inflater.inflate(R.layout.user_detail_edit, container, false); - - - initialViews(); - title = user.getId()>0 && user.getId()==activity.app.user.getUserbean().getId()?"我的信息" - :getResources().getString(R.string.frg_userdetail) +"|"+user.getUserName() ; - return vContainer; - } - - - - - - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); -// IL = new ImageLoader(activity); -// int actid=-1; - - - } - - - - - TextView txtAccount ; - @Override - protected void initialViews(){ - super.initialViews(); - btnLogout =(Button)vContainer.findViewById(R.id.usr_btn_logout); - btnLogout.setOnClickListener(ButtonOnClickListener); - } - - EditText edit_mail; - EditText edit_score; - QroundimageView imgAbulm; - @Override - void initialExtraViews(){ - txtAccount =(TextView)vContainer.findViewById(R.id.user_account); - - edit_mail =(EditText)vContainer.findViewById(R.id.user_mailbox); - edit_score =(EditText)vContainer.findViewById(R.id.act_edit_score); - imgAbulm =(QroundimageView)vContainer.findViewById(R.id.user_abulm); - imgAbulm.setOnClickListener(ButtonOnClickListener); - - } - - @Override - void showWebObject(){ - if(user!=null){ - getDetails(); - } - - } - - - - - - @Override - void setDetails(){ - - if(user==null ||user.getId()==0){ - return; - } - /*if(user.getId()!=activity.app.user.getUserbean().getId()){ - return; - }*/ - // user.setUserName(txtAccount.getText().toString()); - user.setUserDesc(act_edit_description.getText().toString()); - user.setMail(edit_mail.getText().toString()); - - int score=user.getScore(); - if(!TextUtils.isEmpty(edit_score.getText().toString())){ - try{ - score =Integer.valueOf(edit_score.getText().toString()); - }catch(Exception e){ - // QLog.getLogger().e(dTAG, e.toString()); - } - } - user.setScore(score); - - if(user.getId()==activity.app.user.getUserbean().getId()){ - user.setQqExprires(QiYouConstant.PV_EXPIRES_IN); - }else if (!QiYouConstant.DEVELOPER_MODE){ - user.setId(activity.app.user.getUserbean().getId()); - } - // QLog.getLogger().d(dTAG, String.format("user.id %s,activity.app.user.getUserbean().getId() %s", user.getId(),activity.app.user.getUserbean().getId())); - - - - - - } -// @Override -// void drawActNaviRoadbook(Track gpxTrack){ -// return; -// } -// - - @Override - void getDetails(){ - this.BBScate = BBSCate.USER.toInt(); // act - this.BBSSubcate = user.getId(); - this.BBSsubCateName = user.getUserName(); - - txtAccount.setText(user.getUserName()); -// this.edit_act_startGeo.setText(user.getGeo()==null?us); - if(user.getGeo()!=null){ - urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,user.getGeo().getSharedAddressUrl()); - - this.edit_act_startGeo.setText( - (TextUtils.isEmpty(user.getGeo().getCityName())?"":user.getGeo().getCityName()) - + - (TextUtils.isEmpty(user.getGeo().getDistrictName())?"":user.getGeo().getDistrictName()) - - /*+ user.getGeo().getStreetName()*/); - - } - - edit_mail.setText(user.getMail()); - - act_edit_description.setText(user.getUserDesc()); - - edit_act_startTime.setText(Utils.getFormatedTime(user.getRegtime())); - -// edit_act_distance.setText(Utils.getFormatedDistance(user.getDistance())); - edit_act_distance.setText(String.format("%.1f", user.getDistance()/1000)); - - edit_score.setText(user.getScore()+""); -// String imgUrl= TextUtils.isEmpty(user.getAlbum())?user.getQqAbulmUrl() :Utils.getUserAlbum(user.getAlbum()); - String imgUrl = Utils.getUserAlbum(user); - if(!TextUtils.isEmpty(imgUrl)){ - this.IL.DisplayImage(imgUrl, imgAbulm); - } - - act_svrNo.setText(user.getId()>0?user.getId()+"":"") ; - super.BBSsubCateName = user.getUserName(); - } - - - - @Override - void validInputs(){ - - - /*if(activity.app.user.getUserbean().getId() <=0){ - activity.showLogin(); - }*/ - - boolean canEdit = canEdit() ;//||QiYouConstant.DEVELOPER_MODE; - int visible=canEdit?View.VISIBLE:View.GONE; - txtStartGeoPicker.setVisibility(visible); - btn_submitAct.setVisibility(visible); - btn_submitAct.setEnabled(canEdit); -// btn_saveAct.setEnabled(user.getId()==0); - btn_saveAct.setVisibility(/*user.getId()==0?View.VISIBLE:*/View.GONE); - btn_submitAct.setText(/*user.getId()>0?R.string.act_update:*/R.string.act_submit); - -// act_edit_title.setEnabled(/*canEdit*/false); - edit_act_startGeo.setEnabled(canEdit); - act_edit_description.setEnabled(canEdit); - edit_mail.setEnabled(canEdit &&TextUtils.isEmpty(edit_mail.getText().toString().trim())) ; - -// edit_act_distance.setEnabled(canEdit); -// edit_act_speed.setEnabled(canEdit); - - -// boolean canJoin = activity.user.getId()>0 && activity.user.getUserId() !=activity.app.user.getUserbean().getId(); -// visible=canJoin ?View.VISIBLE:View.GONE; - btn_actJoin.setVisibility(/*visible*/View.GONE); -// btn_actJoin.setEnabled(canJoin); - -// btn_refresh.setEnabled(true); -// btn_refresh.setVisibility(/*activity.user.getId()>0?View.VISIBLE:View.GONE*/View.VISIBLE); - - edit_score.setEnabled(QiYouConstant.DEVELOPER_MODE); - super.imgTopBanner.setEnabled(false); - imgAbulm.setEnabled(canEdit() || QiYouConstant.DEVELOPER_MODE); - - btnLogout.setVisibility(canEdit?View.VISIBLE : View.GONE); - - } - - @Override - boolean validSubmit(){ - - - if (!Utils.validate(edit_mail.getText().toString())) { - this.showNotes( "请输入正确的邮箱", true); -// Toast.makeText(activity, "请输入正确的邮箱",Toast.LENGTH_LONG).show(); - edit_mail.setHintTextColor(Color.RED); - edit_mail.setSelected(true); - return false; - } - - return true; - } - - @Override - void postSvr() { - this.postJsonWS(Utils.getGsonString(user),RestMethods.USER_P_UPDATE/* "mb/group/"*/); - } - - - - @Override - void writeLocalObjCache(){ - - - } - @Override - void joinSvrObj(){ - - - } - @Override - void setbackGeoInfo(int textViewId){ - if(user.getLat()>0 && user.getLon()>0) - if(textViewId == R.id.act_txt_startGeo_picker){ - activity.latToshow =user.getLat(); - activity.lngToshow =user.getLon(); - - } - - } - @Override - boolean canEdit(){ - return user!=null && - user.getId() == activity.app.user.getUserbean().getId() - ||this.isAdmin(); - } - - @Override - void setFindResult(){ - int txtid=activity.addressTextId == R.id.act_txt_startGeo_picker?R.id.act_edit_startGeo : -1; - - if(activity.geoAddress==null || TextUtils.isEmpty(activity.geoAddress.getCity()) ||TextUtils.isEmpty(activity.geoAddress.getCity().replace("null", "")))return; - if(txtid==-1)return; - - EditText text =((EditText)vContainer.findViewById(txtid)); - - if(text!=null){ - text.setText(activity.geoAddress.getCity()+activity.geoAddress.getDistrict()); - - if(txtid ==R.id.act_edit_startGeo){ - user.setGeo(new GEO_bean(activity.geoAddress )); - if(user.getGeo()!=null){ - user.getGeo().setSharedAddressUrl(activity.sharedAddressUrl ); - user.getGeo().setName(activity.geoAddress.getCity() +activity.geoAddress.getDistrict() ); - urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,activity.sharedAddressUrl ); - } - user.setLat(activity.geoAddress.getLat()); - user.setLon(activity.geoAddress.getLon()); - } - - activity.geoAddress=null; - activity.addressTextId=0; - } - - } - - - - @Override - void shareEndUrl(int viewId){ - - if(user.getGeo()==null || TextUtils.isEmpty(user.getGeo().getSharedAddressUrl()) ){ - return; - } - Intent sendIntent = new Intent(); - sendIntent.setAction(Intent.ACTION_SEND); - - String url =user.getGeo().getSharedAddressUrl(); /*viewId==R.id.act_txt_startGeo_share? currentAct.getStartAddressUrl() - : currentAct.getEndAddressUrl();*/ - String title =edit_act_startGeo.getText().toString();//user.getGeo().getName(); - title =String.format("【%s】 %s", user.getUserName(),title); - if(viewId==R.id.act_txt_startGeo_share) - sendIntent.putExtra(Intent.EXTRA_TEXT, url); - sendIntent.setType("text/plain"); - startActivity(Intent.createChooser(sendIntent,title )); - - } - - - - @Override - void processGetJsonObject(String method,JSONObject jsonObject,String msg) throws JSONException, NullPointerException, NoWebObjectException { - if(method.equalsIgnoreCase(RestMethods.USER_G_FIND_BY_ID)){ - user = (User_bean)Utils.getGsonObject(jsonObject.toString(), User_bean.class); - getDetails(); - return; - } - super.processGetJsonObject(method,jsonObject,msg); - if(jsonObject==null)return; - - - - } - @Override - void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{ - super.processJsonObject(method, jsonObject, msg); - if(method.equalsIgnoreCase(RestMethods.USER_P_UPDATE)){ //sumbmit act - this.showNotes(msg); - } - - } - - @Override - void showMember(User_bean user){ - this.getDetails(); - } - - @Override - protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){ - - - - if (user.getId() > 0){ - Media md = new Media(); - md.setTrackSvrNumber(user.getId()); - md.setUri(picName); - md.setType(mediaType.PIC); - md.setSvrUri(user.getAlbum()); - int tmp = QiYouConstant.WEB_PIC_SIZE; - try { - QiYouConstant.WEB_PIC_SIZE = 128; - super.postBinaryWS(md, RestMethods.USER_P_UPLOAD_ALBUM); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - QiYouConstant.WEB_PIC_SIZE = tmp; - - }else { - user.setAlbum(picName); - } - - - } - - @Override - void uploadMediasOnReturn(JSONObject jo) { - this.showNotes("图片上传成功!"); - if (jo!=null){ - try { - if (user!=null){ - user.setAlbum(jo.getString("svrUri")); - if (user.getId() == activity.app.user.getUserbean().getId()){ - activity.app.user.getUserbean().setAlbum(user.getAlbum()); - activity.app.updateUserPref(user); - - } - } - - IL.DisplayImage(QiYouConstant.BASE_MD_URL + jo.getString("svrUri"),this.imgAbulm); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - @Override - void shareObj(){ - String shareTitle =user.getDistance()> 100 ? "共运动了"+ edit_act_distance.getText()+"公里" : "和我一起运动吧" ; - String shareContent = "约吗?\n" + BBSsubCateName ; -// Bitmap b = this.imgTopBanner.getDrawingCache(); -// Bitmap b = ((BitmapDrawable)imgTopBanner.getDrawable()).getBitmap(); - Bitmap b = Utils.getBitmapFromView(this.imgAbulm); -// String imgurl = currentAct !=null ? currentAct.getAlbum() : - MobclickAgent.onEvent(activity,"shareObj-" + BBSCate.values()[super.BBScate]); - QLog.getLogger().d(dTAG, " sharecontent is "+shareContent +",title is "+ title); - activity.doShare(shareTitle, shareContent, "", b , QiYouConstant.BASE_URL +"list?user=" + user.getId()); - - - } - - - @Override - public void onResume() { -// activity.app.currentActiveFragment =TAG; - super.onResume(); -// activity.updateActionBarTitle(title); - - - } - - @Override - void generateQcode(){ - if (user.getId() > 0){ - - JSONObject json = new JSONObject(); - try { - json.put(QiYouConstant.EXTRA_KEY_SVRID, String.valueOf(user.getId())); - json.put("ownerId", String.valueOf( user.getId())); - json.put("svrName", user.getUserName()); - json.put(QiYouConstant.EXTRA_KEY_RESTMETHOD,RestMethods.USER_G_FIND_BY_ID); - json.put(QiYouConstant.EXTRA_KEY_QCODEDESC, user.getUserName()); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - activity.showQcode(json.toString()); - } - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/UserHome.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/UserHome.java deleted file mode 100644 index 393acc6..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/UserHome.java +++ /dev/null @@ -1,366 +0,0 @@ -package com.qiyou.mb.android.ui.fragments; - -import org.json.JSONException; -import org.json.JSONObject; - -import android.content.Intent; -import android.graphics.Color; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.TabHost; -import android.widget.TextView; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.GEO_bean; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.exception.NoWebObjectException; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; -import com.umeng.socialize.utils.Log; - -public class UserHome extends GroupHome /*TrackingBasic_fragment*/ { -/* @Override - public String getCurrentTag() { - // TODO Auto-generated method stub - setFTag(); - return TAG; - }*/ - - @Override - public void setFTag() { - // TODO Auto-generated method stub - TAG="com.qiyou.UserHome"; -// FirstTabTextColor= getResources().getColorStateList(R.color.red); -// FirstTabBackGround=R.drawable.icon_user; - } - - public static String getFTag() { - return "com.qiyou.UserHome"; - - } - -// public class UserProfile extends TrackList_fragment { -// protected int currentLayout; -// int userId; - private User_bean user; - - public static UserHome newInstance(User_bean user/*,int userId*/) - { - - UserHome f = new UserHome(); - f.user=user; - - return f; - } - public static UserHome newInstance() - { - - UserHome f = new UserHome(); - - - return f; - } - - - public void setCurrentUser(User_bean user){ - this.user =user; - -// initialWebQuery(); - } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - - - } - - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - vContainer = inflater.inflate(R.layout.user_home, container, false); - - - initialViews(); - title = user.getId()>0 && user.getId()==activity.app.user.getUserbean().getId()?"我的信息" - :getResources().getString(R.string.frg_userdetail) +"|"+user.getUserName() ; - return vContainer; - } - - - - - - - - - private TextView userTitle, userCalori, userDist, faraway,userSvrno; - - @Override - void initialExtraViews(){ - - userTitle = (TextView)vContainer.findViewById(R.id.usr_name); - userCalori = (TextView)vContainer.findViewById(R.id.usr_calorie); - userDist = (TextView)vContainer.findViewById(R.id.usr_dist); - faraway = (TextView)vContainer.findViewById(R.id.usr_faraway); - userSvrno = (TextView)vContainer.findViewById(R.id.usr_svrno); - - - } - - @Override - void showWebObject(){ - if(user!=null){ - getDetails(); - } - - } - - - - - - - @Override - void addTabs(){ - -// - - tabhost.addTab(tabBbs); - - tabhost.addTab(tabTrack); - - - tabhost.addTab(tabAct); - - - tabhost.addTab(tabGrp); - tabhost.addTab(tabLive); - - -// - - } - - -// private int currentActTab; -// //not to remember last selected tab. -// @Override -// protected void setSelectedTab(){ -// if(tabhost!=null&& tabhost.getCurrentTab()!=currentActTab){ -// tabhost.setCurrentTab(currentActTab); -// } -// } - - @Override - void getQueryType(int queryType){ - isBBSQuery = queryType == 0; - isGroupQuery = queryType==3; - isActivityQuery = queryType==2; - isShareQuery =queryType==1; - isLiveQuery =queryType==4; -// currentActTab = currentTab; - - } -// @Override -// void processTabQuery(){ -// super.processTabQuery(); -// -// if(isGroupQuery){ -// lvWeb.setVisibility(View.VISIBLE); -// // QLog.getLogger().d(dTAG, "grpData is Null? " + (grpData==null)); -// if(grpData==null) -//// doActQuery(); -// doGroupQuery(); -// else -// showGrpData(); -// if(grpData!=null) -// showNoRecText(grpData.size()==0); -// -// -// } -// } - - @Override - void showObjDetail(){ - activity.showUserDetails(user); - } - - @Override - void getDetails(){ - - this.BBScate = BBSCate.USER.toInt(); //act - this.BBSSubcate = user.getId(); - this.BBSsubCateName =user.getUserName(); - BBSSubcateOwner = user.getId(); - - userTitle.setText(user.getUserName()) ; - userCalori.setText( String.format("%.0f",user.getCalorie())); - userDist.setText( String.format("%.0f",user.getDistance()/1000)); - faraway.setText( user.getLat()>0 && QiYouConstant.PV_LAST_LAT>0? String.format("%.1f", Utils.getDistanceFromXtoY( user.getLat(), user.getLon(), - QiYouConstant.PV_LAST_LAT, QiYouConstant.PV_LAST_LON)/1000 ):"--" ) ; -// userSvrno.setText(user.getId()+"") ; - userSvrno.setText(String.format("%s %s", user.getGeo().getCityName(),user.getGeo().getDistrictName()).replace("null", "")); - - - - - -// txtAccount.setText(user.getUserName()); -//// this.edit_act_startGeo.setText(user.getGeo()==null?us); -// if(user.getGeo()!=null){ -// urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,user.getGeo().getSharedAddressUrl()); -// -// this.edit_act_startGeo.setText( -// (TextUtils.isEmpty(user.getGeo().getCityName())?"":user.getGeo().getCityName()) -// + -// (TextUtils.isEmpty(user.getGeo().getDistrictName())?"":user.getGeo().getDistrictName()) -// -// /*+ user.getGeo().getStreetName()*/); -// -// } -// -// edit_mail.setText(user.getMail()); -// -// act_edit_description.setText(user.getUserDesc()); -// -// edit_act_startTime.setText(Utils.getFormatedTime(user.getRegtime())); -// -//// edit_act_distance.setText(Utils.getFormatedDistance(user.getDistance())); -// edit_act_distance.setText(String.format("%.1f", user.getDistance()/1000)); -// -// edit_score.setText(user.getScore()+""); -// String imgUrl=user.getQqAbulmUrl(); -// if(!TextUtils.isEmpty(imgUrl)){ -// this.IL.DisplayImage(imgUrl, imgAbulm); -// } -// -// act_svrNo.setText(user.getId()>0?user.getId()+"":"") ; - } - - - - @Override - void refresh(){ - - - - - if(currentTab==0){ - requestUserFromWeb(user.getId()); - return ; - - - }else if(isLiveQuery){ -// showLive(); - return ; - } - - - this.initialWebQuery(); - - - } - - - - - - - - - RequestParams buildLiveQueryParames(){ - RequestParams params = new RequestParams(); -// final int GEO_CITY_TYPE=2; - -// if(activity.currentAcitiviy==null) return null; - params.add("userId", String.valueOf(user.getId())); - params.add("from", String.valueOf(lastMaxLiveTime)); - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - - - @Override - void showMember(User_bean user){ - this.getDetails(); - } - @Override - RequestParams buildShareQueryParames(){ - -// RequestParams params = new RequestParams(); - - RequestParams params = super.buildShareQueryParames(); - if(user.getId()>0){ - params.add("ownerId", String.valueOf(user.getId())); - } - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - RequestParams buildActQueryParames(){ - RequestParams params = new RequestParams(); - - params.add("userId", String.valueOf(user.getId())); - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - RequestParams buildGroupQueryParames(){ - RequestParams params = super.buildGroupQueryParames() ; - params.add("ownerId", String.valueOf(user.getId())); - return params ; - - - - } - - - /*@Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return false; - }*/ - - - @Override - public void setTabOnFiling() { - // TODO Auto-generated method stub - maxTabIndex =5; - MAPVIEW_INDEX=maxTabIndex; - - } - - - @Override - public void onResume() { -// activity.app.currentActiveFragment =TAG; - super.onResume(); -// activity.updateActionBarTitle(title); - - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/WebList_fragment.java b/qy/src/main/java/com/qiyou/mb/android/ui/fragments/WebList_fragment.java deleted file mode 100644 index 58aef27..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/ui/fragments/WebList_fragment.java +++ /dev/null @@ -1,3251 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.ui.fragments; - -import android.annotation.TargetApi; -import android.app.ProgressDialog; -import android.content.Context; -import android.database.Cursor; -import android.graphics.Typeface; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.text.InputType; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.ListView; -import android.widget.SimpleAdapter.ViewBinder; -import android.widget.Spinner; -import android.widget.TabHost; -import android.widget.TabHost.OnTabChangeListener; -import android.widget.TextView; - -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.RequestParams; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Activity_bean; -import com.qiyou.mb.android.beans.basic.GEOaddress; -import com.qiyou.mb.android.beans.basic.Group_bean; -import com.qiyou.mb.android.beans.basic.Note; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.utils.NoScrollGridView; -import com.qiyou.mb.android.utils.QCursorAdapter; -import com.qiyou.mb.android.utils.QSimpleAdapter; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.enums.BBSCate; -import com.qiyou.mb.android.utils.enums.TrackAvStatus; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.WebQueryCate; -import com.qiyou.mb.android.utils.image.ImageGridAdapter; -import com.qiyou.mb.android.utils.log.QLog; -import com.qiyou.mb.android.utils.server.RestMethods; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -//import android.widget.ImageView; - -/** - * @author mwang - * - */ -public class WebList_fragment extends TrackMap_fragment/* TrackList_fragment *//* TrackingBasic_fragment *//* - * Querybase_fragment - * implements - * LoaderCallbacks - * < - * Cursor - * > - */{ - - @Override - public void setFTag() { - TAG = "com.qiyou.WebList_fragment"; - // FirstTabTextColor= getResources().getColorStateList(R.color.red); - // FirstTabBackGround=R.drawable.icon_clouds; - } - - public static String getFTag() { - return "com.qiyou.WebList_fragment"; - } - - @Override - public String getCurrentTag() { - activity.updateActionBarTitle(R.string.frg_trackWeb); - return "com.qiyou.WebList_fragment"; - - } - - private boolean isFirstCreate = false; - protected Cursor cursor = null; - protected QCursorAdapter adapter; - // protected MainActivity activity; - private ProgressDialog progressDialog; - // private Handler handler ; - - // TextView noRec ; - // private ListView lv = null; - // protected ListView lvWeb = null; - // ListView lvWeb = null; - // ListView lvWeb = null; - // ListView lvWeb =null; - // ListView lvWeb = null; - - // private ImageButton btn_webquery; - private ImageView btn_webquery; - - private CheckBox chk_web_pic; - // private CheckBox chk_my_tracks; - // private CheckBox chk_my_nearby; - boolean isShowPic = true; - private boolean isShowMytrackOnly; - private boolean isShowMyNearbyOnly; - - private QSimpleAdapter lvAdapter; - - protected TextView txtNote; - - private final int STRLNG = 30; - - private ArrayList> tmpData; - - private ListviewOnScroll listViewOnScroll = new ListviewOnScroll(); - - // for web sp input - private List cateList = null; // Arrays.asList(Cates); - private String[] totalCates = { "默认", "周边", "地区", "关键字", "我的", "驴友", "编号", - "骑行", "路书", "徒步", "机动", "积分", "活动相关", "队伍相关", "软件使用", "车辆装备", - "问题反馈", "骑行天地", "跑友交流", "徒步户外" }; - private String[] firstCate = {}; // { - // "默认","\(firstItem)","我的","软件使用","活动相关","队伍相关", - // "车辆装备","问题反馈"} - private ArrayAdapter spAdapterWeb; - private List totalList; - private String BBSCity = ""; - - // private SwipeRefreshLayout mSwipeLayout; - - // private TextView txt_swip_refrsh ; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (activity == null) { - activity = (com.qiyou.mb.android.ui.MainActivity) getActivity(); - } - firstLoad = true; - isFirstCreate = true; - if (activity != null && activity.app != null) { - webTrackType = activity.app.getLastTracktype(); - // IL= new com.qiyou.mb.android.utils.ImageLoader(activity); - } - IL = new com.qiyou.mb.android.utils.ImageLoader(getActivity()); - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - vContainer = inflater.inflate(R.layout.web_list, container, false); - - spWebInputType = (Spinner) vContainer - .findViewById(R.id.sp_Web_inputType); - - initialView(); - - // showCategoryList(cateLv,null); - - return vContainer; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - // this.setSelectedTab(); - // processTabQuery(); - - // getLoaderManager().initLoader(0, null, this); - - } - - @Override - protected void initialView() { - firstLoad = true; - - txt_webinput = (EditText) vContainer.findViewById(R.id.txt_webinput); - - btn_webquery = (ImageView) vContainer.findViewById(R.id.btn_WebQuery); - btn_webquery.setOnClickListener(ButtonOnClickListener); - - chk_web_pic = (CheckBox) vContainer.findViewById(R.id.fm_chk_web_pic); - - chk_web_pic.setOnCheckedChangeListener(m_checkboxListener); - isShowPic = /* isShowPic|| */Utils.getNetworkType(activity) == QiYouConstant.NETWORK_TYPE_WIFII; - chk_web_pic.setChecked(!isShowPic); - txtNote = (TextView) vContainer.findViewById(R.id.txtNotice); - initialTabSpIndex(); - initialWebInput(); - // initWebQueryTypeSpinWeb(); - initialTabhost(); - initialLoadingMore(); - getQueryCate(); - - } - - /* - * void initialBBSWebListView(int viewId){ lvWeb - * =(ListView)vContainer.findViewById(viewId); - * lvWeb.setVisibility(View.VISIBLE); - * lvWeb.setOnItemClickListener(itemListener); lvWeb.setOnTouchListener(new - * OnTouchListener() { - * - * @Override public boolean onTouch(View v, MotionEvent event) { - * Utils.hideSoftKeyboard(activity); return false; } }); - * - * lvWeb.setOnScrollListener( listViewOnScroll); } - */ - @Override - void initialWebListView(int viewId) { - lvWeb = (ListView) vContainer.findViewById(viewId); - if (lvWeb == null) { - return; - } - lvWeb.setVisibility(View.VISIBLE); - lvWeb.setOnItemClickListener(itemListener); - lvWeb.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - Utils.hideSoftKeyboard(activity); - return false; - } - }); - - if (ll_loadmore == null) { - initialLoadingMore(); - loadingMore.setText(R.string.loadmore_complete); - loadingImg.setBackgroundResource(R.drawable.icon_stop); - } - lvWeb.setOnScrollListener(listViewOnScroll); - lvWeb.removeFooterView(ll_loadmore); - lvWeb.addFooterView(ll_loadmore); - } - - @SuppressWarnings("unchecked") - void initialTabSpIndex() { - if (activity.app.tabSpIndex != null) { - return; - } - if (!TextUtils.isEmpty(QiYouConstant.PV_LAST_BBS_CATE)) { - activity.app.tabSpIndex = (HashMap) Utils - .getGsonObject(QiYouConstant.PV_LAST_BBS_CATE, - HashMap.class); - - } else { - activity.app.tabSpIndex = new HashMap(); // default - // selected - // item - activity.app.tabSpIndex.put("0", 0); - activity.app.tabSpIndex.put("1", 0); - activity.app.tabSpIndex.put("2", 1); - activity.app.tabSpIndex.put("3", 1); - activity.app.tabSpIndex.put("4", 0); - } - - tabSpIndexValue = new HashMap>(); - HashMap tmp = new HashMap(); -// tmp.put(0, ""); -// tabSpIndexValue.put(0, tmp); - tmp = new HashMap(); - tmp.put(3, ""); - tmp.put(4, ""); - tmp.put(5, ""); - tmp.put(6, ""); - tabSpIndexValue.put(1, tmp); - tmp = new HashMap(); - tmp.put(2, ""); - tmp.put(3, ""); - tmp.put(5, ""); - tabSpIndexValue.put(2, tmp); - tmp = new HashMap(); - tmp.put(2, ""); - tmp.put(3, ""); - tmp.put(5, ""); - tabSpIndexValue.put(3, tmp); - tmp = new HashMap(); - tmp.put(2, ""); - tmp.put(3, ""); - tmp.put(5, ""); - tabSpIndexValue.put(4, tmp); - } - - @TargetApi(Build.VERSION_CODES.GINGERBREAD) - void getQueryCate() { - - if (spWebInputType == null) { - - return; - } - - // String[] Cates = {}; - // List a = Arrays.asList(totalCates); - - try { - - // totalList = (ArrayList) Arrays.asList(totalCates); - - // List totalList2 = - // (List)Arrays.asList(totalCates); - // totalList = (ArrayList) totalList2; - totalList = (List) Arrays.asList(totalCates); - - } catch (Exception e) { - e.printStackTrace(); - QLog.getLogger().d(TAG, e.getMessage()); - } - switch (currentTab) { - case 0: - BBSCity = activity.app.user.getUserbean().getGeo().getCityName(); // .getGeo().getCityName(); - if (BBSCity == null || TextUtils.isEmpty(BBSCity)) { - BBSCity = "地方论坛"; - - } - ; - - // if (!totalList.contains(BBSCity)){ - // totalCates +=[BBSCity]; //totalList.add(totalList.size(), city); - // } - - String[] bbsCates = { "默认", BBSCity, "我的", "软件使用", "骑行天地", "跑友交流", - "徒步户外", "活动相关", "队伍相关", "车辆装备", "问题反馈" }; - cateList = Arrays.asList(bbsCates); - - break; - case 1: - String[] shareCates = { "我的", "默认", "周边", "地区", "关键字", "驴友", "编号", - "骑行", "路书", "徒步", "机动" }; - cateList = Arrays.asList(shareCates); - - break; - case 2: - String[] groupCates = { "默认", "周边", "地区", "关键字", "我的", "编号" }; - cateList = Arrays.asList(groupCates); - break; - case 3: - String[] actCates = { "默认", "周边", "地区", "关键字", "我的", "编号" }; - cateList = Arrays.asList(actCates); - break; - case 4: - String[] userCates = { "默认", "周边", "地区", "关键字", "驴友", "编号" }; - cateList = Arrays.asList(userCates); - break; - - } - - // 将可选内容与ArrayAdapter连接起来 - // ArrayAdapter - spAdapterWeb = new QArrayAdapter(activity, R.layout.myspinner, cateList) { - @Override - public View getDropDownView(int position, View convertView, - ViewGroup parent) { - TextView v = (TextView) super.getView(position, convertView, - parent); - // v.setMinimumHeight((int) (200* - // getResources().getDisplayMetrics().density)); - - v.setBackgroundResource(R.drawable.linearlayout_horizontal); - - // v.setTextAppearance(activity, R.style.ll_text_view_1); - v.setPadding(5, 8, 5, 8); - int selected = spWebInputType.getSelectedItemPosition(); - if (position == selected) { - v.setTypeface(null, Typeface.BOLD); - v.setBackgroundResource(R.drawable.head_linearlayout); - } - // - // v.getPaint().setFlags(0); - // v.setTypeface(null, Typeface.BOLD); - // LayoutParams lp = new LayoutParams(); - - v.setLayoutParams(new android.widget.AbsListView.LayoutParams( - LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); - return v; - } - };// ArrayAdapter.createFromResource( activity,R.array.webInputType, - // R.layout.thinspinner); - - // 设置下拉列表的风格 - spAdapterWeb.setDropDownViewResource(R.layout.spinner_item); - - // 将adapter2 添加到spinner中 - spWebInputType.setAdapter(spAdapterWeb); - // int type = activity.app.getLastTracktype(); //设置首选 - // spWebInputType.setSelection(type); - isSwitchWebInputOnly = true; // whe back from other fragment, no query - spWebInputType.setOnItemSelectedListener(null); - try { - setSpSelection(); - } catch (Exception er) { - - } - spWebInputType - .setOnItemSelectedListener(new SpinnerXMLSelectedListener()); - // setSpSelection(); - } - - class QArrayAdapter extends ArrayAdapter { - - public QArrayAdapter(Context context, int textViewResourceId, - List cateList) { - super(context, textViewResourceId, cateList); - // TODO Auto-generated constructor stub - } - - /* - * @Override public View getDropDownView(int position, View cnvtView, - * ViewGroup prnt){ LayoutInflater inflater = - * activity.getLayoutInflater(); View spinnerItem = inflater.inflate( - * R.layout.spinner_item, null); - * - * TextView mytext= - * (TextView)spinnerItem.findViewById(android.R.id.text1); - * mytext.setText(cateList.get(position)); - * - * //int selected = Spinner. int selected = - * spWebInputType.getSelectedItemPosition(); if(position == selected){ - * spinnerItem.setBackgroundColor(Color.BLUE); } return spinnerItem; - * - * } - */ - - } - - private int lastSelectedCateId = -1; - - void webSpinnerSelected(int spID) { - -// if (lastSelectedCateId == spID) { -// return; -// } - - setNote(); - -// lastSelectedCateId = spID; - - Map tmp = tabSpIndexValue.get(Integer - .valueOf(currentTab));// new HashMap(); - String oldV = ""; - if (tmp != null) { - oldV = tmp.get(Integer.valueOf(spID)); - txt_webinput.setText(oldV); - } - - activity.app.tabSpIndex.put(String.valueOf(currentTab), spID); - WebQueryCate wq = getSelectedCate(); - /* - * String selectedItem = spAdapterWeb.getItem(spID).toString(); - * WebQueryCate wq = WebQueryCate.LATEST; - * - * int cateIndex = totalList.indexOf(selectedItem); // wq = - * WebQueryCate.valueOf(cateIndex); if (cateIndex == -1){ - * if(BBSCity.equalsIgnoreCase(selectedItem)){ wq = WebQueryCate.CITY; } - * }else { wq = WebQueryCate.values()[cateIndex]; } - */ - txt_webinput.setVisibility(View.VISIBLE); - btn_webquery.setVisibility(View.VISIBLE); - switch (wq) { - case GEO: - - if (TextUtils.isEmpty(oldV)) { - txt_webinput.setText(QiYouConstant.PV_LAST_CITY); - } - txt_webinput.setInputType(InputType.TYPE_CLASS_TEXT); - break; - case KEYWORD: - - txt_webinput.setHint("请输入关键字"); - // txt_webinput.setText(""); - txt_webinput.setInputType(InputType.TYPE_CLASS_TEXT); - - break; - case USER: - - txt_webinput.setHint("请输入用户名"); - // txt_webinput.setText(""); - txt_webinput.setInputType(InputType.TYPE_CLASS_TEXT); - break; - case SVRNO: - - txt_webinput.setHint("请输入编号"); - // txt_webinput.setText(""); - txt_webinput.setInputType(InputType.TYPE_CLASS_NUMBER); - break; - default: - btn_webquery.setVisibility(View.GONE); - txt_webinput.setVisibility(View.GONE); - - /* - * if (isSwitchWebInputOnly){ isSwitchWebInputOnly = false; if - * (isFirstCreate){ //解决 首次创建时 不响应 cate item changed isFirstCreate = - * false; }else{ return; } } - */ - if (lastSelectedCateId == spID) { - return; - } - - lastSelectedCateId = spID; - - if (!firstLoad) { - doQuery(); - } else { - firstLoad = false; - } - break; - } - - } - - /* - * void initialTabSpIndex(){ - * - * - * initWebQueryTypeSpinWeb(); - * - * } - */ - // @Override - // void mapViewOnActivityCreated(){ - // - // } - @Override - void reNewShareOverflay() { - super.reNewShareOverflay(); - } - - @Override - void trackOnActivityCreated() { - // locData = new LocationData(); - } - - CheckBox.OnCheckedChangeListener m_checkboxListener = new CheckBox.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - // TODO Auto-generated method stub - switch (buttonView.getId()) { - case R.id.fm_chk_web_pic: - isShowPic = !chk_web_pic.isChecked(); - // doWebTrackQuery(); - break; - case R.id.fm_chk_show_pic: - doQuery(); - break; - case R.id.fm_chk_show_map: - doQuery(); - break; - - } - - } - - }; - - void initialWebInput() { - lastWebQueryPara = ""; - lastActQueryPara = ""; - lastGrpQueryPara = ""; - lastLiveQueryPara = ""; - pageNo = 1; - - } - - String webTab;// 活动,队伍,用户...; - String actTab;// "活动"; - String grpTab;// "队伍"; - String memberTab;// "驴友"; - String shareTab;// "分享"; - // String cloudTab; - String bbsTab; // bbs - TabHost.TabSpec tabTrack, tabAct, tabGrp, tabUser, tabBbs, tabLive, - tabRoadbook; - - protected void initialTabhost() { - bbsTab = getResources().getString(R.string.tab_bbs);// "云端"; - // cloudTab =getResources().getString(R.string.tab_cloud);//"云端"; - shareTab = getResources().getString(R.string.tab_share);// "分享"; - actTab = getResources().getString(R.string.tab_act);// "活动"; - grpTab = getResources().getString(R.string.tab_group);// "队伍"; - memberTab = getResources().getString(R.string.tab_users);// "驴友"; - - tabhost = (TabHost) vContainer.findViewById(R.id.queryTabhost); - if (tabhost == null) - return; - tabhost.setup(); - - creatTabs(); - addTabs(); - - initialTabhostStyle(tabhost); - - tabhost.setOnTabChangedListener(new OnTabChangeListener() { - @Override - public void onTabChanged(String tabId) { - - onMyTabChanged(tabId); - - } - }); - - } - - void creatTabs() { - - // tabhost.getTabWidget().setStripEnabled(false); - tabTrack = tabhost.newTabSpec(shareTab); - // t1.setIndicator(shareTab); - tabTrack.setContent(R.id.tab_webquery); - - tabTrack.setIndicator(shareTab/* - * , getResources().getDrawable(R.drawable. - * icon_upload,null) - */); - - tabAct = tabhost.newTabSpec(actTab); - tabAct.setIndicator(actTab/* - * , - * getResources().getDrawable(R.drawable.icon_star - * ,null) - */); - tabAct.setContent(R.id.tab_activity); - - tabGrp = tabhost.newTabSpec(grpTab); - tabGrp.setIndicator(grpTab/* - * , - * getResources().getDrawable(R.drawable.icon_group - * ,null) - */); - tabGrp.setContent(R.id.tab_group); - - tabUser = tabhost.newTabSpec(memberTab); - tabUser.setIndicator(memberTab/* - * , getResources().getDrawable(R.drawable. - * icon_user,null) - */); - tabUser.setContent(R.id.tab_members); - - tabBbs = tabhost.newTabSpec(bbsTab); - tabBbs.setIndicator(bbsTab/* - * , - * getResources().getDrawable(R.drawable.icon_user - * ,null) - */); - tabBbs.setContent(R.id.tab_bbs); - - /* - * t1=getTab(shareTab, R.drawable.icon_share ,R.id.tab_webquery); - * t2=getTab(actTab, R.drawable.icon_star ,R.id.tab_activity); - * t3=getTab(grpTab, R.drawable.icon_group ,R.id.tab_group); - * t4=getTab(memberTab, R.drawable.icon_user ,R.id.tab_members); - */ - - } - - void addTabs() { - // tabTrak,tabAct,tabGrp,tabUser,tabBbs - tabhost.addTab(tabBbs); - tabhost.addTab(tabTrack); - tabhost.addTab(tabAct); - tabhost.addTab(tabGrp); - tabhost.addTab(tabUser); - // tabhost.getTabWidget().setStripEnabled(true); - - } - - // 条目上单击处理方法. - int selectedTrackItem = -1; - int selectedActItem = -1; - int selectMemberItem = -1; - int selectActShareItem = -1; - int selectGroupItem = -1; - int selectedBBSItem = -1; - // boolean isActShareQuery=false; - boolean isShareQuery = false; - boolean canclick = true; - Handler handler; - - OnItemClickListener itemListener = new OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, - long id) { - - // QLog.getLogger().d(dTAG, - // String.format("adapter count %s,postion is %s", - // parent.getCount(),position)); - - if (parent.getCount() == position + 1 || !canclick) - return; - canclick = false; - - lastIndexOnMore = -1; - // isLoadMoreIndex =false; - selectedTrackItem = position; - selectedActItem = position; - selectMemberItem = position; - selectActShareItem = position; - selectedBBSItem = position; - if (isWebTrackQuery || isShareQuery) { - - // Track track =showWebTrackDetail(position); - showWebTrack(getWebTrackDetail(position)); - canclick = true; - return; - } - - if (isActivityQuery) { - - // do activity query clicked - showActivityDetail(position); - canclick = true; - return; - } - - if (isMemberQuery) { - - // do activity query clicked - showMemberDetail(position); - canclick = true; - return; - } - - if (isGroupQuery) { - showGroupDetail(position); - canclick = true; - return; - } - - if (isBBSQuery) { - showNoteDetail(position); - canclick = true; - return; - } - } - - }; - - @Override - void loadingMore() { - - // QLog.getLogger().d(dTAG, "------ can loading more 2 .. " + - // canLoadingMore); - - isLoadingMore = true; - // isLoadMoreIndex=true; - lastIndexOnMore = visibleLastIndex; - if (this.isWebTrackQuery) { - lastWebQueryPara = ""; - pageNo++; - doWebTrackQuery(); - } else if (this.isActivityQuery) { - lastActQueryPara = ""; - pageNo++; - doActQuery(); - } else if (isMemberQuery) { - lastMemberQueryPara = ""; - pageNo++; - doUserQuery(); - } else if (isGroupQuery) { - lastGrpQueryPara = ""; - pageNo++; - doGroupQuery(); - } else if (isBBSQuery) { - // lastGrpQueryPara=""; - pageNo++; - doBBSQuery(); - - } - - } - - boolean validInput() { - if (this.spWebInputType == null || txt_webinput == null) - return true; - - if (txt_webinput.getVisibility() == View.VISIBLE) { - if (TextUtils.isEmpty(txt_webinput.getText())) { - txt_webinput.setSelected(true); - if (mSwipeLayout != null) { - mSwipeLayout.setRefreshing(false); - } - return false; - } - } - return true; - - } - - List> trackData; - List> actData; - List> grpData; - - @Override - public void initialWebQuery() { - - pageNo = 1; - if (!validInput()) { - return; - } - if (this.isActivityQuery) { - this.actData = null; - pageNo = 1; - lastActQueryPara = ""; - doActQuery(); - } else if (this.isWebTrackQuery) { - lastWebQueryPara = ""; - this.pageNo = 1; - this.trackData = null; - doWebTrackQuery(); - } else if (isMemberQuery) { - lastMemberQueryPara = ""; - pageNo = 1; - this.userData = null; - - doUserQuery(); - } else if (isGroupQuery) { - lastGrpQueryPara = ""; - pageNo = 1; - this.grpData = null; - - doGroupQuery(); - } else if (isBBSQuery) { - lastNoteQueryPara = ""; - pageNo = 1; - this.bbsData = null; - - doBBSQuery(); - } - if (spWebInputType == null) { - return; - } - // when query remember the webinput query parameters for currenttab - if (txt_webinput.getVisibility() == View.VISIBLE){ - Map tmp = new HashMap(); - tmp.put(spWebInputType.getSelectedItemPosition(), txt_webinput - .getText().toString()); - tabSpIndexValue.put(currentTab, tmp);// remember the currentTab,and its - // selected webinput sp's item - // and value. - activity.app.tabSpIndex.put(String.valueOf(currentTab), - this.spWebInputType.getSelectedItemPosition());// remember the - // current tab's - } // sp item - } - - @Override - public void doQuery() { - if (!validInput()) { - - return; - } - switchTabOptions(currentTab); - this.initialWebQuery(); - - } - - // ---------------------begin web track query----------------------- - - /* - * int pageNo=1; int pageSize=10; List> trackData; - */ - void doWebTrackQuery() { - Utils.hideSoftKeyboard(activity); - // noRec.setVisibility(View.GONE); - isWebTrackQuery = true; - // lvWeb.setVisibility(View.VISIBLE); - // lv.setVisibility(View.GONE); - // QLog.getLogger().d(dTAG, TAG+"------begin web query--------- "); - - // getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo); - // lastWebQueryPara - - if (this.firstLoad && !TextUtils.isEmpty(lastWebQueryPara)) { - // QLog.getLogger().d(dTAG, - // String.format("firstLoad %s,lastWebQueryPara %s ", - // firstLoad,lastWebQueryPara)); - return; - } - RequestParams param = buildTrackQueryParames(); - if (param != null - && !lastWebQueryPara.equalsIgnoreCase(param.toString())) { - - // QLog.getLogger().d(dTAG, lastWebQueryPara); - // QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param, RestMethods.TRACK_G_LIST/* "mb/track/list" */); - lastWebQueryPara = param.toString(); - selectedTrackItem = -1; - - } - - } - - RequestParams buildTrackQueryParames() { - - // RequestParams params =buildBasicParames(pageNo,webTrackType); - // //default to get last sport type from web? - // TrackType tmp = TrackType.valueOf(webTrackType); - - RequestParams params = buildBasicParames(pageNo, -1); - - params.add("showpic", String.valueOf(isShowPic)); - params.add("swidth", String.valueOf(QiYouConstant.PV_INT_SCREEN_WIDTH)); - params.add("sheight", - String.valueOf(QiYouConstant.PV_INT_SCREEN_HEIGHT)); - params.add("isMyOnly", String.valueOf(isShowMytrackOnly)); - - return params; - } - - @Override - void processTrackJsonArray(JSONArray jsonArrary) { - - /* trackData = getWebTrackList( jsonArrary); */ - - // trackData = initialListData( trackData ); - // trackData.addAll(getWebTrackList( jsonArrary)); - trackData = getListData(trackData, getWebTrackList(jsonArrary)); - - - if (!isLiveQuery) { - showNoRecText(trackData.size() == 0); - showWebTrackListData(trackData); - } - // QLog.getLogger().e(dTAG, - // String.format("trackPageNo is%s, actual pageno is %s ",pageNo,trackData.size()/pageSize)); - - /* - * if( lvAdapter !=null){ lvAdapter.notifyDataSetChanged(); }else{ - * showWebTrackListData(trackData); } - */ - - /* - * SimpleAdapter is meant for static data, so your performance may vary. - * The best solution is probably to switch to a different type of - * adapter, such as ArrayAdapter, or make a new SimpleAdapter every time - * you change the dataset - */ - - } - void showLive() {} - List> getWebTrackList(JSONArray jsonArrary) { - List> webData = new ArrayList>(); - JSONObject jo = null; - Track_bean tb; - Track tr;// = new Track(); - if (jsonArrary != null) - for (int i = 0; i < jsonArrary.length(); i++) { - try { - jo = jsonArrary.getJSONObject(i); - if (jo == null) - continue; - // // QLog.getLogger().d(dTAG, "jsonarray:--> " - // +jo.toString()); - tb = (Track_bean) Utils.getGsonObject(jo.toString(), - Track_bean.class); - - } catch (JsonSyntaxException je) { - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - if (tb != null) { - tr = new Track(tb); - Map t = new HashMap(); - t.put("name", tb.getName()); - t.put("svrNumber", tb.getSvrNumber() + ""); - t.put("start", Utils.getFormatedTime(tb.getStartTime(), - dateFormatDDMMYY)); - t.put("distance", - String.format("%.2f", tb.getDistance() / 1000)); - // t.put("sportime", Utils.getTimeCnt(tb.getSportTime(), - // true)); - - - - float avs = tb.getType() == TrackType.GPX ? activity.app.getAVS() : tb.getAvs(); - - long sptime = tb.getType() ==TrackType.GPX ? (long)( tb.getDistance() / avs *3600) : tb.getTotalTime(); - t.put("sportime", Utils.getTimeCnt(sptime, true)); - // t.put("avs", String.format("%.2f",tb.getAvs())); - t.put("avs", String.format("%.2f", avs)); - -// t.put("sportime", Utils.getTimeCnt(tb.getTotalTime(), true)); -// // t.put("avs", String.format("%.2f",tb.getAvs())); -// t.put("avs", String.format("%.2f", tb.getTavs())); - t.put("cal", String.format("%.2f", tb.getBurn())); - t.put("comment", tb.getComment()); - t.put("desc", - Utils.getShortString(tb.getDescription(), STRLNG)); - t.put("summary", "");// tb.getSummary()); - t.put("creator", tb.getCreator()); - t.put("avstatus", tb.getAvStatus().toString()); - - /* - * String staticMapUrl - * =isShowPic?Utils.getBaiduStaticMapUrl(tr):""; // String - * staticMapUrl - * =Utils.getBaiduStaticUrlFromServer(tb.getSvrNumber()); // - * QLog.getLogger().d(dTAG, - * " static map url is: "+staticMapUrl); // - * QLog.getLogger().i(dTAG, - * " static map url is: "+staticMapUrl); t.put("staticmap", - * staticMapUrl ); - */ - - try { - t.put("userName", jo.getString("userName")); - - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - t.put("lastupdated", String.valueOf(tb.getLastdbTime())); - // t.put("cloud", "云:" ); - // // QLog.getLogger().d(dTAG, "svrNumber:--> " + - // tb.getSvrNumber()); - // // QLog.getLogger().d(dTAG, "sportime:--> " + - // t.get("sportime") - // +"...."+Utils.getTimeCnt(tb.getTotalTime(), true)); - // // QLog.getLogger().d(dTAG, "avs:--> " + - // t.get("avs")+"...."+ String.format("%.2f",tb.getTavs())); - // // QLog.getLogger().d(dTAG, "lastupdated:--> " + - // String.valueOf(tb.getLastdbTime())); - - t.put("type", String.valueOf(tb.getType())); - - // String[] urls=tr.getWebPicList(4, true); - - String strUrls = ""; - if (isShowPic) { - t.put("staticmap", tb.getStaticMapUrl()); - - if (tb.getThumbUrls() != null) - for (String url : tb.getThumbUrls()) { - // // QLog.getLogger().d(dTAG, " url is" +url); - strUrls += QiYouConstant.BASE_MD_URL + url - + QiYouConstant.SPLITOR; - } - } - t.put("urls", strUrls); - webData.add(t); - } - - } - - return webData; - - } - - /* - * void getPicUrls(){ imgUrls= mTrack.getPicList(); - * ValidUrls=mTrack.getValidPicList(); - * - * } - */ - - // QSimpleAdapter lvAdapter; - - int currentRow = 0; - - protected void showWebTrackListData(List> trackData) { - // this.btn_pagedown.setEnabled(!isLastPage); - // this.btn_pageup.setEnabled(!isFirstPage); - - lvAdapter = new QSimpleAdapter(activity, trackData, - R.layout.track_list_detail, new String[] { "start", "distance", - "avs", "cal", "comment", "sportime", "summary", "name", - "urls" - // ,"creator" - // ,"cloud" - , "svrNumber", "userName", "staticmap", "avstatus" }, - new int[] { R.id.trakList_tv_starttime, R.id.trakList_tv_dist, - R.id.trakList_tv_avs, R.id.trakList_tv_burn, - R.id.trakList_tv_comment, R.id.trakList_tv_sportTime, - R.id.trakList_tv_desc, R.id.trakList_tv_name, - R.id.trakList_gridView - // ,R.id.trakList_tv_creator - // ,R.id.trakList_tv_cloud - , R.id.trakList_tv_svrNo, R.id.trakList_tv_creator - - // ,R.id.trakList_tv_showGpx - , R.id.trakList_staticMap, R.id.trakList_avStatusImg }); - currentRow = 0; - lvAdapter.setViewBinder(new ViewBinder() { - - @Override - public boolean setViewValue(View view, Object data, - String textRepresentation) { - currentRow++; - TextView text; - switch (view.getId()) { - case R.id.trakList_tv_name: { - text = (TextView) view; - - String str = "未命名"; - if (data != null) { - str = Utils.getShortString(data.toString(), 6); - } - text.setText(str); // set some data - text.setVisibility(View.VISIBLE); - - return true; - } - - case R.id.trakList_tv_creator: { // track title - if (!isShowMytrackOnly && data != null) - view.setVisibility(View.VISIBLE); - - return false; - } - - case R.id.trakList_tv_svrNo: { - if (data != null) { - text = (TextView) view; - text.setText("" + data); - } - // QLog.getLogger().d(dTAG, " displaying server number " + - // data.toString()); - return true; - } - - case R.id.trakList_staticMap: { - // TextView text = (TextView) view; // get your View - com.qiyou.mb.android.utils.image.QimageView imgv = (com.qiyou.mb.android.utils.image.QimageView) view; - imgv.setVisibility(View.GONE); - if (data == null || data.toString().length() < 10) - return true; - // QLog.getLogger().d(dTAG, " displaying static image of " + - // data.toString()); - IL.DisplayImage(data.toString(), imgv); - imgv.setVisibility(View.VISIBLE); - - return true; - } - - case R.id.trakList_tv_desc: { - text = (TextView) view; - String str = null; - if (data != null) { - str = Utils.getShortString(data.toString(), 20); - } - if (TextUtils.isEmpty(str)) - text.setVisibility(View.GONE); - else { - text.setText(str); // set some data - text.setVisibility(View.VISIBLE); - } - return true; - } - - case R.id.trakList_tv_comment: { - // TextView text = (TextView) view; // get your View - text = (TextView) view; - - String str = null; - if (data != null) { - str = Utils.getShortString(data.toString(), 20); - } - if (TextUtils.isEmpty(str)) - text.setVisibility(View.GONE); - else { - text.setText(str); // set some data - text.setVisibility(View.VISIBLE); - } - - return true; - } - case R.id.trakList_avStatusImg: { - com.qiyou.mb.android.utils.image.QimageView imgv = (com.qiyou.mb.android.utils.image.QimageView) view; - imgv.setVisibility(View.GONE); - if (data == null - || !data.toString().equalsIgnoreCase( - TrackAvStatus.PRIVATE.toString())) - return true; - // QLog.getLogger().d(dTAG, - // " displaying available image of " + data.toString()); - imgv.setBackgroundResource(R.drawable.icon_lock); - imgv.setVisibility(View.VISIBLE); - return true; - } - - case R.id.trakList_gridView: { - - // int picCnt=4; - - String[] Urls = ((String) data) - .split(QiYouConstant.SPLITOR_KEY); - // String[] Urls=getImages(cursor.getString(8),picCnt); - // //pic cnt = screen.width/80 - NoScrollGridView gridView = (NoScrollGridView) view; - gridView.setVisibility(View.GONE); - // QLog.getLogger().d(dTAG, - // TAG+" checking if the urls is empty.......... "); - if (TextUtils.isEmpty((String) data)) - return true; - - if (Urls != null && Urls.length > 0) { - // QLog.getLogger().d(dTAG, - // TAG+" checking if the urls is empty "+(String)data); - - gridView.setVisibility(View.VISIBLE); - gridView.setAdapter(new ImageGridAdapter(Urls, activity)); - gridView.setFocusable(false); - - // gridView.setOnItemClickListener(itemListener); - // gridView.cursorPosition=currentRow; - - /* - * how to get current row of lvWeb - * http://stackoverflow.com - * /questions/17394498/android-bind - * -data-to-listview-without-cursor - * - * @Override public View getView(int position, View - * convertView, ViewGroup parent) { - * - * gridView.setOnItemClickListener(new - * AdapterView.OnItemClickListener() { - * - * @Override public void onItemClick(AdapterView - * parent, View view, int position, long id) { int mpos - * = ((NoScrollGridView)parent).cursorPosition; - * lvWeb.performItemClick - * (lvWeb.getAdapter().getView(mpos, null, null), mpos, - * mpos); - * - * } }); - */ - - } - - return true; - } - - } - return false; - } - }); - - // selectedTrackItem =visibleLastIndex - visibleItemCnt + 1; - - /* - * selectedTrackItem - * =lastIndexOnMore>0?lvAdapter.getCount()-pageSize:selectedTrackItem; - * lvWeb.addFooterView(ll_loadmore); - * - * lvWeb.setAdapter(lvAdapter); if(lastIndexOnMore<=0){ - * lvAdapter.setSelectItem(selectedTrackItem); } - * lvWeb.setSelection(selectedTrackItem); - */ - - bindListView(lvAdapter, lvWeb, selectedTrackItem, isTrackLastPage); - - // lvWeb.setSelection(isLoadMoreIndex?visibleLastIndex - - // visibleItemCnt-1:selectedTrackItem); - - // lvWeb.setSelection(); //设置选中项 - // adapter.setSelectItem(selectedFoodmarkItem); - // lv.setSelection(selectedFoodmarkItem); - - // lv.smoothScrollToPosition(selectedFoodmarkItem); - // lv.smoothScrollToPositionFromTop(selectedFoodmarkItem, 50); - } - - /* - * int svrNumber; int svrTrackType; long lastupdated; - */ - - Track getWebTrackDetail(int position) { - -// if (trackData /* lvAdapter */== null /* || this.lvAdapter.getCount()==0 */) { -// return null; -// } - - if(isWebTrackQuery && trackData == null ){ - return null; - } - - if ( lvAdapter == null || this.lvAdapter.getCount()==0 ) { - return null; - } - Track track = null; - - try { - // this.lvAdapter.setSelectItem(position); - // this.lvAdapter.notifyDataSetInvalidated(); - // this.lvWeb.setSelection(position); -// HashMap localHashMap = (HashMap) trackData -// .get(position); // this.lvAdapter.getItem(position); - HashMap localHashMap = isWebTrackQuery ? (HashMap) trackData - .get(position) :(HashMap) this.lvAdapter.getItem(position); - - this.trackSvrNumber = Integer.parseInt(localHashMap - .get("svrNumber")); - this.svrTrackType = Integer.parseInt(localHashMap.get("type")); - this.lastupdated = Long.parseLong(localHashMap.get("lastupdated")); - // }catch(NumberFormatException ne ){ - // Utils.logStackTrace(ne, TAG); - // showNotes("出错了"); - // return; - // } - // QLog.getLogger().d("com.qiyou", TAG + - // " get selected trackSvrNumber:" + this. trackSvrNumber); - - // try{ - - // requestTrackFromWeb(); - // long start=System.currentTimeMillis(); - - // track = getTrackFromWebCache(String.valueOf(svrNumber) + - // this.lastupdated); - track = getTrackFromWebCache(trackSvrNumber, this.lastupdated); - // // QLog.getLogger().d(dTAG, - // " load track cost "+(System.currentTimeMillis()-start )); - - // if(track!=null){ - // // QLog.getLogger().d(dTAG, - // " mtrack_bean startwp: "+mTrack_bean.getStartWp().toString()); - // // QLog.getLogger().d(dTAG, - // " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); - // // QLog.getLogger().d(dTAG, - // " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); - // track.getTrackBean().getTrkseg().clear(); - // // QLog.getLogger().d(dTAG, " track is"+track.toString()); - - // } - - } catch (NumberFormatException ne) { - Utils.logStackTrace(ne, TAG); - showNotes("出错了"); - return null; - } catch (IOException localIOException) { - Utils.logStackTrace(localIOException, TAG); - } catch (java.lang.IndexOutOfBoundsException IndexException) { - Utils.logStackTrace(IndexException, TAG); - } catch (Exception er) { - Utils.logStackTrace(er, TAG); - } - - if ((track != null) - && (track.getTrackBean().getSvrNumber() == this.trackSvrNumber)) { - return track; - - } else { - requestTrackFromWeb(this.trackSvrNumber); - return null; - } - } - @Override - void showWebTrack(Track tr){ - if(tr==null)return; - this.activity.app.setCurrentTrack(tr,true); -// showDetailTrack( this.svrNumber ); - activity.showGpxTrackDetail( tr.getTrackBean().getType().toInt() , tr.getTrackBean().getSvrNumber(), true); - } - // -------------------------------------------------------------web query - // end-------------------- - - // -------------------------------------------------------------activity - // query begin -------------------------------------- - - /* - * int pageNo=1; List> actData; - */ - - void doActQuery() { - Utils.hideSoftKeyboard(activity); - // noRec.setVisibility(View.GONE); - isActivityQuery = true; - // lvWeb.setVisibility(View.VISIBLE); - // lv.setVisibility(View.GONE); - // QLog.getLogger().d(dTAG, TAG+"------begin Act query--------- "); - - // getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo); - // lastWebQueryPara - - if (this.firstLoad && !TextUtils.isEmpty(lastActQueryPara)) { - return; - } - RequestParams param = buildActQueryParames(); - if (param != null - && !lastActQueryPara.equalsIgnoreCase(param.toString())) { - - // QLog.getLogger().d(dTAG, lastActQueryPara); - // QLog.getLogger().d(dTAG, - // RestMethods.ACT_G_LIST+"?"+param.toString()); - - getJsonWs(param, RestMethods.ACT_G_LIST/* "mb/activity/list" */); - lastActQueryPara = param.toString(); - selectedActItem = -1; - - } - - } - - RequestParams buildActQueryParames() { - RequestParams params = buildBasicParames(pageNo, -1); - - return params; - } - - /* - * RequestParams buildNearByQueryParames(){ RequestParams params = new - * RequestParams(); - * - * // String svrNo= edSvrNo.getText().toString(); int page=1; - * if(isActivityQuery){ page=pageNo; // - * QLog.getLogger().d(dTAG," building activity nearby query...."); }else - * if(isGroupQuery){ page=pageNo; // - * QLog.getLogger().d(dTAG," building group nearby query...."); - * - * }else{ // QLog.getLogger().e(dTAG, - * " neither activity nore group nearby query....pls check, return null"); - * - * return null; } params.add("page", String.valueOf(page)); - * params.add("pagesize", String.valueOf(pageSize)); - * //QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON - * params.add("lat",String.valueOf(QiYouConstant.PV_LAST_LAT)); - * params.add("lon",String.valueOf(QiYouConstant.PV_LAST_LON)); - * params.add("memberId" - * ,String.valueOf(activity.app.user.getUserbean().getId())); - * - * if(!TextUtils.isEmpty(svrNo)){ params.add("svrNo", svrNo); } - * - * // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - * - * return params; } - */ - - /* - * void doActNearbyQuery(){ Utils.hideSoftKeyboard(activity); - * noRec.setVisibility(View.GONE); isActivityQuery=true; // - * lvWeb.setVisibility(View.VISIBLE); // lv.setVisibility(View.GONE); // - * QLog.getLogger().d(dTAG, TAG+"------begin Act Nearby query--------- "); - * - * // getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo); // - * lastWebQueryPara - * - * if(this.firstLoad&&!TextUtils.isEmpty(lastActQueryPara)){ return; } - * RequestParams param=buildNearByQueryParames(); if(param!=null && - * !lastActQueryPara.equalsIgnoreCase(param.toString()) ){ - * - * // QLog.getLogger().d(dTAG, lastActQueryPara); // - * QLog.getLogger().d(dTAG, param.toString()); - * - * getJsonWs(param,RestMethods.ACT_G_LIST"mb/activity/nearbylist"); - * lastActQueryPara =param.toString(); selectedActItem =-1; - * - * } - * - * } - */ - - /* - * boolean isActFirstPage; boolean isActLastPage; void - * processActPageInfo(JSONObject jo) throws JSONException{ - * - * // jo.getInt("totalPages"); isActLastPage =jo.getBoolean("last"); - * isActFirstPage =jo.getBoolean("first"); // jo.get("size");//pagesize // - * jo.get("totalElements"); //总数 // jo.get("numberOfElements");//返回个数 // - * jo.get("number"); - * - * // this.btn_pagedown.setEnabled(!isLastPage); // - * this.btn_pageup.setEnabled(!isFirstPage); - * processActJsonArray(jo.getJSONArray("content")); } - */ - - private final String dateFormatDDMMYY = "yyyy.MM.d HH:mm"; - - @Override - void processActJsonArray(JSONArray jsonArrary) { - - tmpData = new ArrayList>(); - - JSONObject jo = null; - Activity_bean ab; - - GEOaddress startgeo, endgeo; - - if (jsonArrary != null) - for (int i = 0; i < jsonArrary.length(); i++) { - try { - jo = jsonArrary.getJSONObject(i); - if (jo == null) - continue; - // // QLog.getLogger().d(dTAG, "jsonarray:--> " - // +jo.toString()); - ab = (Activity_bean) Utils.getGsonObject(jo.toString(), - Activity_bean.class); - - } catch (JsonSyntaxException je) { - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - if (ab != null) { - // tr= new Track(tb); - Map t = new HashMap(); - startgeo = new GEOaddress(ab.getStartGeo()); - endgeo = new GEOaddress(ab.getEndGeo()); - - t.put("name", ab.getName()); - t.put("svrNumber", ab.getSvrNumber() + ""); - t.put("startTime", Utils.getFormatedTime(ab.getStartDate(), - dateFormatDDMMYY)); - t.put("endTime", Utils.getFormatedTime(ab.getEndDate(), - dateFormatDDMMYY)); - t.put("description", - Utils.getShortString(ab.getDescription(), STRLNG)); - - t.put("startPlace", - String.format("%s %s", ab.getStartPlace(), - startgeo.toString(",")).replace("null", "")); - t.put("endPlace", - String.format("%s %s", ab.getEndPlace(), - endgeo.toString(startgeo, ",")).replace( - "null", "")); - t.put("shangquan", ab.getStartGeo().getComment()); - t.put("status", ab.getStatus().toString()); - t.put("memberCnt", ab.getUserCnt() + ""); - t.put("userName", ab.getUserName()); - - String dist = ab.getLat() > 0 && QiYouConstant.PV_LAST_LAT > 0 ? String.format("距你 %s,", Utils.getDistanceRange(0,ab.getLat(), ab.getLon())) : "" ; - t.put("distrg",dist + getTimeLeft(ab)) ; - -// t.put("distrg",dist + String.format("距你 %s , %s", Utils -// .getDistanceRange(/* ab.getDistrange() */0, -// ab.getLat(), ab.getLon()), getTimeLeft(ab))); - - // t.put("timeLeft", "当前距活动开始剩余时间:" + getTimeLeft(ab)); - t.put("lastupdated", ab.getLastupdated() + ""); - /* - * String staticMapUrl - * =isShowPic?Utils.getBaiduStaticMapUrl(tr):""; // String - * staticMapUrl - * =Utils.getBaiduStaticUrlFromServer(tb.getSvrNumber()); // - * QLog.getLogger().d(dTAG, - * " static map url is: "+staticMapUrl); // - * QLog.getLogger().i(dTAG, - * " static map url is: "+staticMapUrl); t.put("staticmap", - * staticMapUrl ); - */ - - try { - t.put("userName", jo.getString("userName")); - - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - // t.put("lastupdated", String.valueOf(ab.getLastdbTime()) - // ); - // t.put("cloud", "云:" ); - // QLog.getLogger().d(dTAG, "svrNumber:--> " + - // ab.getSvrNumber()); - // // QLog.getLogger().d(dTAG, "lastupdated:--> " + - // String.valueOf(ab.getLastdbTime())); - - t.put("type", String.valueOf(ab.getType())); - - t.put("dist", String.valueOf(ab.getDistance())); - t.put("avs", String.valueOf(ab.getAvSpeed())); - t.put("rateLevel", String.format("%.0f", ab.getRateLevel())); - t.put("timelong", - ab.getAvSpeed() > 0 ? String.format("%.0f", - ab.getDistance() / ab.getAvSpeed()) : "--"); - t.put("userCnt", String.valueOf(ab.getUserCnt())); - - // String[] urls=tr.getWebPicList(4, true); - - String strUrls = ""; - if (isShowPic) { - /* - * t.put("staticmap", ab.getStaticMapUrl() ); - * - * if(tb.getThumbUrls()!=null) for(String - * url:tb.getThumbUrls()){ // QLog.getLogger().d(dTAG, - * " url is" +url); - * strUrls+=QiYouConstant.BASE_MD_URL+url - * +QiYouConstant.SPLITOR; } - */ - } - t.put("urls", strUrls); - tmpData.add(t); - } - - } - - actData = getListData(actData, tmpData); - - showNoRecText(actData.size() == 0); - - showActData(); - - // QLog.getLogger().e(dTAG, - // String.format("pageNo is%s, actual pageno is %s ",pageNo,actData.size()/pageSize)); - - } - - String getTimeLeft(Activity_bean ab) { - - // String rtformat="活动开始还有:%s天"; - String rtformat = " %s天后开始"; - String startSoon = " 即将开始"; - String startted = "已经开始"; - String expired = "已经结束"; - int days; - if (ab.isRepeatable()) { - - long diff = ab.getStartDate() - System.currentTimeMillis(); - days = Utils.getDayscnt(diff); - if (diff >= 0) { // not started yet - // return prefix+ Utils.getDayscnt(diff); - if (days > 0) - return String.format(rtformat, days); - else - return startSoon; - } else if (ab.getEndDate() > 0) { - if (ab.getEndDate() > System.currentTimeMillis()) { - // return startted; - } else { - return expired; - } - } - - if (ab.getDays().size() == 0) { - return ""; - } - - Calendar c = Calendar.getInstance(); - int currentDay = c.get(Calendar.DAY_OF_WEEK) - 1; - // int minDay=8; - int nextDay = currentDay; - for (int i : ab.getDays()) { - if (nextDay < i) { - nextDay = i; - break; - } - - } - - if (nextDay > currentDay) { // 本周 - - days = nextDay - currentDay; - - } else { // next week - days = 7 - currentDay + ab.getDays().get(0); - } - - // return prefix+( days>0?(days+"天"):""); - if (days > 0) { - return String.format(rtformat, days); - } else { - return startSoon; - } - - } else { - if (System.currentTimeMillis() < ab.getStartDate()) { - // return prefix+ Utils.getDayscnt(ab.getStartDate() - // -System.currentTimeMillis() ); - days = Utils.getDayscnt(ab.getStartDate() - - System.currentTimeMillis()); - if (days > 0) { - return String.format( - rtformat, - Utils.getDayscnt(ab.getStartDate() - - System.currentTimeMillis())); - } else { - return startSoon; - } - } else { - if (ab.getEndDate() > 0) { - if (ab.getEndDate() > System.currentTimeMillis()) { - return startted; - } else { - return expired; - } - } - - return startted; - } - - } - - } - - // QSimpleAdapter lvAdapter; - - int currentActRow = 0; - - protected void showActData() { - // this.btn_pagedown.setEnabled(!isActLastPage); - // this.btn_pageup.setEnabled(!isActFirstPage); - - lvAdapter = new QSimpleAdapter(activity, actData, - R.layout.activity_list_detail, new String[] { "name", - "svrNumber", "startTime", "endTime", "startPlace", - "endPlace", "memberCnt", "shangquan", "description", - "status", "type", "distrg", "dist", "avs", "rateLevel", - "timelong", "userName" - - }, new int[] { R.id.actList_name, R.id.actList_svrNo, - R.id.actList_starttime, R.id.actList_endtime, - R.id.actList_startplace, R.id.actList_endplace, - R.id.actList_memberCnt, R.id.actList_shangquan, - R.id.actList_desc, R.id.actlist_status, - R.id.actlist_type, R.id.actList_distRange, - R.id.actList_dist, R.id.actList_avs, - R.id.actList_level, R.id.actList_sportTime, - R.id.actList_owner }); - - // - // lvWeb.setAdapter(lvAdapter); - // - // lvAdapter.setSelectItem(selectedActItem); - // lvWeb.setSelection(selectedActItem); - - bindListView(lvAdapter, lvWeb, selectedActItem, isActLastPage); - - /* - * selectedActItem - * =lastIndexOnMore>0?lvAdapter.getCount()-pageSize:selectedActItem; - * lvWeb.addFooterView(ll_loadmore); - * - * lvWeb.setAdapter(lvAdapter); if(lastIndexOnMore<=0){ - * lvAdapter.setSelectItem(selectedActItem); } - * lvWeb.setSelection(selectedActItem); - */ - - } - - /* - * int actSvrNumber; int actType; long actLastupdated; - */ - - void showActivityDetail(int position) { - int actSvrNumber = 0; - Activity_bean act = null; - if (lvAdapter == null || lvAdapter.getCount() <= position) { - // QLog.getLogger().e(dTAG, - // "wrong group position clicked,reurn...."); - return; - } - try { - this.lvAdapter.setSelectItem(position); - this.lvAdapter.notifyDataSetInvalidated(); - this.lvWeb.setSelection(position); - HashMap localHashMap = (HashMap) this.lvAdapter - .getItem(position); - actSvrNumber = Integer.parseInt(localHashMap.get("svrNumber")); - if (localHashMap.get("type") != null - && !localHashMap.get("type").equalsIgnoreCase("null")) { - try { - this.actType = Integer.parseInt(localHashMap.get("type")); - } catch (NumberFormatException ne) { - Utils.logStackTrace(ne, TAG); - } - } - this.actLastupdated = Long.parseLong(localHashMap - .get("lastupdated")); - // }catch(NumberFormatException ne ){ - // Utils.logStackTrace(ne, TAG); - // showNotes("出错了"); - // return; - // } - // QLog.getLogger().d("com.qiyou", TAG + - // " get selected actSvrNumber:" + actSvrNumber); - - // try{ - - // requestTrackFromWeb(); - long start = System.currentTimeMillis(); - - // track = getTrackFromWebCache(String.valueOf(svrNumber) + - // this.lastupdated); - // act = getActFromWebCache( actSvrNumber, this.actLastupdated); - // QLog.getLogger().d(dTAG, - // " load act cost "+(System.currentTimeMillis()-start )); - - // if(track!=null){ - // // QLog.getLogger().d(dTAG, - // " mtrack_bean startwp: "+mTrack_bean.getStartWp().toString()); - // // QLog.getLogger().d(dTAG, - // " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); - // // QLog.getLogger().d(dTAG, - // " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); - // track.getTrackBean().getTrkseg().clear(); - // // QLog.getLogger().d(dTAG, " track is"+track.toString()); - - // } - - } catch (NumberFormatException ne) { - Utils.logStackTrace(ne, TAG); - showNotes("出错了"); - return; - } - // catch (IOException localIOException){ - // Utils.logStackTrace(localIOException, TAG); - // } - catch (java.lang.IndexOutOfBoundsException IndexException) { - Utils.logStackTrace(IndexException, TAG); - } catch (Exception er) { - Utils.logStackTrace(er, TAG); - } - - if (actSvrNumber <= 0) { - return; - } - - // if ((act != null) && (act.getSvrNumber() == actSvrNumber)){ - // showActivity(act); - // - // } - // else - requestActFromWeb(actSvrNumber); - } - - void requestActFromWeb(int svrNo) { - RequestParams params = new RequestParams(); - params.add("id", String.valueOf(svrNo)); - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params, RestMethods.ACT_G_FIND_BY_ID/* "mb/activity/" */); - // long l1 = System.currentTimeMillis(); - // // QLog.getLogger().d("com.qiyou", TAG + - // " start Click item to show track detail, time is:" + l1); - // getJsonWs(null, "mb/track/" + this.svrNumber); - // /long l2 = System.currentTimeMillis() - l1; - // // QLog.getLogger().d("com.qiyou", TAG + " get data from web cost:" + - // l2); - } - - /* - * void checkActUserWs(RequestParams params,String url){ - * if(prgDialog==null)initPrgDialog(); // if(this.isAdded()) - * prgDialog.show(); showWebDialog(); hideNotes(); - * - * QiYouApplication.get(url, params, new JsonHttpResponseHandler() { - * - * @Override public void onSuccess(int statusCode, Header[] headers, - * JSONObject response) { prgDialog.hide(); // QLog.getLogger().d(dTAG, TAG+ - * ", onSuccess(int statusCode, Header[] headers, JSONObject response) was received" - * ); - * - * // if (response != null) { try { checkActUserResult( response); } catch - * (JSONException e) { // TODO Auto-generated catch block - * e.printStackTrace(); } - * - * // } } }); } - */ - - // void checkActUserResult( JSONObject response) throws JSONException { - // - // } - - // ---------------------------------------------------------activity query - // end---------------------------------------------- - - // ---------------------------------------------------------member query - // begin---------------------------------------------- - - int userId; - List> userData; - - void doUserQuery() { - Utils.hideSoftKeyboard(activity); - // noRec.setVisibility(View.GONE); - isMemberQuery = true; - // lvWeb.setVisibility(View.VISIBLE); - // lv.setVisibility(View.GONE); - // QLog.getLogger().d(dTAG, TAG+"------begin Member query--------- "); - - // getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo); - // lastWebQueryPara - - if (/* - * activity.currentAcitiviy ==null || - * activity.currentAcitiviy.getSvrNumber()==0 || - */ - this.firstLoad && !TextUtils.isEmpty(lastMemberQueryPara)) { - return; - } - RequestParams param = buildMemberQueryParames(); - if (param != null - && !lastMemberQueryPara.equalsIgnoreCase(param.toString())) { - - // QLog.getLogger().d(dTAG, lastActQueryPara); - // QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param, RestMethods.USER_G_LIST /* "mb/user/actusers" */); - lastMemberQueryPara = param.toString(); - selectMemberItem = -1; - - } - - } - - RequestParams buildMemberQueryParames() { - RequestParams params = buildBasicParames(pageNo, -1); - return params; - /* - * RequestParams params = new RequestParams(); // - * params.add("lat",String.valueOf(QiYouConstant.PV_LAST_LAT)); // - * params.add("lon",String.valueOf(QiYouConstant.PV_LAST_LON)); String - * city =webCity!=null?webCity.getText().toString().trim():null; - * if(!TextUtils.isEmpty(city)){ try { city - * =URLEncoder.encode(webCity.getText().toString(),"UTF-8"); - * params.add("city", city); } catch (UnsupportedEncodingException e) { - * // TODO Auto-generated catch block e.printStackTrace(); } } - * params.add("page", String.valueOf(pageNo)); params.add("pagesize", - * String.valueOf(pageSize)); params.add("isNearby", - * String.valueOf(this.isShowMyNearbyOnly)); - * - * // QLog.getLogger().d(dTAG, TAG+" user query params: "+params); - * - * return params; - */ - } - - void showMemberDetail(int position) { - try { - this.lvAdapter.setSelectItem(position); - this.lvAdapter.notifyDataSetInvalidated(); - // this.lvWeb.setSelection(position); - HashMap localHashMap = (HashMap) this.lvAdapter - .getItem(position); - userId = Integer.parseInt(localHashMap.get("id")); - - // this.actLastupdated = - // Long.parseLong(localHashMap.get("lastupdated")) ; - // }catch(NumberFormatException ne ){ - // Utils.logStackTrace(ne, TAG); - // showNotes("出错了"); - // return; - // } - // QLog.getLogger().d("com.qiyou", TAG + " get selected userId:" + - // this.userId); - - // try{ - - // requestTrackFromWeb(); - long start = System.currentTimeMillis(); - - // track = getTrackFromWebCache(String.valueOf(svrNumber) + - // this.lastupdated); - // userId = getActFromWebCache( svrNumber, this.actLastupdated); - // QLog.getLogger().d(dTAG, - // " load userId cost "+(System.currentTimeMillis()-start )); - - // if(track!=null){ - // // QLog.getLogger().d(dTAG, - // " mtrack_bean startwp: "+mTrack_bean.getStartWp().toString()); - // // QLog.getLogger().d(dTAG, - // " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); - // // QLog.getLogger().d(dTAG, - // " mtrack_bean endwp: "+mTrack_bean.getLastWp().toString()); - // track.getTrackBean().getTrkseg().clear(); - // // QLog.getLogger().d(dTAG, " track is"+track.toString()); - - // } - - } catch (NumberFormatException ne) { - Utils.logStackTrace(ne, TAG); - showNotes("出错了"); - return; - } - /* - * catch (IOException localIOException){ - * Utils.logStackTrace(localIOException, TAG); } - */ - catch (java.lang.IndexOutOfBoundsException IndexException) { - Utils.logStackTrace(IndexException, TAG); - } catch (Exception er) { - Utils.logStackTrace(er, TAG); - } - - requestUserFromWeb(userId); - - } - - void processUserJsonArray(JSONArray jsonArrary) { - tmpData = new ArrayList>(); - JSONObject jo = null; - User_bean ab; - - if (jsonArrary != null) - for (int i = 0; i < jsonArrary.length(); i++) { - try { - jo = jsonArrary.getJSONObject(i); - if (jo == null) - continue; - QLog.getLogger().d(dTAG, "jsonarray:--> " + jo.toString()); - ab = (User_bean) Utils.getGsonObject(jo.toString(), - User_bean.class); - - } catch (JsonSyntaxException je) { - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - if (ab != null) { - // tr= new Track(tb); - Map t = new HashMap(); - t.put("name", Utils.getShortString(ab.getUserName(), 50) /* - * . - * getAccount - * ( - * ) - */); - - t.put("id", String.valueOf(ab.getId())); - // t.put("distance",String.valueOf(Utils.getFormatedDistance(ab.getDistance()))); - t.put("distance", - String.format("%.1f", ab.getDistance() / 1000)); - t.put("calorie", String.format("%.0f", ab.getCalorie())); - t.put("geo", - String.format("%s %s", ab.getGeo().getCityName(), - ab.getGeo().getDistrictName()).replace( - "null", "")); - - String strUrls = Utils.getUserAlbum(ab); - - /* - * if(isShowPic){ - * - * strUrls=ab.getQqAbulmUrl(); } - */ - t.put("urls", strUrls); - - String d = String.format("%.0f", Utils.getDistanceFromXtoY(ab.getLat(), ab.getLon(), QiYouConstant.PV_LAST_LAT, QiYouConstant.PV_LAST_LON)/1000); - String dist = ab.getLat() > 0 && QiYouConstant.PV_LAST_LAT > 0 ? d /*Utils.getDistanceRange(0,ab.getLat(), ab.getLon())*/ : "--" ; - t.put("distrange",dist ) ; - -// t.put("distrange", -// ab.getLat() > 0 && QiYouConstant.PV_LAST_LAT > 0 ? String -// .format("%.1f", Utils.getDistanceFromXtoY( -// ab.getLat(), ab.getLon(), -// QiYouConstant.PV_LAST_LAT, -// QiYouConstant.PV_LAST_LON) / 1000) -// : "--"); - - tmpData.add(t); - } - - } - - userData = getListData(userData, tmpData); - - showNoRecText(userData.size() == 0); - - showUserData(); - - // QLog.getLogger().e(dTAG, - // String.format("pageNo is%s, actual pageno is %s ",pageNo,userData.size()/pageSize)); - - } - - // QSimpleAdapter lvAdapter; - - int currentUserRow = 0; - - protected void showUserData() { - // this.btn_pagedown.setEnabled(!isMemberLastPage); - // this.btn_pageup.setEnabled(!isMemberFirstPage); - - lvAdapter = new QSimpleAdapter(activity, userData, - R.layout.user_list_detail, new String[] { "urls", "name", "id", - "distance", "distrange", "calorie", "geo", "id" }, - new int[] { R.id.user_abulm, R.id.actList_name, - R.id.actList_svrNo, R.id.actList_dist, - R.id.actList_distrange, R.id.actList_calorie, - R.id.actList_geo, R.id.lst_btnDelUser }); - - // lvWeb.setAdapter(lvAdapter); - // lvAdapter.setSelectItem(selectMemberItem); - // lvWeb.setSelection(selectMemberItem); - - Activity_bean act = getCurrentAct(); - Group_bean group = getCurrentGroup(); - - final boolean canDel = (act != null - && act.getSvrNumber() > 0 - && (this.getUser().getId() == act.getSvrNumber() || this - .isAdmin()) || group != null && group.getId() > 0 - && (this.getUser().getId() == group.getId() || this.isAdmin())); - - // QLog.getLogger().d(dTAG,String.format("------------canDel %s act is null?%s group is null? %s", - // canDel,act==null,group==null)); - - final int visible = canDel ? View.VISIBLE : View.GONE; - - lvAdapter.setViewBinder(new ViewBinder() { - @Override - public boolean setViewValue(View view, Object data, - String textRepresentation) { - - switch (view.getId()) { - - case R.id.user_abulm: { - com.qiyou.mb.android.utils.image.QimageView imgv = (com.qiyou.mb.android.utils.image.QimageView) view; - - if (data == null) - return false; - // QLog.getLogger().d(dTAG, - // " displaying available image of " + data.toString()); - - IL.DisplayImage(data.toString(), imgv); - - return true; - } - case R.id.lst_btnDelUser: { - view.setVisibility(visible); - - if (canDel && data != null) { - final int userId = Integer.parseInt(data.toString()); - Button btn = (Button) view; - btn.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - - /* - * AlertDialog.Builder builder = new - * Builder(activity); - * builder.setMessage("是否踢出该用户?"); - * builder.setTitle("提示"); - * builder.setCancelable(false); - * builder.setPositiveButton("确认", new - * android.content - * .DialogInterface.OnClickListener() { - * - * @Override public void onClick(DialogInterface - * dialog, int which) { dialog.dismiss(); - * removeUser(userId); } }); - * builder.setNegativeButton("取消", new - * android.content - * .DialogInterface.OnClickListener() { - * - * @Override public void onClick(DialogInterface - * dialog, int which) { dialog.dismiss(); - * - * } }); builder.create().show(); - */ - - removeUser(userId); - } - }); - } - - return true; - } - } - - return false; - } - }); - - bindListView(lvAdapter, lvWeb, selectMemberItem, isMemberLastPage); - } - - // ---------------------------------------------------------member query - // end---------------------------------------------- - - // ----------------group query begin---------------- - - RequestParams buildGroupQueryParames() { - RequestParams params = buildBasicParames(pageNo, -1); - - return params; - - } - - void doGroupQuery() { - Utils.hideSoftKeyboard(activity); - // noRec.setVisibility(View.GONE); - isGroupQuery = true; - - if (this.firstLoad && !TextUtils.isEmpty(lastGrpQueryPara)) { - return; - } - RequestParams param = buildGroupQueryParames(); - if (param != null - && !lastGrpQueryPara.equalsIgnoreCase(param.toString())) { - - // QLog.getLogger().d(dTAG, lastGrpQueryPara); - // QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param, RestMethods.GRP_G_LIST/* "mb/group/list" */); - lastGrpQueryPara = param.toString(); - selectGroupItem = -1; - - } - - } - - @Override - void processGrpJsonArray(JSONArray jsonArrary) { - - tmpData = new ArrayList>(); - JSONObject jo = null; - Group_bean ab; - GEOaddress startgeo; - if (jsonArrary != null) - for (int i = 0; i < jsonArrary.length(); i++) { - try { - jo = jsonArrary.getJSONObject(i); - if (jo == null) - continue; - // QLog.getLogger().d(dTAG, "jsonarray:--> " - // +jo.toString()); - ab = (Group_bean) Utils.getGsonObject(jo.toString(), - Group_bean.class); - - } catch (JsonSyntaxException je) { - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - if (ab != null) { - // tr= new Track(tb); - Map t = new HashMap(); - - startgeo = new GEOaddress(ab.getGeo()); - - t.put("name", ab.getName()); - t.put("svrNumber", ab.getId() + ""); - t.put("created", - Utils.getFormatedTimeMonthDay(ab.getCreated())); - t.put("description", - Utils.getShortString(ab.getDesc(), STRLNG)); - t.put("startPlace", - String.format("%s %s", ab.getPlace(), - startgeo.toString(",")).replace("null", "")); - t.put("shangquan", ab.getGeo().getComment()); -// t.put("distrg", String.format("队伍位置:%s", Utils -// .getDistanceRange(/* ab.getDistrange() */0, -// ab.getLat(), ab.getLon()))); - - String dist = ab.getLat() > 0 && QiYouConstant.PV_LAST_LAT > 0 ? String.format("队伍位置:%s", Utils.getDistanceRange(0,ab.getLat(), ab.getLon())) : "--" ; - t.put("distrg",dist ) ; - - t.put("userCnt", String.valueOf(ab.getUserCnt())); - - // t.put("timeLeft", "当前距活动开始剩余时间:" + getTimeLeft(ab)); - t.put("lastupdated", ab.getLastupdated() + ""); - /* - * String staticMapUrl - * =isShowPic?Utils.getBaiduStaticMapUrl(tr):""; // String - * staticMapUrl - * =Utils.getBaiduStaticUrlFromServer(tb.getSvrNumber()); // - * QLog.getLogger().d(dTAG, - * " static map url is: "+staticMapUrl); // - * QLog.getLogger().i(dTAG, - * " static map url is: "+staticMapUrl); t.put("staticmap", - * staticMapUrl ); - */ - t.put("userName", ab.getUserName()); - // t.put("lastupdated", String.valueOf(ab.getLastdbTime()) - // ); - // t.put("cloud", "云:" ); - // QLog.getLogger().d(dTAG, "svrNumber:--> " + ab.getId()); - // // QLog.getLogger().d(dTAG, "lastupdated:--> " + - // String.valueOf(ab.getLastdbTime())); - - t.put("type", String.valueOf(ab.getType())); - - t.put("dist", - String.format("%.1f", ab.getDistance() / 1000)); - // t.put("avs", String.valueOf(ab.getAvSpeed())); - - t.put("rateLevel", String.valueOf(ab.getLevel())); - - t.put("timelong", String.format("%.1f", - ab.getSportTime() / 1000 / 3600.0) /* - * Utils. - * getTimeCnt4Read - * ( - * ab.getSportTime - * (), false) - */); - // String[] urls=tr.getWebPicList(4, true); - t.put("userCnt", String.valueOf(ab.getUserCnt())); - String strUrls = ""; - if (isShowPic) { - /* - * t.put("staticmap", ab.getStaticMapUrl() ); - * - * if(tb.getThumbUrls()!=null) for(String - * url:tb.getThumbUrls()){ // QLog.getLogger().d(dTAG, - * " url is" +url); - * strUrls+=QiYouConstant.BASE_MD_URL+url - * +QiYouConstant.SPLITOR; } - */ - } - t.put("urls", strUrls); - tmpData.add(t); - } - - } - grpData = getListData(grpData, tmpData); - showNoRecText(grpData.size() == 0); - - showGrpData(); - - // QLog.getLogger().e(dTAG, - // String.format("pageNo is%s, actual pageno is %s ", - // pageNo,grpData.size()/pageSize)); - - } - - // QSimpleAdapter lvAdapter; - - int currentGrpRow = 0; - - protected void showGrpData() { - // this.btn_pagedown.setEnabled(!isGrpLastPage); - // this.btn_pageup.setEnabled(!isGrpFirstPage); - - lvAdapter = new QSimpleAdapter(activity, grpData, - R.layout.group_list_detail, new String[] { "name", "svrNumber", - "startTime", "startPlace", "shangquan", "description", - "dist", - - "rateLevel", "timelong", "distrg", "userCnt", - "userName" }, new int[] { R.id.actList_name, - R.id.actList_svrNo, R.id.actList_starttime, - R.id.actList_startplace, R.id.actList_shangquan, - R.id.actList_desc, R.id.actList_dist, - - R.id.actList_level, R.id.actList_sportTime, - R.id.actList_distRange, R.id.actList_memberCnt, - R.id.actList_owner }); - - // lvWeb.setAdapter(lvAdapter); - // lvAdapter.setSelectItem(selectGroupItem); - // lvWeb.setSelection(selectGroupItem); - // QLog.getLogger().d(dTAG, "------ isGrpLastPage .. " + - // isGrpLastPage); - - bindListView(lvAdapter, lvWeb, selectGroupItem, isGrpLastPage); - - } - - /* - * int actSvrNumber; int actType; long actLastupdated; - */ - - void showGroupDetail(int position) { - - int grpSvrNumber = 0; - - if (lvAdapter == null || lvAdapter.getCount() <= position) { - // QLog.getLogger().e(dTAG, - // "wrong group position clicked,reurn...."); - return; - } - try { - this.lvAdapter.setSelectItem(position); - this.lvAdapter.notifyDataSetInvalidated(); - // this.lvWeb.setSelection(position); - HashMap localHashMap = (HashMap) this.lvAdapter - .getItem(position); - grpSvrNumber = Integer.parseInt(localHashMap.get("svrNumber")); - /* - * if(localHashMap.get("type")!=null && - * !localHashMap.get("type").equalsIgnoreCase("null")){ try{ - * this.actType = Integer.parseInt(localHashMap.get("type")) ; - * }catch(NumberFormatException ne ){ Utils.logStackTrace(ne, TAG); - * } } - */ - // this.grpLastupdated = - // Long.parseLong(localHashMap.get("lastupdated")) ; - // }catch(NumberFormatException ne ){ - // Utils.logStackTrace(ne, TAG); - // showNotes("出错了"); - // return; - // } - // QLog.getLogger().d("com.qiyou", TAG + - // " get selected grpSvrNumber:" + grpSvrNumber); - - } catch (NumberFormatException ne) { - Utils.logStackTrace(ne, TAG); - showNotes("出错了"); - return; - } - - catch (java.lang.IndexOutOfBoundsException IndexException) { - Utils.logStackTrace(IndexException, TAG); - } catch (Exception er) { - Utils.logStackTrace(er, TAG); - } - - requestGroupFromWeb(grpSvrNumber); - } - - void requestGroupFromWeb(int svrNo) { - RequestParams params = new RequestParams(); - params.add("id", String.valueOf(svrNo)); - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - getJsonWs(params, RestMethods.GRP_G_FIND_BY_ID/* "mb/activity/" */); - // long l1 = System.currentTimeMillis(); - // // QLog.getLogger().d("com.qiyou", TAG + - // " start Click item to show track detail, time is:" + l1); - // getJsonWs(null, "mb/track/" + this.svrNumber); - // /long l2 = System.currentTimeMillis() - l1; - // // QLog.getLogger().d("com.qiyou", TAG + " get data from web cost:" + - // l2); - } - - // @Override - // void showGroup(Group_bean group) { - // activity.showGroup(group); - // } - - // /------------------------------------------group query - // end------------------------------- - - // begin BBS List -------------------------------BBS - // begin-------------------------------------- - - // boolean isNoteQuery ; - String lastNoteQueryPara; - // int pageNo; - int noteId; - int svrNo; - List> bbsData; - Button btnNew, btnRefresh; - - void doBBSQuery() { - Utils.hideSoftKeyboard(activity); - - // isNoteQuery=true; - // lvWeb.setVisibility(View.VISIBLE); - // lv.setVisibility(View.GONE); - QLog.getLogger().d(dTAG, TAG + "------begin Note query--------- "); - - /* - * if( this.firstLoad&&!TextUtils.isEmpty(lastNoteQueryPara)){ return; } - */ - RequestParams param = buildNotesQueryParames(); - if (param != null) { - - QLog.getLogger().d(dTAG, lastNoteQueryPara); - QLog.getLogger().d(dTAG, param.toString()); - - getJsonWs(param, RestMethods.NOTE_G_LIST /* "mb/user/actusers" */); - - selectedBBSItem = -1; - - } - - } - - RequestParams buildNotesQueryParames() { - RequestParams params = buildBasicParames(pageNo, -1); - params.add("cate1", String.valueOf(this.BBScate)); - params.add("cate2", String.valueOf(this.BBSSubcate)); - - if (BBScate == BBSCate.USER.toInt()) { - params.put("owner", -1); - } - - return params; - - } - - void showNoteDetail(int position) { - try { - this.lvAdapter.setSelectItem(position); - this.lvAdapter.notifyDataSetInvalidated(); - // this.lvWeb.setSelection(position); - HashMap localHashMap = (HashMap) this.lvAdapter - .getItem(position); - noteId = Integer.parseInt(localHashMap.get("id")); - - QLog.getLogger().d("com.qiyou", - TAG + " get selected noteId:" + this.noteId); - - } catch (NumberFormatException ne) { - Utils.logStackTrace(ne, TAG); - showNotes("出错了"); - return; - } catch (java.lang.IndexOutOfBoundsException IndexException) { - Utils.logStackTrace(IndexException, TAG); - } catch (Exception er) { - Utils.logStackTrace(er, TAG); - } - - requestNoteFromWeb(noteId); - - } - - void requestNoteFromWeb(int noteId) { - if (noteId <= 0) - return; - RequestParams params = new RequestParams(); - params.add("id", String.valueOf(noteId)); - getJsonWs(params, RestMethods.NOTE_G_FIND_BY_ID); - } - - @Override - void processNotesJsonArray(JSONArray jsonArrary) { - ArrayList> tmpData = new ArrayList>(); - JSONObject jo = null; - Note ab; - - if (jsonArrary != null) - for (int i = 0; i < jsonArrary.length(); i++) { - try { - jo = jsonArrary.getJSONObject(i); - if (jo == null) - continue; - // QLog.getLogger().d(dTAG, "jsonarray:--> " - // +jo.toString()); - ab = (Note) Utils.getGsonObject(jo.toString(), Note.class); - - } catch (JsonSyntaxException je) { - Utils.logStackTrace(je, TAG); - continue; - } catch (JSONException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - continue; - } - - if (ab != null) { - Map t = new HashMap(); - t.put("title", ab.getTitle()/* .getAccount() */); - t.put("id", String.valueOf(ab.getId())); - t.put("body", ab.getBody()); - t.put("username", ab.getUserName()/* - * ab.getOwner()!=null?ab. - * getOwner - * ().getUserName():"" - */); - t.put("created", Utils.getFormatedTime(ab.getCreated())); - t.put("replycnt", ab.getReplyCnt() + ""); - t.put("lastreply", - ab.getLastupdated() > ab.getCreated() ? ab - .getLastReplyer() : ""); - - BBSCate cate = BBSCate.values()[ab.getCategory()]; - String cateName = ab.getCategory() == this.BBScate - && ab.getSubCate() == this.BBSSubcate ? "" : "[" - + cate.toCHString() + "]"; - String subCateName = TextUtils.isEmpty(cateName) ? "" - : TextUtils.isEmpty(ab.getSubCateName()) ? "" : "[" - + ab.getSubCateName() + "]"; - t.put("cateName", cateName); - t.put("subCatename", subCateName); - if (TextUtils.isEmpty(cateName) - && TextUtils.isEmpty(subCateName)) { - t.put("cates", null); - } - t.put("cateOwnerId", ab.getCateOwnerId() + ""); - t.put("album", Utils.getUserAlbum(ab.getUserAlbum())); - // int priorityType = ab.getMainPriority() > 0 ? 0 : - // ab.getCatePriority()>0 ? 1 : ab.getPriority() > 0?2 : -1; - int priorityImgsrc = ab.getMainPriority() > 0 ? R.drawable.icon_maintop - : ab.getCatePriority() > 0 ? R.drawable.icon_catetop - : ab.getPriority() > 0 ? R.drawable.icon_subcatetop - : -1; - if (priorityImgsrc > 0) { - t.put("priorityImgsrc", priorityImgsrc + ""); - } - - tmpData.add(t); - } - - } - - bbsData = getListData(bbsData, tmpData); - - showNoRecText(bbsData.size() == 0); - - showBBSData(); - - QLog.getLogger().e( - dTAG, - String.format("pageNo is%s, actual pageno is %s ", pageNo, - bbsData.size() / pageSize)); - - } - - // QSimpleAdapter notesSimpleAdapter; - - protected void showBBSData() { - - lvAdapter = new QSimpleAdapter(activity, bbsData, - R.layout.notes_list_detail, new String[] { "title", "body", - "id", "username", "created", "replycnt", "lastreply" - - , "cateName", "subCatename", "priorityImgsrc", "album" - // ,"cates" - }, new int[] { R.id.list_note_name, R.id.list_note_body, - R.id.list_note_id, R.id.list_note_username, - R.id.list_note_created, R.id.list_note_reply_cnt, - R.id.list_note_reply_user - - , R.id.list_note_cate, R.id.list_note_subcate, - R.id.list_note_imgCateTop, R.id.list_note_imgUserAbulm - // ,R.id.list_cate - }); - - lvAdapter.setViewBinder(new ViewBinder() { - @Override - public boolean setViewValue(View view, Object data, - String textRepresentation) { - - switch (view.getId()) { - - case R.id.list_note_imgCateTop: { - com.qiyou.mb.android.utils.image.QimageView imgv = (com.qiyou.mb.android.utils.image.QimageView) view; - - if (data == null) { - // imgv.setVisibility(View.GONE); - return false; - } - imgv.setVisibility(View.VISIBLE); - // QLog.getLogger().d(dTAG, - // " displaying available image of " + data.toString()); - imgv.setImageResource(Integer.valueOf(data.toString())); - // IL.DisplayImage( data.toString(),imgv); - - return true; - } - case R.id.list_note_imgUserAbulm: { - com.qiyou.mb.android.utils.image.QroundimageView imgv = (com.qiyou.mb.android.utils.image.QroundimageView) view; - - if (data == null) { - - return false; - } - QLog.getLogger() - .d(dTAG, - " displaying available image of " - + data.toString()); - IL.DisplayImage(data.toString(), imgv); - - return true; - } - case R.id.list_note_subcate: { - - view.setVisibility(View.VISIBLE); - if (data != null && TextUtils.isEmpty(data.toString())) { - - view.setVisibility(View.GONE); - return true; - } - - return false; - } - case R.id.list_note_cate: { - - view.setVisibility(View.VISIBLE); - if (data != null && TextUtils.isEmpty(data.toString())) { - - view.setVisibility(View.GONE); - return true; - } - - return false; - } - // case R.id.list_cate:{ - // - // - // if(data==null ){ - // - // view.setVisibility(View.GONE); - // - // } - // - // - // return true; - // } - - } - - return false; - } - }); - - bindListView(lvAdapter, lvWeb, selectedBBSItem, isBBSLastPage); - - lvWeb.setDividerHeight(2); - - } - - // void initialNotesQuery(){ - // pageNo=1; - // doBBSQuery(); - // } - - // /////------------ BBS end - - private WebQueryCate getSelectedCate() { - WebQueryCate wq = WebQueryCate.LATEST; - if (spWebInputType == null) { - return wq; - } - int selected = spWebInputType.getSelectedItemPosition(); - String selectedItem = spAdapterWeb.getItem(selected).toString(); - int cateIndex = totalList.indexOf(selectedItem); - if (cateIndex == -1) { - if (BBSCity.equalsIgnoreCase(selectedItem)) { - wq = WebQueryCate.CITY; - } - } else { - // wq = WebQueryCate.valueOf(cateIndex); - wq = WebQueryCate.values()[cateIndex]; - } - - return wq; - } - - RequestParams buildBasicParames(int pageNo, int type) { - RequestParams params = new RequestParams(); - - final int GEO_CITY_TYPE = 2; - String userName = null; - String svrNo = null; - String cityName = null; - String keyName = null; - /* - * if(edUserName!=null){ userName=edUserName.getText().toString(); - * svrNo= edSvrNo.getText().toString(); - * cityName=webCity.getText().toString(); } - */ - isShowMyNearbyOnly = false; - isShowMytrackOnly = false; - - if (spWebInputType != null) { - - this.BBSSubcate = 0; - this.BBSsubCateName = ""; - this.BBScate = BBSCate.NORMAL.toInt(); - - // int selected = spWebInputType.getSelectedItemPosition(); - // String selectedItem = spAdapterWeb.getItem(selected).toString(); - WebQueryCate wq = getSelectedCate(); - /* - * WebQueryCate.LATEST; - * - * int cateIndex = totalList.indexOf(selectedItem); - * - * if (cateIndex == -1){ if(BBSCity.equalsIgnoreCase(selectedItem)){ - * wq = WebQueryCate.CITY; } }else { // wq = - * WebQueryCate.valueOf(cateIndex); wq = - * WebQueryCate.values()[cateIndex]; } - */ - - switch (wq) { - case LATEST: - - break; - case MYNEARBY: - isShowMyNearbyOnly = true; - break; - case GEO: - cityName = txt_webinput.getText().toString(); - if (TextUtils.isEmpty(cityName)) { - cityName = QiYouConstant.PV_LAST_CITY; - } - break; - case KEYWORD: - keyName = txt_webinput.getText().toString(); - if (TextUtils.isEmpty(keyName)) { - - return params; - } - break; - case MINE: - isShowMytrackOnly = true; - break; - case USER: - userName = txt_webinput.getText().toString(); - break; - case SVRNO: - svrNo = txt_webinput.getText().toString(); - break; - case BIKE: - type = TrackType.BIKE.toInt(); - break; - case GPX: - type = TrackType.GPX.toInt(); - break; - case HIKE: - type = TrackType.HIKE.toInt(); - break; - case MOTOR: - type = TrackType.MOTOR.toInt(); - break; - case SCORE: - break; - - // below is for bbs - case QXTD: - this.BBScate = BBSCate.QXTD.toInt(); - break; - case PYJL: - this.BBScate = BBSCate.PYJL.toInt(); - break; - case TBDS: - this.BBScate = BBSCate.TBDS.toInt(); - break; - case ACTIVITY: - this.BBScate = BBSCate.ACT.toInt(); - break; - case GROUP: - this.BBScate = BBSCate.GROUP.toInt(); - break; - case LEARNING: - this.BBScate = BBSCate.LEARNING.toInt(); - break; - case QANDA: - this.BBScate = BBSCate.QANDA.toInt(); - break; - case BIKECARE: - this.BBScate = BBSCate.BIKECARE.toInt(); - break; - case CITY: - this.BBScate = BBSCate.GEO.toInt(); - this.BBSSubcate = activity.app.user.getUserbean().getGeo() - .getCity(); - this.BBSsubCateName = activity.app.user.getUserbean().getGeo() - .getCityName(); - - break; - } - } - - if (!TextUtils.isEmpty(svrNo)) { - params.add("svrNo", svrNo); - return params; - } - - params.add("page", String.valueOf(pageNo)); - params.add("pagesize", String.valueOf(pageSize)); - - params.add("type", String.valueOf(type)); - - if (isShowMytrackOnly) { - // params.add("isMyOnly", String.valueOf(isShowMytrackOnly)); - params.add("ownerId", - String.valueOf(activity.app.user.getUserbean().getId())); - } else if (isShowMyNearbyOnly) { - params.add("isNearby", String.valueOf(this.isShowMyNearbyOnly)); - params.add("lat", String.valueOf(QiYouConstant.PV_LAST_LAT)); - params.add("lon", String.valueOf(QiYouConstant.PV_LAST_LON)); - params.add("dist", String.valueOf(50)); - } - - if (!TextUtils.isEmpty(keyName)) { - try { - params.add("keyName", URLEncoder.encode(keyName, "UTF-8")); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - - } - - if (!TextUtils.isEmpty(cityName)) { - try { - params.add("geoName", URLEncoder.encode(cityName, "UTF-8")); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - params.add("geoType", String.valueOf(GEO_CITY_TYPE)); - } - if (!TextUtils.isEmpty(userName)) { - - try { - params.add("userName", URLEncoder.encode(userName, "UTF-8")); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, dTAG); - } - } - - // QLog.getLogger().d(dTAG, TAG+" web query params: "+params); - - return params; - } - - @Override - protected void onMyTabChanged(String tabId) { - super.onMyTabChanged(tabId); - /* - * if(tabhost==null)return; initialTabhostStyle(tabhost); - * setSelectedTabhostStyle(tabhost); currentTab= - * tabhost.getCurrentTab(); - */ - lastSelectedCateId = -1; - isSwitchWebInputOnly = true; - getQueryCate(); - processTabQuery(); - - // isLastPage=false; - } - - void processTabQuery() { - setNote(); - isLoadingMore = false; - pageNo = 1; - if (progressDialog != null) - progressDialog.dismiss(); - // noRec.setVisibility(View.GONE); - QLog.getLogger().d( - dTAG, - " tab changed....to... " + currentTab + ", isLoadingMore? " - + isLoadingMore); - switchTabOptions(currentTab); - // lvWeb.setVisibility(View.GONE); - // this.lvWeb.setVisibility(View.GONE); - // lvWeb.setVisibility(View.GONE); - // lvWeb.setVisibility(View.GONE); - // lvWeb.setVisibility(View.GONE); - if (!validInput()) { - return; - } - if (imgWebPlus != null) { - imgWebPlus.setVisibility(View.GONE); - } - canclick = true; - /* - * if(currentTab==0){ this.lv.setVisibility(View.VISIBLE); doQuery(); - * }else if(isByCatesQuery){ this.lv.setVisibility(View.VISIBLE); - * doCatesQuery(); // }else if(isInactiveQuery){ // doInactiveQuery(); - * }else if(isRouteQuery){ this.lv.setVisibility(View.VISIBLE); - * doRouteQuery(); }else - */ - showNoRecText(false); - - if (firstLoad) { - WebQueryCate wq = getSelectedCate(); - if (wq == WebQueryCate.SVRNO) { - return; - } - } - - if (isWebTrackQuery) { - // ll_webinput.setVisibility(View.VISIBLE); - // lvWeb.setVisibility(View.VISIBLE); - // QLog.getLogger().d(dTAG, "trackData is Null? " + - // (trackData==null)); - - if (activity.isNeedFresh) { - activity.isNeedFresh = false; - doWebTrackQuery(); - this.isSwitchWebInputOnly = false; - return; - } - - if (trackData == null) { - - doWebTrackQuery(); - } else - showWebTrackListData(trackData); - - if (trackData != null) - showNoRecText(trackData.size() == 0); - - } else if (isActivityQuery) { - if (imgWebPlus != null) { - imgWebPlus.setVisibility(View.VISIBLE); - } - // ll_webinput.setVisibility(View.VISIBLE); - // lvWeb.setVisibility(View.VISIBLE); - // QLog.getLogger().d(dTAG, "actData is Null? " + (actData==null)); - if (actData == null) - // doActQuery(); - doActQuery(); - else - showActData(); - - if (actData != null) - showNoRecText(actData.size() == 0); - - } else if (isGroupQuery) { - if (imgWebPlus != null) { - imgWebPlus.setVisibility(View.VISIBLE); - } - // lvWeb.setVisibility(View.VISIBLE); - // QLog.getLogger().d(dTAG, "grpData is Null? " + (grpData==null)); - if (grpData == null) - doGroupQuery(); - else - showGrpData(); - - if (grpData != null) - showNoRecText(grpData.size() == 0); - - } else if (isMemberQuery) { - // lvWeb.setVisibility(View.VISIBLE); - if (userData == null) - doUserQuery(); - else - showUserData(); - if (userData != null) - showNoRecText(userData.size() == 0); - - } else if (isBBSQuery) { - // lvWeb.setVisibility(View.VISIBLE); - // lvWeb.setVisibility(View.VISIBLE); - if (imgWebPlus != null) { - imgWebPlus.setVisibility(View.VISIBLE); - } - if (activity.isNeedFresh) { - activity.isNeedFresh = false; - doBBSQuery(); - this.isSwitchWebInputOnly = false; - return; - } - - if (bbsData == null) - doBBSQuery(); - else - showBBSData(); - - } - - // lvWeb.setVisibility(View.VISIBLE); - } - - void switchTabOptions(int queryType) { - - if (lvWeb == null) { - return; - } - lvWeb.setVisibility(View.GONE); - - isBBSQuery = queryType == 0; - isWebTrackQuery = queryType == 1; - isActivityQuery = queryType == 2; - isGroupQuery = queryType == 3; - isMemberQuery = queryType == 4; - - if (spWebInputType == null) - return; - - // setSpSelection(); - - // tmp.get(Integer.valueOf( spWebInputType.getSelectedItemPosition())) - // this.txt_webinput.setText( tmp.get(Integer.valueOf( - // spWebInputType.getSelectedItemPosition())) ); - this.chk_web_pic.setVisibility(isWebTrackQuery ? View.VISIBLE - : View.GONE); - } - - Activity_bean getCurrentAct() { - return null; - } - - Group_bean getCurrentGroup() { - return null; - } - - void setSpSelection() { - // super.firstLoad = true; //tab changes,spWebInput items changes, wont' - // fire the doQuery() again - Object a = activity.app.tabSpIndex.get(String.valueOf(currentTab)); // java.lang.Double - // cannot - // be - // cast - // to - // java.lang.Integer - Double id = Double.valueOf(a.toString()); - int cacheId = id.intValue();// (int) - // activity.app.tabSpIndex.get(String.valueOf(currentTab)) - // ; - lastSelectedCateId = cacheId; - if (cacheId != spWebInputType.getSelectedItemPosition()) { - // isSwitchWebInputOnly = true; // whe back from oth222er fragment, - // no query - spWebInputType.setSelection(cacheId); - - } - - if (tabSpIndexValue == null) { - tabSpIndexValue = new HashMap>(); - - } - - this.txt_webinput.setVisibility(View.GONE); - this.btn_webquery.setVisibility(View.GONE); - Map tmp = tabSpIndexValue.get(Integer - .valueOf(currentTab)); - if (tmp != null) { - - String cachedTxt = tmp.get(Integer.valueOf(spWebInputType - .getSelectedItemPosition())); - this.txt_webinput.setText(cachedTxt); - this.txt_webinput.setVisibility( cachedTxt == null ? View.GONE : View.VISIBLE); - this.btn_webquery.setVisibility(txt_webinput.getVisibility()); - - } - setNote(); - // isSwitchWebInputOnly = true; - // webSpinnerSelected(this.activity.app.tabSpIndex.get(Integer.valueOf(currentTab))); - } - - /** - * reomve user from the group or activity ... etc member list the method - * need to be overrided in group or activity ...fragment. - * - * @param userId - * ,user to remove - */ - void removeUser(int userId) { - - } - - @Override - public boolean isShowBottomTabs() { - // TODO Auto-generated method stub - return true; - } - - @Override - public void setTabOnFiling() { - - maxTabIndex = 4; - - } - - @Override - protected void setSelectedTab() { - if (tabhost != null) { // && tabhost.getCurrentTab()!=currentTab){ - if (tabhost.getCurrentTab() != currentTab) { // back from navigation - tabhost.setCurrentTab(currentTab); - } else if (currentTab == 0) {// on first load - this.processTabQuery(); - } - } - } - - @Override - public void onResume() { - // activity.app.currentActiveFragment =TAG; - super.onResume(); - // activity.updateActionBarTitle( R.string.frg_trackWeb ); - // // - // QLog.getLogger().e(dTAG,TAG+" app.currentActiveFragment of trackList: "+TAG); - // if(tabhost!= null && tabhost.getCurrentTab() != currentTab){ - // processTabQuery(); - // } - - } - - @Override - public void onPause() { - super.onPause(); - if (progressDialog != null) - progressDialog.dismiss(); - } - - @Override - void setNote() { - - if(txtNote== null){ - return; - } - - txtNote.setVisibility(View.VISIBLE); - String noteTxt = ""; - - WebQueryCate wq = getSelectedCate(); - TextView tv = (TextView) tabhost.getTabWidget().getChildAt(currentTab).findViewById(android.R.id.title); - String tabTxt = tv.getText().toString(); - if (currentTab == 0 ){ - if (wq == WebQueryCate.LATEST){ - noteTxt = BBSCate.NORMAL.toCHString() + ",最新" + tabTxt;//+BBSCate.NORMAL.toCHString(); - }else if(wq==WebQueryCate.MINE) { - noteTxt = "我发表的" + tabTxt;//+ tabhost.getCurrentTabTag(); - }else { - noteTxt = wq.toCHString(); - } - }else if (currentTab == 4 && wq == WebQueryCate.LATEST){ - noteTxt = "驴友排行榜"; // + tabTxt; - } - else { - noteTxt = wq.toCHString() + tabTxt;// + tabhost.getCurrentTabTag(); - } -// else if(isWebTrackQuery){ -// noteTxt = super.BBSsubCateName + " 相关路书"; -// }else if(isMemberQuery){ -// noteTxt = super.BBSsubCateName + "成员"; -// }else if(isShareQuery){ -// noteTxt = super.BBSsubCateName + "的运动分享"; -// }else if(isLiveQuery){ -// noteTxt = super.BBSsubCateName + "位置直播"; -// }else if(isActivityQuery){ -// noteTxt = super.BBSsubCateName + "的相关活动"; -// }else if(super.isGroupQuery){ -// noteTxt = super.BBSsubCateName + "的相关队伍"; -// } - - - txtNote.setText(noteTxt); - - - } - @Override - void hideNotes(){ - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/upgrade/ParseXmlService.java b/qy/src/main/java/com/qiyou/mb/android/upgrade/ParseXmlService.java deleted file mode 100644 index 68983eb..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/upgrade/ParseXmlService.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.qiyou.mb.android.upgrade; - -import java.io.InputStream; -import java.util.HashMap; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - - */ -public class ParseXmlService -{ - public HashMap parseXml(InputStream inStream) throws Exception - { - HashMap hashMap = new HashMap(); - - // 实例化一个文档构建器工厂 - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - // 通过文档构建器工厂获取一个文档构建器 - DocumentBuilder builder = factory.newDocumentBuilder(); - // 通过文档通过文档构建器构建一个文档实例 - Document document = builder.parse(inStream); - //获取XML文件根节点 - Element root = document.getDocumentElement(); - //获得所有子节点 - NodeList childNodes = root.getChildNodes(); - for (int j = 0; j < childNodes.getLength(); j++) - { - //遍历子节点 - Node childNode = childNodes.item(j); - if (childNode.getNodeType() == Node.ELEMENT_NODE){ - Element childElement = (Element) childNode; - hashMap.put(childElement.getNodeName(),childElement.getFirstChild().getNodeValue()); - } - /*if (childNode.getNodeType() == Node.ELEMENT_NODE) - { - Element childElement = (Element) childNode; - //版本号 - if ("version".equals(childElement.getNodeName())) - { - hashMap.put("version",childElement.getFirstChild().getNodeValue()); - } - //软件名称 - else if (("name".equals(childElement.getNodeName()))) - { - hashMap.put("name",childElement.getFirstChild().getNodeValue()); - } - //下载地址 - else if (("url".equals(childElement.getNodeName()))) - { - hashMap.put("url",childElement.getFirstChild().getNodeValue()); - } - else if (("details".equals(childElement.getNodeName()))) - { - hashMap.put("details",childElement.getFirstChild().getNodeValue()); - } - }*/ - } - return hashMap; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/upgrade/UpdateManager.java b/qy/src/main/java/com/qiyou/mb/android/upgrade/UpdateManager.java deleted file mode 100644 index b84fdf7..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/upgrade/UpdateManager.java +++ /dev/null @@ -1,440 +0,0 @@ -package com.qiyou.mb.android.upgrade; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; - -import org.apache.http.Header; - -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.content.Intent; -import android.content.pm.PackageManager.NameNotFoundException; -import android.net.Uri; -import android.os.Environment; -import android.os.Handler; -import android.os.Message; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.ProgressBar; -import android.widget.Toast; - -import com.loopj.android.http.AsyncHttpResponseHandler; -import com.qiyou.mb.android.QiYouApplication; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.Utils; -import com.qiyou.mb.android.utils.log.QLog; - - - -public class UpdateManager { - - public static final String TAG ="com.qiyou.UpdateManager"; - public static final String dTAG ="com.qiyou"; - private static final int DOWNLOAD = 1; - private static final int DOWNLOAD_FINISH = 2; - HashMap mHashMap; - private String mSavePath; - private int progress; - private boolean cancelUpdate = false; - private Context mContext; - private ProgressBar mProgress; - private Dialog mDownloadDialog; - private Handler mHandler = new Handler() - { - @Override - public void handleMessage(Message msg) - { - switch (msg.what) - { - case DOWNLOAD: - mProgress.setProgress(progress); - break; - case DOWNLOAD_FINISH: - installApk(); - break; - default: - break; - } - }; - }; - - public UpdateManager(Context context) - { - this.mContext = context; -// app =(QiYouApplication)context; - } - - /** - * 濡拷绁存潪顖欐閺囧瓨鏌� - */ - public void checkUpdate() - { - String urlStr =QiYouConstant.VERSION_ADDRESS; - checkUpdate(urlStr); - /*if (isUpdate()) - { - showNoticeDialog(); - } else - { - Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show(); - }*/ - } - boolean isSilence =false; - public void checkUpdateSilence() - { - isSilence=true; - checkUpdate(); - } - - - - - - - - void checkUpdate(String url){ - - - QiYouApplication.requestWeb(url, null, new AsyncHttpResponseHandler(){ - -// String msg = ""; - - public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable) - { - QLog.getLogger().dLog(dTAG, TAG + ",版本检查错误 onFailure(int, Header[],byte[], Throwable ) was received"); - if(!isSilence) - Toast.makeText(mContext, "版本检查出错了", Toast.LENGTH_LONG).show(); - } - - public void onSuccess(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte) - { - - QLog.getLogger().d(dTAG, TAG + ", response is " + new String(paramAnonymousArrayOfByte)); - if (paramAnonymousArrayOfByte != null) { - processTxtOnSuccess(paramAnonymousArrayOfByte); - } - } - }); - - - - } - - void processTxtOnSuccess(byte[] paramArrayOfByte) { - - boolean isUpdate=false; - int versionCode = getVersionCode(mContext); - InputStream inputStream = null; - inputStream =new ByteArrayInputStream(paramArrayOfByte); - ParseXmlService service = new ParseXmlService(); - try - { - - if(inputStream!=null) - mHashMap = service.parseXml(inputStream); - - } catch (Exception e) - { - e.printStackTrace(); - } - if (null != mHashMap) - { - int serviceCode = Integer.valueOf(mHashMap.get("version")); - // need update or not - isUpdate =serviceCode > versionCode; - } - - if (isUpdate) - { - showNoticeDialog(); - } else - { - if(!isSilence) - Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show(); - } - - - } - - - - - /** - * 濡拷鐓℃潪顖欐閺勵垰鎯侀張澶嬫纯閺傛壆澧楅張锟� * - * @return - */ - /*private boolean isUpdate() - { - // 閼惧嘲褰囪ぐ鎾冲鏉烆垯娆㈤悧鍫熸拱 - int versionCode = getVersionCode(mContext); - String urlStr =QiYouConstant.VERSION_ADDRESS; - // 閹跺ersion.xml閺�儳鍩岀純鎴犵捕娑撳绱濋悞璺烘倵閼惧嘲褰囬弬鍥︽娣団剝浼� -// InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml"); - // 鐟欙絾鐎絏ML閺傚洣娆㈤妴锟介悽鍙樼艾XML閺傚洣娆㈠В鏃囩窛鐏忓骏绱濋崶鐘愁劃娴h法鏁OM閺傜懓绱℃潻娑滎攽鐟欙絾鐎� - ParseXmlService service = new ParseXmlService(); - try - { - InputStream inStream = getInputStreamFromUrl(urlStr);//ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml"); - if(inStream!=null) - mHashMap = service.parseXml(inStream); - - } catch (Exception e) - { - e.printStackTrace(); - } - if (null != mHashMap) - { - int serviceCode = Integer.valueOf(mHashMap.get("version")); - // 閻楀牊婀伴崚銈嗘焽 - if (serviceCode > versionCode) - { - return true; - } - } - return false; - } - public InputStream getInputStreamFromUrl(String urlStr) - throws MalformedURLException, IOException { - - URL url; - URI uri = null ; - try { - url = new URL(urlStr); - uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if(uri==null)return null; - - HttpGet httpRequest ;//= new HttpGet( urlStr); - httpRequest = new HttpGet( uri); - HttpResponse response=app.getHttpClient().execute(httpRequest); - InputStream inputStream = null; - QLog.getLogger().d(dTAG, TAG+" urlStr:" + urlStr); - - QLog.getLogger().d(dTAG, TAG+"response.getStatusLine().getStatusCode():" +response.getStatusLine().getStatusCode()); - - if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ - - - inputStream =response.getEntity().getContent(); - - } - return inputStream; - - } - - */ - - /** - * 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣锟� * - * @param context - * @return - */ - public int getVersionCode(Context context) - { - int versionCode = 0; - try - { - // 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣鍑ょ礉鐎电懓绨睞ndroidManifest.xml娑撳獘ndroid:versionCode - versionCode = context.getPackageManager().getPackageInfo("com.qiyou.mb.android", 0).versionCode; - } catch (NameNotFoundException e) - { - Utils.logStackTrace(e, TAG); - } - return versionCode; - } - - /** - * 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣锟� * - * @param context - * @return - */ - public static String getVersionName(Context context) - { - String versionName = ""; - try - { - // 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣鍑ょ礉鐎电懓绨睞ndroidManifest.xml娑撳獘ndroid:versionCode - versionName = context.getPackageManager().getPackageInfo("com.qiyou.mb.android", 0).versionName; - } catch (NameNotFoundException e) - { - Utils.logStackTrace(e, TAG); - } - return versionName; - } - - /** - * 閺勫墽銇氭潪顖欐閺囧瓨鏌婄�纭呯樈濡楋拷 - */ - private void showNoticeDialog() - { - // 閺嬪嫰锟界�纭呯樈濡楋拷 - AlertDialog.Builder builder = new Builder(mContext); - builder.setTitle(R.string.soft_update_title); - String upgradeDetails=mHashMap.get("details"); - - builder.setMessage( mContext.getString(R.string.soft_update_info) +upgradeDetails ); - builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - dialog.dismiss(); - showDownloadDialog(); - } - }); - // 缁嬪秴鎮楅弴瀛樻煀 - builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - dialog.dismiss(); - } - }); - Dialog noticeDialog = builder.create(); - noticeDialog.show(); - } - - /** - * 閺勫墽銇氭潪顖欐娑撳娴囩�纭呯樈濡楋拷 - */ - private void showDownloadDialog() - { - // 閺嬪嫰锟芥潪顖欐娑撳娴囩�纭呯樈濡楋拷 - AlertDialog.Builder builder = new Builder(mContext); - builder.setTitle(R.string.soft_updating); - // 缂佹瑤绗呮潪钘夘嚠鐠囨繃顢嬫晶鐐插鏉╂稑瀹抽弶锟� - final LayoutInflater inflater = LayoutInflater.from(mContext); - View v = inflater.inflate(R.layout.softupgrade_progress, null); - mProgress = (ProgressBar) v.findViewById(R.id.update_progress); - builder.setView(v); - // 閸欐牗绉烽弴瀛樻煀 - builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - dialog.dismiss(); - // 鐠佸墽鐤嗛崣鏍ㄧХ閻樿埖锟� - cancelUpdate = true; - } - }); - mDownloadDialog = builder.create(); - mDownloadDialog.setCancelable(false); - mDownloadDialog.show(); - // 閻滄澘婀弬鍥︽ - downloadApk(); - } - - /** - * 娑撳娴嘺pk閺傚洣娆� - */ - private void downloadApk() - { - // 閸氼垰濮╅弬鎵殠缁嬪绗呮潪鍊熻拫娴狅拷 - new downloadApkThread().start(); - } - - /** - * 娑撳娴囬弬鍥︽缁捐法鈻� - */ - private class downloadApkThread extends Thread - { - @Override - public void run() - { - try - { - // 閸掋倖鏌嘢D閸椻剝妲搁崥锕�摠閸︻煉绱濋獮鏈电瑬閺勵垰鎯侀崗閿嬫箒鐠囪鍟撻弶鍐 - if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) - { - // 閼惧嘲绶辩�妯哄亶閸楋紕娈戠捄顖氱窞 - String sdpath = Environment.getExternalStorageDirectory() + "/"; - mSavePath = sdpath + "download"; - URL url = new URL(mHashMap.get("url")); - // 閸掓稑缂撴潻鐐村复 - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.connect(); - // 閼惧嘲褰囬弬鍥︽婢堆冪毈 - int length = conn.getContentLength(); - // 閸掓稑缂撴潏鎾冲弳濞达拷 - InputStream is = conn.getInputStream(); - - File file = new File(mSavePath); - // 閸掋倖鏌囬弬鍥︽閻╊喖缍嶉弰顖氭儊鐎涙ê婀� - if (!file.exists()) - { - file.mkdir(); - } - File apkFile = new File(mSavePath, mHashMap.get("name")); - FileOutputStream fos = new FileOutputStream(apkFile); - int count = 0; - // 缂傛挸鐡� - byte buf[] = new byte[1024]; - // 閸愭瑥鍙嗛崚鐗堟瀮娴犳湹鑵� - do - { - int numread = is.read(buf); - count += numread; - // 鐠侊紕鐣绘潻娑樺閺夆�缍呯純锟� - progress = (int) (((float) count / length) * 100); - // 閺囧瓨鏌婃潻娑樺 - mHandler.sendEmptyMessage(DOWNLOAD); - if (numread <= 0) - { - // 娑撳娴囩�灞惧灇 - mHandler.sendEmptyMessage(DOWNLOAD_FINISH); - break; - } - // 閸愭瑥鍙嗛弬鍥︽ - fos.write(buf, 0, numread); - } while (!cancelUpdate);// 閻愮懓鍤崣鏍ㄧХ鐏忓崬浠犲顤嶇瑓鏉烇拷 - fos.close(); - is.close(); - } - } catch (MalformedURLException e) - { - Utils.logStackTrace(e, TAG); - } catch (IOException e) - { - Utils.logStackTrace(e, TAG); - } - // 閸欐牗绉锋稉瀣祰鐎电鐦藉鍡樻▔缁�拷 - mDownloadDialog.dismiss(); - } - }; - - /** - * 鐎瑰顥朅PK閺傚洣娆� - */ - private void installApk() - { - File apkfile = new File(mSavePath, mHashMap.get("name")); - if (!apkfile.exists()) - { - return; - } - // 闁俺绻僆ntent鐎瑰顥朅PK閺傚洣娆� - Intent i = new Intent(Intent.ACTION_VIEW); - i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); - mContext.startActivity(i); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/BMapUtil.java b/qy/src/main/java/com/qiyou/mb/android/utils/BMapUtil.java deleted file mode 100644 index 83fcdca..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/BMapUtil.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.qiyou.mb.android.utils; - -import android.graphics.Bitmap; -import android.view.View; - -public class BMapUtil { - - /** - * 浠巚iew 寰楀埌鍥剧墖 - * @param view - * @return - */ - public static Bitmap getBitmapFromView(View view) { - view.destroyDrawingCache(); - view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), - View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); - view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); - view.setDrawingCacheEnabled(true); - Bitmap bitmap = view.getDrawingCache(true); - return bitmap; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/CompositDrawableView.java b/qy/src/main/java/com/qiyou/mb/android/utils/CompositDrawableView.java deleted file mode 100644 index 651dc9c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/CompositDrawableView.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.qiyou.mb.android.utils; - -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.image.QimageView; - -import android.R.color; -import android.annotation.TargetApi; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.view.Gravity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.LinearLayout.LayoutParams; -import android.widget.RelativeLayout; -import android.widget.ScrollView; -import android.widget.TextView; - -public class CompositDrawableView extends ScrollView{ - private final String TAG = "TextDrawableView"; - TextView tv = null; - ImageView iv = null; - RelativeLayout ll=null; - public CompositDrawableView(Context context, String text,int width,int height) { - super(context); - - getTv(context,text,12); - tv.setPadding(-5, -5, -5, 2); - tv.setBackgroundColor(Color.RED); - tv.setTextColor(Color.WHITE); - tv.setGravity(Gravity.CENTER); - this.addView(tv, new LayoutParams(width,height)); - } - - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public CompositDrawableView(Context context, String text,int textSize,boolean hasMsg,float bear,int width,int height) { - super(context); - - /* LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - View layout = inflater.inflate(R.layout.live_share_point, - (ViewGroup) this); - ImageView image = (ImageView) layout.findViewById(R.id.img_direction); - image.setBackgroundResource(R.drawable.icon_play); - image.setRotation(bear); - image.setAlpha(150); - TextView tv = (TextView) layout.findViewById(R.id.txt_name); - tv.setBackgroundResource( R.drawable.icon_textbox); - tv.setTextColor(Color.RED); - tv.setPadding(2, -5, -5, 6); - tv.setGravity(Gravity.CENTER); - */ - this.setBackgroundColor(Color.RED); - getLL(context); - -// text="名称233445"; - - - iv = new ImageView(context); - - iv.setBackgroundResource(R.drawable.icon_arrowb); - iv.setRotation(bear-90); -// image.setVisibility(View.GONE); - iv.setAlpha(150); -// iv.setLeft(50); - - - getTv(context,text,textSize); -// tv.setBackgroundResource(getResources().getDrawable(R.drawable.icon_waypoint)); -// tv.setBackgroundResource( R.drawable.icon_textbox); -// tv.setBackgroundResource( R.drawable.icon_pass); -// tv.setPadding(0, 50,0, 0); -// tv.setBackgroundColor(Color.RED); - tv.setTextColor(Color.RED); - tv.setPadding(12, 2, 2, 2); - tv.setBottom(2); -// tv.setPadding(2, -5, -5, 6); - tv.setGravity(Gravity.CENTER); -// tv.setId(10); -// tv.setBackgroundColor(Color.GREEN); -// tv.setCompoundDrawables( getResources().getDrawable(R.drawable.icon_pass),null, null ,null); - -// tv.setRotation(bear); -// Drawable d =getResources().getDrawable(R.drawable.icon_waypoint); -// tv.setTextColor(Color.GREEN); -// tv.setCompoundDrawables( getResources().getDrawable(R.drawable.icon_pass),null, null ,null); -// android.view.ViewGroup.LayoutParams -// ll.addView(tv,0, new android.view.ViewGroup.LayoutParams(width,height)); -// this.addView(tv, new LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); - ll.addView(tv, new android.view.ViewGroup.LayoutParams(width,height)); - -// ll.addView(tv, new android.view.ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); - ll.addView(iv, new android.view.ViewGroup.LayoutParams( android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); - - /* if(bear<=180){ - ll.addView(tv, new android.view.ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); - ll.addView(iv, new android.view.ViewGroup.LayoutParams( android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); - }else { - ll.addView(iv, new android.view.ViewGroup.LayoutParams( android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); - ll.addView(tv, new android.view.ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); - }*/ - -/* TextView msg = new TextView(context); - msg.setText("something to say"); - msg.setBackgroundResource(R.drawable.icon_waypoint); - this.addView(msg, new LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));*/ -// ll.addView(iv,1, new android.view.ViewGroup.LayoutParams( android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); -// ll.addView(iv,1, new android.view.ViewGroup.LayoutParams( android.view.ViewGroup.LayoutParams.MATCH_PARENT,android.view.ViewGroup.LayoutParams.MATCH_PARENT)); - - this.addView(ll); - } - void getLL(Context context){ - /*ll = new LinearLayout( context); - LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams( - LayoutParams.MATCH_PARENT, - LayoutParams.MATCH_PARENT); - ll.setLayoutParams(linearParams); - ll.setOrientation(LinearLayout.HORIZONTAL); - ll.setBackgroundColor(Color.LTGRAY);*/ - - ll = new RelativeLayout( context); - RelativeLayout.LayoutParams linearParams = new RelativeLayout.LayoutParams( - LayoutParams.MATCH_PARENT, - LayoutParams.MATCH_PARENT); - ll.setLayoutParams(linearParams); - ll.setBackgroundColor(Color.LTGRAY); - } - - void getTv(Context context, String text,int textSize){ - tv = new TextView(context); - tv.setText(text); - tv.setTextSize(textSize); - - - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/DummyTabContent.java b/qy/src/main/java/com/qiyou/mb/android/utils/DummyTabContent.java deleted file mode 100644 index af05206..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/DummyTabContent.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.qiyou.mb.android.utils; - -import android.content.Context; -import android.view.View; -import android.widget.TabHost.TabContentFactory; - -public class DummyTabContent implements TabContentFactory{ - private Context mContext; - - public DummyTabContent(Context context){ - mContext = context; - } - - - @Override - public View createTabContent(String tag) { - View v = new View(mContext); - return v; - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/EasySSLSocketFactory.java b/qy/src/main/java/com/qiyou/mb/android/utils/EasySSLSocketFactory.java deleted file mode 100644 index 1a1a507..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/EasySSLSocketFactory.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; - -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.conn.scheme.LayeredSocketFactory; -import org.apache.http.conn.scheme.SocketFactory; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; - -public class EasySSLSocketFactory implements SocketFactory, -LayeredSocketFactory { - -private SSLContext sslcontext = null; - -private static SSLContext createEasySSLContext() throws IOException { -try { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, new TrustManager[] { new EasyX509TrustManager( - null) }, null); - return context; -} catch (Exception e) { - throw new IOException(e.getMessage()); -} -} - -private SSLContext getSSLContext() throws IOException { -if (this.sslcontext == null) { - this.sslcontext = createEasySSLContext(); -} -return this.sslcontext; -} - - -public Socket connectSocket(Socket sock, String host, int port, - InetAddress localAddress, int localPort, HttpParams params) - throws IOException, UnknownHostException, ConnectTimeoutException { -int connTimeout = HttpConnectionParams.getConnectionTimeout(params); -int soTimeout = HttpConnectionParams.getSoTimeout(params); - -InetSocketAddress remoteAddress = new InetSocketAddress(host, port); -SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); - -if ((localAddress != null) || (localPort > 0)) { - // we need to bind explicitly - if (localPort < 0) { - localPort = 0; // indicates "any" - } - InetSocketAddress isa = new InetSocketAddress(localAddress, - localPort); - sslsock.bind(isa); -} - -sslsock.connect(remoteAddress, connTimeout); -sslsock.setSoTimeout(soTimeout); -return sslsock; - -} - - -public Socket createSocket() throws IOException { -return getSSLContext().getSocketFactory().createSocket(); -} - - -public boolean isSecure(Socket socket) throws IllegalArgumentException { -return true; -} - - -public Socket createSocket(Socket socket, String host, int port, - boolean autoClose) throws IOException, UnknownHostException { -return getSSLContext().getSocketFactory().createSocket(socket, host, - port, autoClose); -} - -// ------------------------------------------------------------------- -// javadoc in org.apache.http.conn.scheme.SocketFactory says : -// Both Object.equals() and Object.hashCode() must be overridden -// for the correct operation of some connection managers -// ------------------------------------------------------------------- - -public boolean equals(Object obj) { -return ((obj != null) && obj.getClass().equals( - EasySSLSocketFactory.class)); -} - -public int hashCode() { -return EasySSLSocketFactory.class.hashCode(); -} -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/EasyX509TrustManager.java b/qy/src/main/java/com/qiyou/mb/android/utils/EasyX509TrustManager.java deleted file mode 100644 index bb0e9da..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/EasyX509TrustManager.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -public class EasyX509TrustManager implements X509TrustManager { - - private X509TrustManager standardTrustManager = null; - - - public EasyX509TrustManager(KeyStore keystore) - throws NoSuchAlgorithmException, KeyStoreException { - super(); - TrustManagerFactory factory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); - factory.init(keystore); - TrustManager[] trustmanagers = factory.getTrustManagers(); - if (trustmanagers.length == 0) { - throw new NoSuchAlgorithmException("no trust manager found"); - } - this.standardTrustManager = (X509TrustManager) trustmanagers[0]; - } - - - public void checkClientTrusted(X509Certificate[] certificates, - String authType) throws CertificateException { - standardTrustManager.checkClientTrusted(certificates, authType); - } - - - public void checkServerTrusted(X509Certificate[] certificates, - String authType) throws CertificateException { - if ((certificates != null) && (certificates.length == 1)) { - certificates[0].checkValidity(); - } else { - standardTrustManager.checkServerTrusted(certificates, authType); - } - } - - - public X509Certificate[] getAcceptedIssuers() { - return this.standardTrustManager.getAcceptedIssuers(); - } -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/ExportLog.java b/qy/src/main/java/com/qiyou/mb/android/utils/ExportLog.java deleted file mode 100644 index 86be52c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/ExportLog.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.qiyou.mb.android.utils; - -public class ExportLog { - - public ExportLog() { - // TODO Auto-generated constructor stub - } - public static String TAG="com.qiyou.mb.android.utils.EXPORT_LOG"; - - public void exportLog() - { - - - - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/Exportdb.java b/qy/src/main/java/com/qiyou/mb/android/utils/Exportdb.java deleted file mode 100644 index d911fca..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/Exportdb.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.content_providers.TrackProvider; -import com.qiyou.mb.android.utils.log.QLog; - -import android.content.Context; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.database.sqlite.SQLiteDatabase.CursorFactory; -import android.widget.Toast; - -public class Exportdb { - public static String dTAG = "com.qiyou"; - public static String TAG = "com.qiyou.ExportDb"; - - - -// private static final String DATABASE_NAME = "tracks.db"; -// private static final int DATABASE_VERSION = 7; - String destXml; - private String mDestXmlFilename = QiYouConstant.SD_PATH +"export.xml"; - private SQLiteDatabase mDb; - private Exporter mExporter; - String strWhere =" where 1=1 "; - Context context; - String _ids=""; - void prepareExp(){ - /* - PlacesDatabaseHelper dbHelper = new PlacesDatabaseHelper( context, DATABASE_NAME, - null, DATABASE_VERSION); -// File path = new File("/sdcard/qiyou");// 创建目录 - File f = new File("/sdcard/qiyou/tracks.db");// 创建文件 - try { - //tracksDB = dbHelper.getWritableDatabase(); - mDb =SQLiteDatabase.openOrCreateDatabase(f, null); - - } catch (SQLiteException e) { - mDb = null; - QLog.getLogger().d("ExportDB", "Database Opening exception"); - } - */ - - - mDb = TrackProvider.getTracksDB(); - - - } - - public void ExportTracks(){ - - exportData() ; - } - - public void ExportTracks(String[] ids){ - - String strIn = "-1"; - for(String id:ids){ - strIn += "," + id; - QLog.getLogger().d(dTAG,TAG+ "prepare export Track id of " + id); - _ids+="_"+id; - } -// strWhere += " and _id in ("+strIn+")"; - QLog.getLogger().d(dTAG,TAG+ " export strWhere: " + strWhere); - - exportData() ; - } - - public Exportdb(Context ct){ - context =ct; - prepareExp(); - } - - public Exportdb(SQLiteDatabase db, String destXml) { - - try { - // create a file on the sdcard to export the - // database contents to - File myFile = new File(mDestXmlFilename); - myFile.createNewFile(); - - FileOutputStream fOut = new FileOutputStream(myFile); - BufferedOutputStream bos = new BufferedOutputStream(fOut); - - mExporter = new Exporter(bos); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - void exportData() { - - try { - // create a file on the sdcard to export the - // database contents to - mDestXmlFilename = QiYouConstant.SD_PATH + "export"+ _ids+".xml"; - File myFile = new File(mDestXmlFilename); - myFile.createNewFile(); - - FileOutputStream fOut = new FileOutputStream(myFile); - BufferedOutputStream bos = new BufferedOutputStream(fOut); - - mExporter = new Exporter(bos); - - - mExporter.startDbExport(mDb.getPath()); - - // get the tables out of the given sqlite database - String sql = "SELECT * FROM sqlite_master"; - - Cursor cur = mDb.rawQuery(sql, new String[0]); - cur.moveToFirst(); - - String tableName; - while (cur.getPosition() < cur.getCount()) { - tableName = cur.getString(cur.getColumnIndex("name")); - - // don't process these two tables since they are used - // for metadata - if (!tableName.equals("android_metadata") - && !tableName.equals("sqlite_sequence")) { - exportTable(tableName); - } - - cur.moveToNext(); - } - mExporter.endDbExport(); - mExporter.close(); - - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - Toast toast= Toast.makeText(context,"数据已导出至 "+mDestXmlFilename,Toast.LENGTH_SHORT ); - toast.show(); - - } - - private void exportTable(String tableName) throws IOException { - mExporter.startTable(tableName); - - // get everything from the table - String sql = "select * from " + tableName + strWhere; - QLog.getLogger().d(dTAG,TAG+ " export sql: " + sql); - Cursor cur = mDb.rawQuery(sql, new String[0]); - int numcols = cur.getColumnCount(); - - cur.moveToFirst(); - - // move through the table, creating rows - // and adding each column with name and value - // to the row - while (cur.getPosition() < cur.getCount()) { - mExporter.startRow(); - String name; - String val; - QLog.getLogger().d(dTAG, - TAG + " Start to process row with ID " + cur.getString(0)); - try{ - for (int idx = 0; idx < numcols; idx++) { - name = cur.getColumnName(idx); - val = cur.getString(idx); - mExporter.addColumn(name, val); - } - - mExporter.endRow(); - cur.moveToNext(); - } - catch(IllegalStateException e){ - Utils.logStackTrace(e, dTAG); - continue; - } - catch(Exception e){ - Utils.logStackTrace(e, dTAG); - } - } - - cur.close(); - - mExporter.endTable(); - } - - - - class Exporter { - private static final String CLOSING_WITH_TICK = "'>"; - private static final String START_DB = "> getFiles(File file) { - - - // 从根目录开始扫描 - Log.i(TAG, file.getPath()); - List> fileList = new ArrayList>(); -// HashMap fileList = new HashMap(); - getFileList(file, fileList); - return fileList; - } - - /** - * @param path - * @param fileList - * 注意的是并不是所有的文件夹都可以进行读取的,权限问题 - */ - -// private static void getFileList(File path, HashMap fileList) { - private static void getFileList(File path, List> fileList) { - Map file; - // 如果是文件夹的话 - if (path.isDirectory()) { - // 返回文件夹中有的数据 - File[] files = path.listFiles(); - // 先判断下有没有权限,如果没有权限的话,就不执行了 - if (null == files) - return; - - for (int i = 0; i < files.length; i++) { - getFileList(files[i], fileList); - } - } - // 如果是文件的话直接加入 - else { - Log.i(TAG, path.getAbsolutePath()); - // 进行文件的处理 - String filePath = path.getAbsolutePath(); - if(filePath.toUpperCase().endsWith(".GPX")) { - file = new HashMap(); - file.put("fileName", filePath); - /*// 文件名 - String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); - Map file = new HashMap(); - file.put(fileName, filePath); - // 添加 - */ - fileList.add(file); - } - } - } - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/FileUtil.java b/qy/src/main/java/com/qiyou/mb/android/utils/FileUtil.java deleted file mode 100644 index bf1eb6d..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/FileUtil.java +++ /dev/null @@ -1,350 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.io.*; - -import org.apache.http.util.EncodingUtils; - -import android.content.Context; - -import com.facebook.crypto.Crypto; -import com.facebook.crypto.Entity; -import com.facebook.crypto.exception.CryptoInitializationException; -import com.facebook.crypto.exception.KeyChainException; -import com.qiyou.mb.android.utils.log.QLog; - -/** - * @author Toby 复制文件夹或文件夹 - */ -public class FileUtil { - public static final String TAG = "com.qiyou.mb.android.utils.FileUtil"; - public static final String dTAG = "com.qiyou"; - // 复制文件 - public static void copyFile(File sourceFile, File targetFile) throws IOException { - BufferedInputStream inBuff = null; - BufferedOutputStream outBuff = null; - try { - // 新建文件输入流并对它进行缓冲 - inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); - - // 新建文件输出流并对它进行缓冲 - outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); - - // 缓冲数组 - byte[] b = new byte[1024 * 5]; - int len; - while ((len = inBuff.read(b)) != -1) { - outBuff.write(b, 0, len); - } - // 刷新此缓冲的输出流 - outBuff.flush(); - } finally { - // 关闭流 - if (inBuff != null) - inBuff.close(); - if (outBuff != null) - outBuff.close(); - } - } - - // 复制文件夹 - public static void copyDirectiory(String sourceDir, String targetDir) throws IOException { - // 新建目标目录 - (new File(targetDir)).mkdirs(); - // 获取源文件夹当前下的文件或目录 - File[] file = (new File(sourceDir)).listFiles(); - for (int i = 0; i < file.length; i++) { - if (file[i].isFile()) { - // 源文件 - File sourceFile = file[i]; - // 目标文件 - File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName()); - copyFile(sourceFile, targetFile); - } - if (file[i].isDirectory()) { - // 准备复制的源文件夹 - String dir1 =sourceDir.endsWith(File.separator)?(sourceDir + file[i].getName()): (sourceDir + "/" + file[i].getName()); - // 准备复制的目标文件夹 - String dir2 = targetDir.endsWith(File.separator)?(targetDir + file[i].getName()): (targetDir + "/" + file[i].getName()); - copyDirectiory(dir1, dir2); - } - } - } - - /** - * - * @param srcFileName - * @param destFileName - * @param srcCoding - * @param destCoding - * @throws IOException - */ - public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding) throws IOException {// 把文件转换为GBK文件 - BufferedReader br = null; - BufferedWriter bw = null; - try { - br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding)); - bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding)); - char[] cbuf = new char[1024 * 5]; - int len = cbuf.length; - int off = 0; - int ret = 0; - while ((ret = br.read(cbuf, off, len)) > 0) { - off += ret; - len -= ret; - } - bw.write(cbuf, 0, off); - bw.flush(); - } finally { - if (br != null) - br.close(); - if (bw != null) - bw.close(); - } - } - - /** - * - * @param filepath - * @throws IOException - */ - public static void del(String filepath) throws IOException { - File f = new File(filepath);// 定义文件路径 - if (f.exists() && f.isDirectory()) {// 判断是文件还是目录 - if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除 - f.delete(); - } else {// 若有则把文件放进数组,并判断是否有下级目录 - File delFile[] = f.listFiles(); - int i = f.listFiles().length; - for (int j = 0; j < i; j++) { - if (delFile[j].isDirectory()) { - del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径 - } - delFile[j].delete();// 删除文件 - } - } - } - } - - final static String DELICODES="ThisIs->DELICOD@$&*S?>"; - public static void writeFile(Crypto crypto,Entity entity,String fileName,String plainText ) throws IOException, CryptoInitializationException, KeyChainException{ - // Creates a new Crypto object with default implementations of - // a key chain as well as native library. - /*Crypto crypto = new Crypto( - new SharedPrefsBackedKeyChain(context), - new SystemNativeCryptoLibrary()); - entity = new Entity("TEST");*/ - // Check for whether the crypto functionality is available - // This might fail if android does not load libaries correctly. - if (!crypto.isAvailable()) { - QLog.getLogger().d(dTAG, "crypto is not available"); - return; - } - QLog.getLogger().d(dTAG, "crypto is available"); - File file = new File(fileName); - - OutputStream fileStream = new BufferedOutputStream( - new FileOutputStream(file)); - - - - - // Creates an output stream which encrypts the data as - // it is written to it and writes it out to the file. - OutputStream outputStream = crypto.getCipherOutputStream( - fileStream, - entity); - -// plainTextBytes =(plainText+DELICODES).getBytes(); - - // Write plaintext to it. - outputStream.write((plainText+DELICODES).getBytes()); - - outputStream.close(); - QLog.getLogger().d(dTAG, " crypto encrypts successfully..........."); - } - - public static String readFile(String fileName,Crypto crypto,Entity entity){ - - if (!crypto.isAvailable()) { - return null; - } - - File file = new File(fileName); - - if(!file.exists()) return null; - String res=null; - // Get the file to which ciphertext has been written. - FileInputStream fileStream; - try { - fileStream = new FileInputStream(file); - - - // Creates an input stream which decrypts the data as - // it is read from it. - InputStream inputStream = crypto.getCipherInputStream( - fileStream, - entity); - - - int length = inputStream.available(); - - byte [] buffer = new byte[length]; - inputStream.read(buffer); - - - File file2 = new File(fileName+"_dd"); - - FileOutputStream fos = new FileOutputStream(file2); -// FileOutputStream fos1 = new FileOutputStream(file, isAppend) ; - fos.write(buffer); - fos.close(); - - - res = EncodingUtils.getString(buffer, "UTF-8"); - - inputStream.close(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (CryptoInitializationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (KeyChainException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return res; - -/* - // Read into a byte array. - int read; - byte[] buffer = new byte[1024]; - - // You must read the entire stream to completion. - // The verification is done at the end of the stream. - // Thus not reading till the end of the stream will cause - // a security bug. - while ((read = inputStream.read(buffer)) != -1) { - - } - - inputStream.close(); - */ - - } - - public static void encodeFile(String encryptedFileName,String plainedFileName,Crypto crypto,Entity entity){ - - File mEncryptedFile = new File(encryptedFileName); - File mPlainFile = new File(plainedFileName); -// if(!mEncryptedFile.exists()) return null; -// String res=null; - - if (!crypto.isAvailable()) { - QLog.getLogger().d(dTAG, "crypto is not available..........................."); - return; - } - - try{ - BufferedOutputStream fileStream = new BufferedOutputStream(new FileOutputStream(mEncryptedFile)); -// BufferedOutputStream fileStream = new BufferedOutputStream(new FileOutputStream(mPlainFile)); - OutputStream outputStream; - outputStream = crypto.getCipherOutputStream(fileStream, entity); - int read; - byte[] buffer = new byte[1024]; - BufferedInputStream bis = new BufferedInputStream(new FileInputStream(mPlainFile)); - while ((read = bis.read(buffer)) != -1) { - outputStream.write(buffer, 0, read); - } - outputStream.close(); - bis.close(); - mPlainFile.delete(); - QLog.getLogger().d(dTAG, " EnCoded from "+plainedFileName+"................."); - }catch(IOException ioe){ - Utils.logStackTrace(ioe, TAG); - } catch (CryptoInitializationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (KeyChainException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - public static void decodeFile(String encryptedFileName,String plainedFileName,Crypto crypto,Entity entity){ - - File mEncryptedFile = new File(encryptedFileName); - File mDecryptedFile = new File(plainedFileName); - if(!mEncryptedFile.exists()) { - QLog.getLogger().d(dTAG,encryptedFileName+ " dose not exist "); - return ; - } - if (!crypto.isAvailable()) { - QLog.getLogger().d(dTAG, "crypto is not available......................"); - return; - } - try{ - InputStream inputStream; - FileInputStream fileStream = new FileInputStream(mEncryptedFile); - inputStream = crypto.getCipherInputStream(fileStream, entity); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - OutputStream outputStream = new FileOutputStream(mDecryptedFile); - BufferedInputStream bis = new BufferedInputStream(inputStream); - int mRead; - byte[] mBuffer = new byte[1024]; - while ((mRead = bis.read(mBuffer)) != -1) { - outputStream.write(mBuffer, 0, mRead); - } - bis.close(); - out.writeTo(outputStream); - inputStream.close(); - outputStream.close(); - out.close(); - QLog.getLogger().d(dTAG, " deCoded from "+encryptedFileName+"................."); - }catch(IOException ioe){ - Utils.logStackTrace(ioe, TAG); - } catch (CryptoInitializationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (KeyChainException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public static String readEncodedFile(String fileName, Crypto crypto,Entity entity){ - String tmpFileName =fileName+"tmp"; - String ret=null; - - QLog.getLogger().d(dTAG, " begin to decode File "+fileName+".............."); - - decodeFile(fileName,tmpFileName,crypto, entity); - -// QLog.getLogger().d(dTAG, " begin to read from decoded File "+tmpFileName+".............."); - try{ - ret = Utils.readSDFile(tmpFileName); - -// QLog.getLogger().d(dTAG, " readed content is "+ret+".............."); - File tmp = new File(tmpFileName); - tmp.delete(); - - }catch(IOException e){ - Utils.logStackTrace(e, TAG); - } - catch(Exception e){ - Utils.logStackTrace(e, TAG); - } - - return ret; - - } - - - - - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/FootmarkLevel.java b/qy/src/main/java/com/qiyou/mb/android/utils/FootmarkLevel.java deleted file mode 100644 index 8c6209d..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/FootmarkLevel.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.qiyou.mb.android.utils; - -public enum FootmarkLevel { - -STANDARD(0),GEO(1),NOPIC(2),NOWORD(3); - -FootmarkLevel(int level){ - this.level=level; -} -private int level=0; -@Override -public String toString() { - - return String.valueOf(this.level); - -} - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/GoogleEleResult.java b/qy/src/main/java/com/qiyou/mb/android/utils/GoogleEleResult.java deleted file mode 100644 index 2e008d5..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/GoogleEleResult.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.util.ArrayList; - -public class GoogleEleResult { - public GoogleEleResult(){} - private String status; - private ArrayList results = new ArrayList() ; - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - public ArrayList getResults() { - return results; - } - public void setResults(ArrayList results) { - this.results = results; - } - - -} - - - diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/HackyViewPager.java b/qy/src/main/java/com/qiyou/mb/android/utils/HackyViewPager.java deleted file mode 100644 index dbcdbf2..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/HackyViewPager.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.qiyou.mb.android.utils; - -import android.content.Context; -import android.support.v4.view.ViewPager; -import android.util.AttributeSet; -import android.util.Log; -import android.view.MotionEvent; - -/** - * Hacky fix for Issue #4 and - * http://code.google.com/p/android/issues/detail?id=18990 - * - * ScaleGestureDetector seems to mess up the touch events, which means that - * ViewGroups which make use of onInterceptTouchEvent throw a lot of - * IllegalArgumentException: pointerIndex out of range. - * - * There's not much I can do in my code for now, but we can mask the result by - * just catching the problem and ignoring it. - * - * @author Chris Banes - */ -public class HackyViewPager extends ViewPager { - - - private static final String TAG = "HackyViewPager"; - - public HackyViewPager(Context context) { - super(context); - } - - public HackyViewPager(Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - public boolean onInterceptTouchEvent(MotionEvent ev) { - try { - return super.onInterceptTouchEvent(ev); - } catch (IllegalArgumentException e) { - //涓嶇悊浼? - Log.e(TAG,"hacky viewpager error1"); - return false; - }catch(ArrayIndexOutOfBoundsException e ){ - //涓嶇悊浼? - Log.e(TAG,"hacky viewpager error2"); - return false; - } - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/HoneycombStrictMode.java b/qy/src/main/java/com/qiyou/mb/android/utils/HoneycombStrictMode.java deleted file mode 100644 index cc1a4c3..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/HoneycombStrictMode.java +++ /dev/null @@ -1,34 +0,0 @@ - -package com.qiyou.mb.android.utils; - - - -import android.os.StrictMode; - -import com.qiyou.mb.android.utils.base.IStrictMode; - - -/** - * Implementation that supports the Strict Mode functionality - * available Honeycomb. - */ - -public class HoneycombStrictMode implements IStrictMode { - protected static String TAG = "HoneycombStrictMode"; - - /** - * Enable {@link StrictMode} - * TODO Set your preferred Strict Mode features. - */ - -@Override -public void enableStrictMode() { - StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() - .detectDiskReads() - .detectDiskWrites() - .detectNetwork() - .penaltyLog() - .penaltyFlashScreen() - .build()); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/ImageLoader.java b/qy/src/main/java/com/qiyou/mb/android/utils/ImageLoader.java deleted file mode 100644 index ae8abec..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/ImageLoader.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Collections; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import android.app.Activity; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.text.TextUtils; -import android.widget.ImageView; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.log.QLog; - -public class ImageLoader { - public static final String TAG = "com.qiyou.mb.android.utils.ImageLoader"; - public static final String dTAG = "com.qiyou"; - MemoryCache memoryCache = new MemoryCache(); - FileCache fileCache; - private Map imageViews = Collections - .synchronizedMap(new WeakHashMap()); - // 线程池 - ExecutorService executorService; - - public ImageLoader(Context context) { - fileCache = new FileCache(context); - executorService = Executors.newFixedThreadPool(5); - } - - // 当进入listview时默认的图片,可换成你自己的默认图片 - final int stub_id = R.drawable.icon_riding64;//.empty_photo; - final int SIZE=QiYouConstant.SUBNAIL_PIC_SIZE; - // 最主要的方法 - public void DisplayImage(String url, ImageView imageView) { - imageViews.put(imageView, url); - // 先从内存缓存中查找 -// QLog.getLogger().d(dTAG, TAG+" url is:"+url); - Bitmap bitmap = memoryCache.get(url); - - if (bitmap != null){ - QLog.getLogger().d(dTAG, TAG+" Get the Img from cache."); - imageView.setImageBitmap(bitmap); - } - else { - // 若没有的话则开启新线程加载图片 - QLog.getLogger().d(dTAG, TAG+" Img not exist in cache, start to load it."); - queuePhoto(url, imageView); - imageView.setImageResource(stub_id); - } - } - - /*public static void createSmallPic(final String picName,final int SMALLSIZE){ - final int SMALLSIZE=480; - new Thread(new Runnable(){ - @Override - public void run() { - com.qiyou.mb.android.utils.ImageLoader IL = new com.qiyou.mb.android.utils.ImageLoader(activity); - - Bitmap b= IL.getBitmap(picName, SMALLSIZE); - b= watermarkBitmap(b,null,QiYouConstant.MAP_PIC_WATER_MARK_WORDS); - String smallPicName=picName.substring(0,picName.lastIndexOf(".jpg"))+SMALLSIZE+".jpg"; - File file = new File(smallPicName); - FileOutputStream out; - try{ - out = new FileOutputStream(file); - if(b.compress(Bitmap.CompressFormat.PNG, 70, out)) - { - out.flush(); - out.close(); - } - - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - } - }).start(); - }*/ - - private void queuePhoto(String url, ImageView imageView) { - PhotoToLoad p = new PhotoToLoad(url, imageView); - - executorService.submit(new PhotosLoader(p)); - } - - public Bitmap getBitmap(String url ) { - return getBitmap(url,SIZE); - } - - public Bitmap getBitmap(String url,int size) { -// File f = fileCache.getFile(url); - if(TextUtils.isEmpty(url))return null; -// QLog.getLogger().d(dTAG, TAG +", url is: "+url); - File f = fileCache.getLocalMdFile(url); - - // 先从文件缓存中查找是否有 - Bitmap b = decodeFile(f,size); - if (b != null) - return b; - - // 最后从指定的url中下载图片 - try { - Bitmap bitmap = null; - URL imageUrl = new URL(url); - HttpURLConnection conn = (HttpURLConnection) imageUrl - .openConnection(); - conn.setConnectTimeout(30000); - conn.setReadTimeout(30000); - conn.setInstanceFollowRedirects(true); - InputStream is = conn.getInputStream(); - OutputStream os = new FileOutputStream(f); - CopyStream(is, os); - os.close(); - bitmap = decodeFile(f,size); - return bitmap; - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - private Bitmap decodeFile(File f) { - - return decodeFile(f,SIZE); - } - // decode这个图片并且按比例缩放以减少内存消耗,虚拟机对每张图片的缓存大小也是有限制的 - private Bitmap decodeFile(File f,int size) { - try { - // decode image size - BitmapFactory.Options o = new BitmapFactory.Options(); - o.inJustDecodeBounds = true; - FileInputStream is =new FileInputStream(f); - BitmapFactory.decodeStream(is, null, o); - is.close(); -// BitmapFactory.decodeStream(new FileInputStream(f), null, o); - - // Find the correct scale value. It should be the power of 2. - final int REQUIRED_SIZE =size;// 20;//70; - int width_tmp = o.outWidth, height_tmp = o.outHeight; - int scale = 1; - /* while (true) { - if (width_tmp / 2 < REQUIRED_SIZE - || height_tmp / 2 < REQUIRED_SIZE) - break; - width_tmp /= 2; - height_tmp /= 2; - scale *= 2; - }*/ - - while (width_tmp / 2 > REQUIRED_SIZE - || height_tmp / 2 > REQUIRED_SIZE) { - - width_tmp /= 2; - height_tmp /= 2; - scale *= 2; - } - - // decode with inSampleSize - BitmapFactory.Options o2 = new BitmapFactory.Options(); - o2.inSampleSize = scale; -// QLog.getLogger().d(dTAG,TAG +"Picture inSampleSize scale is:" + scale); -// FileInputStream is =new FileInputStream(f); - is =new FileInputStream(f); - Bitmap b = BitmapFactory.decodeStream(is, null, o2); - is.close(); - return b; -// return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); - } catch (FileNotFoundException e) { - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - return null; - } - - - - - /*private Bitmap decodeBitmp(){ - Display display=getWindowManager().getDefaultDisplay(); - int dw=display.getWidth(); - int dh=display.getHeight(); - - //加载图像 - BitmapFactory.Options options=new BitmapFactory.Options(); - options.inJustDecodeBounds=true;//设置之后可以设置长宽 - Bitmap bitmap=BitmapFactory.decodeFile(imageFilePath, options); - - int heightRatio=(int)Math.ceil(options.outHeight/(float)dh); - int widthRatio=(int)Math.ceil(options.outWidth/(float)dw); - - QLog.getLogger().d(TAG, dTAG+ " heith:"+heightRatio); - QLog.getLogger().d(TAG,dTAG+" width:"+widthRatio); - //判断长宽哪个大 - if(heightRatio>1 && widthRatio>1){ - if(heightRatio>widthRatio){ - options.inSampleSize=heightRatio; - }else{ - options.inSampleSize=widthRatio; - } - } - //对它进行真正的解码 - options.inJustDecodeBounds=false; - bitmap=BitmapFactory.decodeFile(imageFilePath, options); - } - */ - - - // Task for the queue - private class PhotoToLoad { - public String url; - public ImageView imageView; - - public PhotoToLoad(String u, ImageView i) { - url = u; - imageView = i; - } - } - - class PhotosLoader implements Runnable { - PhotoToLoad photoToLoad; - - PhotosLoader(PhotoToLoad photoToLoad) { - this.photoToLoad = photoToLoad; - } - - @Override - public void run() { - if (imageViewReused(photoToLoad)) - return; - Bitmap bmp = getBitmap(photoToLoad.url); - memoryCache.put(photoToLoad.url, bmp); - if (imageViewReused(photoToLoad)) - return; - BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); - // 更新的操作放在UI线程中 - Activity a = (Activity) photoToLoad.imageView.getContext(); - a.runOnUiThread(bd); - } - } - - /** - * 防止图片错位 - * - * @param photoToLoad - * @return - */ - boolean imageViewReused(PhotoToLoad photoToLoad) { - String tag = imageViews.get(photoToLoad.imageView); - if (tag == null || !tag.equals(photoToLoad.url)) - return true; - return false; - } - - // 用于在UI线程中更新界面 - class BitmapDisplayer implements Runnable { - Bitmap bitmap; - PhotoToLoad photoToLoad; - - public BitmapDisplayer(Bitmap b, PhotoToLoad p) { - bitmap = b; - photoToLoad = p; - } - - @Override - public void run() { - if (imageViewReused(photoToLoad)) - return; - if (bitmap != null) - photoToLoad.imageView.setImageBitmap(bitmap); - else - photoToLoad.imageView.setImageResource(stub_id); - } - } - - public void clearCache() { - memoryCache.clear(); - fileCache.clear(); - } - - public static void CopyStream(InputStream is, OutputStream os) { - final int buffer_size = 1024; - try { - byte[] bytes = new byte[buffer_size]; - for (;;) { - int count = is.read(bytes, 0, buffer_size); - if (count == -1) - break; - os.write(bytes, 0, count); - } - } catch (Exception ex) { - } - } -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/LegacyStrictMode.java b/qy/src/main/java/com/qiyou/mb/android/utils/LegacyStrictMode.java deleted file mode 100644 index e2f6db7..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/LegacyStrictMode.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.qiyou.mb.android.utils; - -import android.os.StrictMode; - -import com.qiyou.mb.android.utils.base.IStrictMode; - - -/** - * Implementation that supports the Strict Mode functionality - * available for the first platform release that supported Strict Mode. - */ -public class LegacyStrictMode implements IStrictMode { - - /** - * Enable {@link StrictMode} - * TODO Set your preferred Strict Mode features. - */ - @Override -public void enableStrictMode() { - StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() - .detectDiskReads() - .detectDiskWrites() - .detectNetwork() - .penaltyLog() - .build()); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/Location.java b/qy/src/main/java/com/qiyou/mb/android/utils/Location.java deleted file mode 100644 index 2530a4e..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/Location.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.qiyou.mb.android.utils; - - public class Location{ - public Location(){ } - - public double getLat() { - return lat; - } - public void setLat(double lat) { - this.lat = lat; - } - public double getLon() { - return lon; - } - public void setLon(double lon) { - this.lon = lon; - } - private double lat; - private double lon; -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/LocationEle.java b/qy/src/main/java/com/qiyou/mb/android/utils/LocationEle.java deleted file mode 100644 index ca58d8d..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/LocationEle.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.qiyou.mb.android.utils; - -public class LocationEle{ - public LocationEle(){} - - - public Location getLocation() { - return location; - } - public void setLocation(Location location) { - this.location = location; - } - public double getElevation() { - return elevation; - } - public void setElevation(double elevation) { - this.elevation = elevation; - } - private Location location; - private double elevation; - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/MemoryCache.java b/qy/src/main/java/com/qiyou/mb/android/utils/MemoryCache.java deleted file mode 100644 index b802b6e..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/MemoryCache.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import android.graphics.Bitmap; -import android.util.Log; - - -public class MemoryCache { - - public static final String TAG = "com.qiyou.mb.android.utils.MemoryCache"; - public static final String dTAG = "com.qiyou"; - // 放入缓存时是个同步操作 - // LinkedHashMap构造方法的最后一个参数true代表这个map里的元素将按照最近使用次数由少到多排列,即LRU - // 这样的好处是如果要将缓存中的元素替换,则先遍历出最近最少使用的元素来替换以提高效率 - private Map cache = Collections - .synchronizedMap(new LinkedHashMap(10, 1.5f, true)); - // 缓存中图片所占用的字节,初始0,将通过此变量严格控制缓存所占用的堆内存 - private long size = 0;// current allocated size - // 缓存只能占用的最大堆内存 - private long limit = 100000000;// max memory in bytes - - public MemoryCache() { - // use 25% of available heap size - setLimit(Runtime.getRuntime().maxMemory() / 4); - } - - public void setLimit(long new_limit) { - limit = new_limit; - Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB"); - } - - public Bitmap get(String id) { - try { - if (!cache.containsKey(id)) - return null; - return cache.get(id); - } catch (NullPointerException ex) { - return null; - } - } - - public void put(String id, Bitmap bitmap) { - try { - if (cache.containsKey(id)) - size -= getSizeInBytes(cache.get(id)); - cache.put(id, bitmap); - size += getSizeInBytes(bitmap); - checkSize(); - } catch (Throwable th) { - th.printStackTrace(); - } - } - - /** - * 严格控制堆内存,如果超过将首先替换最近最少使用的那个图片缓存 - * - */ - private void checkSize() { - Log.i(TAG, "cache size=" + size + " length=" + cache.size()); - if (size > limit) { - // 先遍历最近最少使用的元素 - Iterator> iter = cache.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - size -= getSizeInBytes(entry.getValue()); - iter.remove(); - if (size <= limit) - break; - } - Log.i(TAG, "Clean cache. New size " + cache.size()); - } - } - - public void clear() { - cache.clear(); - } - - /** - * 图片占用的内存 - * - * @param bitmap - * @return - */ - long getSizeInBytes(Bitmap bitmap) { - if (bitmap == null) - return 0; - return bitmap.getRowBytes() * bitmap.getHeight(); - } -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/MemorySoftCache.java b/qy/src/main/java/com/qiyou/mb/android/utils/MemorySoftCache.java deleted file mode 100644 index 89bec6a..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/MemorySoftCache.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.lang.ref.SoftReference; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import android.graphics.Bitmap; - -public class MemorySoftCache { - - public MemorySoftCache (){ - - } - - private Map> cache = Collections - .synchronizedMap(new HashMap>()); - - public Bitmap get(String id) { - if (!cache.containsKey(id)) - return null; - SoftReference ref = cache.get(id); - return ref.get(); - } - - public void put(String id, Bitmap bitmap) { - cache.put(id, new SoftReference(bitmap)); - } - - public void clear() { - cache.clear(); - } - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/NoScrollGridView.java b/qy/src/main/java/com/qiyou/mb/android/utils/NoScrollGridView.java deleted file mode 100644 index 0aecb77..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/NoScrollGridView.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.qiyou.mb.android.utils; - -import android.content.Context; -import android.util.AttributeSet; -import android.widget.GridView; - -public class NoScrollGridView extends GridView { - - public NoScrollGridView(Context context) { - super(context); - } - - public NoScrollGridView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST); - super.onMeasure(widthMeasureSpec, expandSpec); - } - public int cursorPosition; -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/PlatformSpecificImplementationFactory.java b/qy/src/main/java/com/qiyou/mb/android/utils/PlatformSpecificImplementationFactory.java deleted file mode 100644 index bcbbaa5..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/PlatformSpecificImplementationFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.qiyou.mb.android.utils; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.base.IStrictMode; - - - -/** - * Factory class to create the correct instances - * of a variety of classes with platform specific - * implementations. - * - */ -public class PlatformSpecificImplementationFactory { - - - /** - * Create a new StrictMode instance. - * @return StrictMode - */ - public static IStrictMode getStrictMode() { - if (QiYouConstant.SUPPORTS_HONEYCOMB) - return new HoneycombStrictMode(); - else if (QiYouConstant.SUPPORTS_GINGERBREAD) - return new LegacyStrictMode(); - else - return null; - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/QCursorAdapter.java b/qy/src/main/java/com/qiyou/mb/android/utils/QCursorAdapter.java deleted file mode 100644 index 9336a10..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/QCursorAdapter.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.qiyou.mb.android.utils; - -import com.qiyou.mb.android.R; - -import android.content.Context; -import android.database.Cursor; -import android.graphics.Color; -import android.support.v4.widget.SimpleCursorAdapter; -import android.view.View; -import android.view.ViewGroup; - -public class QCursorAdapter extends SimpleCursorAdapter{ - - public QCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) -{ - super(context, layout, c, from, to); - // TODO Auto-generated constructor stub -} -//int[] colors={R.color.floralwhite,R.color.white }; -//int[] colors={R.color.lightcyan,R.color.ivory };//R.color.lightcoral - int[] colors={R.color.ivory,R.color.snow };//R.color.lightcoral -//int[] colors={R.color.lightgray,R.color.lightpink }; -//int[] colors={R.color.springgreen,R.color.silver }; -//int selectedColor=R.color.cyan;//R.color.blanchedalmond; - int selectedColor=R.color.silver; - -@Override -public View getView(int position, View convertView, ViewGroup parent){ - -// if (position == selectItem) { -// convertView.setBackgroundColor(Color.RED); -// } -// else { -// convertView.setBackgroundColor(Color.TRANSPARENT); -// } -// - - View v =super.getView(position, convertView, parent); - v.setBackgroundResource(colors[position%2]); -// v.setBackgroundColor(colors[position%2]); - if (position == selectItem) { - v.setBackgroundResource(selectedColor); -// v.setBackgroundColor(Color.parseColor("#95AC5F")); - } - - return v; -} - -public void setSelectItem(int selectItem) { - this.selectItem = selectItem; -// View v =super.getView(selectItem, null, null); -// -// v.setBackgroundResource(selectedColor); - -} -private int selectItem=-1; - - } \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/QSimpleAdapter.java b/qy/src/main/java/com/qiyou/mb/android/utils/QSimpleAdapter.java deleted file mode 100644 index f568e9a..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/QSimpleAdapter.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.util.List; -import java.util.Map; - -import com.qiyou.mb.android.R; - -import android.content.Context; -import android.view.View; -import android.view.ViewGroup; -import android.widget.SimpleAdapter; - -public class QSimpleAdapter extends SimpleAdapter{ - - public QSimpleAdapter(Context context, List> data, - int resource, String[] from, int[] to) { - super(context, data, resource, from, to); - // TODO Auto-generated constructor stub - } -// int[] colors={R.color.floralwhite,R.color.white }; -// int[] colors={R.color.lightcyan,R.color.ivory }; - int[] colors={R.color.ivory,R.color.snow };//R.color.lightcoral - //int[] colors={R.color.lightgray,R.color.lightpink }; - //int[] colors={R.color.springgreen,R.color.silver }; -// int selectedColor=R.color.blanchedalmond; - int selectedColor=R.color.silver; - - @Override - public View getView(int position, View convertView, ViewGroup parent){ - View v =super.getView(position, convertView, parent); - v.setBackgroundResource(colors[position%2]); - if (position == selectItem) { - v.setBackgroundResource(selectedColor); - } - v.getBackground().setAlpha(150); - return v; - } - - - - public void setSelectItem(int selectItem) { - this.selectItem = selectItem; - } - private int selectItem=-1; -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/QiyouRestClient.java b/qy/src/main/java/com/qiyou/mb/android/utils/QiyouRestClient.java deleted file mode 100644 index 27912da..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/QiyouRestClient.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.qiyou.mb.android.utils; -import org.apache.http.HttpEntity; -import org.apache.http.protocol.HttpContext; - -import android.content.Context; - -import com.loopj.android.http.*; - -public class QiyouRestClient { - - - - /*private static final String BASE_URL = "http://home:8080/qiyouji/"; - - private static AsyncHttpClient client = new AsyncHttpClient(); - - public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.get(getAbsoluteUrl(url), params, responseHandler); - } - - public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.post(getAbsoluteUrl(url), params, responseHandler); - } - - public static void post (Context context, String url, HttpEntity entity, String contentType, - ResponseHandlerInterface responseHandler){ - client.post(context, getAbsoluteUrl(url), entity, contentType, responseHandler); - } - - public static HttpContext getHttpContext(){ - return client.getHttpContext(); - } - - private static String getAbsoluteUrl(String relativeUrl) { - return BASE_URL + relativeUrl; - } - -public static void setCookieStore(PersistentCookieStore myCookieStore) { - // TODO Auto-generated method stub - client.setCookieStore(myCookieStore); - -} -*/ - - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/TextDrawableView.java b/qy/src/main/java/com/qiyou/mb/android/utils/TextDrawableView.java deleted file mode 100644 index bc3961c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/TextDrawableView.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.qiyou.mb.android.utils; - -import android.content.Context; -import android.graphics.Color; -import android.view.Gravity; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -public class TextDrawableView extends LinearLayout{ - private final String TAG = "TextDrawableView"; - TextView tv = null; - ImageView iv = null; - public TextDrawableView(Context context, String text,int width,int height) { - super(context); - this.setOrientation(VERTICAL); - getTv(context,text,11); -// tv.setPadding(-5.0, -5.0, -5.0, 2); - tv.setBackgroundColor(Color.RED); - tv.setTextColor(Color.WHITE); - tv.setGravity(Gravity.CENTER); - this.addView(tv, new LayoutParams(width,height)); - } - - /* - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public TextDrawableView(Context context, String text,int textSize,boolean hasMsg,float bear,int width,int height) { - super(context); - - *//* LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - View layout = inflater.inflate(R.layout.live_share_point, - (ViewGroup) this); - ImageView image = (ImageView) layout.findViewById(R.id.img_direction); - image.setBackgroundResource(R.drawable.icon_play); - image.setRotation(bear); - image.setAlpha(150); - TextView tv = (TextView) layout.findViewById(R.id.txt_name); - tv.setBackgroundResource( R.drawable.icon_textbox); - tv.setTextColor(Color.RED); - tv.setPadding(2, -5, -5, 6); - tv.setGravity(Gravity.CENTER); - *//* - - - this.setOrientation(LinearLayout.VERTICAL); - this.setBackgroundColor(color.holo_purple); - - - ImageView image = new ImageView(context); - - image.setBackgroundResource(R.drawable.icon_play); - image.setRotation(bear); -// image.setVisibility(View.GONE); - image.setAlpha(150); - image.setId(10); - - - getTv(context,text,textSize); -// tv.setBackgroundResource(getResources().getDrawable(R.drawable.icon_waypoint)); -// tv.setBackgroundResource( R.drawable.icon_textbox); - tv.setTextColor(Color.RED); - tv.setPadding(2.0, -5.0, -5.0, 6.0); - tv.setGravity(Gravity.CENTER); - tv.setId(10); - tv.setCompoundDrawables( getResources().getDrawable(R.drawable.icon_pass),null, null ,null); - -// tv.setRotation(bear); -// Drawable d =getResources().getDrawable(R.drawable.icon_waypoint); -// tv.setTextColor(Color.GREEN); -// tv.setCompoundDrawables( getResources().getDrawable(R.drawable.icon_pass),null, null ,null); -// android.view.ViewGroup.LayoutParams - this.addView(tv,0, new android.view.ViewGroup.LayoutParams(width,height)); -// this.addView(tv, new LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); -*//* TextView msg = new TextView(context); - msg.setText("something to say"); - msg.setBackgroundResource(R.drawable.icon_waypoint); - this.addView(msg, new LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));*//* - this.addView(image,1, new android.view.ViewGroup.LayoutParams( android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); - - - } - */ - public void reWriteText(String text){ - tv.setText(text); - } - - public String getText(){ - return tv.getText().toString(); - } - - public void reWriteText(String text,int width,int height){ - tv.setText(text); - this.addView(tv, new LayoutParams(width, height)); - } - - void getTv(Context context, String text,int textSize){ - tv = new TextView(context); - tv.setText(text); - tv.setTextSize(textSize); - - - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/TextDrawableViewKm.java b/qy/src/main/java/com/qiyou/mb/android/utils/TextDrawableViewKm.java deleted file mode 100644 index 1fb808c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/TextDrawableViewKm.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.qiyou.mb.android.utils; - -import android.content.Context; -import android.graphics.Color; -import android.view.Gravity; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -public class TextDrawableViewKm extends LinearLayout{ - private final String TAG = "TextDrawableView"; - TextView tv = null; - ImageView iv = null; - public TextDrawableViewKm(Context context, String text) { - super(context); - this.setOrientation(VERTICAL); - tv = new TextView(context); - tv.setText(text); - tv.setTextSize(12); - tv.setGravity(Gravity.CENTER); - tv.setPadding(0, 5, 0,0); - - - this.addView(tv, new LayoutParams(-1, -1)); - } - - - public void reWriteText(String text){ - tv.setText(text); - } - - public String getText(){ - return tv.getText().toString(); - } - - public void setBackGround(int background){ - tv.setBackgroundResource(background); - } - public void setTextColor(int color){ - tv.setTextColor(color); - } - public void setBackgroundColor(int color){ - tv.setBackgroundColor(color); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/TrackCache.java b/qy/src/main/java/com/qiyou/mb/android/utils/TrackCache.java deleted file mode 100644 index 5a6f21d..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/TrackCache.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.utils.log.QLog; - -import android.graphics.Bitmap; -import android.util.Log; - - -public class TrackCache { - - public static final String TAG = "com.qiyou.mb.android.utils.TrackCache"; - public static final String dTAG = "com.qiyou"; - // 放入缓存时是个同步操作 - // LinkedHashMap构造方法的最后一个参数true代表这个map里的元素将按照最近使用次数由少到多排列,即LRU - // 这样的好处是如果要将缓存中的元素替换,则先遍历出最近最少使用的元素来替换以提高效率 - private Map cache = Collections - .synchronizedMap(new LinkedHashMap(10, 1.5f, true)); - // 缓存中图片所占用的字节,初始0,将通过此变量严格控制缓存所占用的堆内存 - private long size = 0;// current allocated size - // 缓存只能占用的最大堆内存 - private long limit = 100000000;// max memory in bytes - - public TrackCache() { - // use 25% of available heap size - setLimit(Runtime.getRuntime().maxMemory() / 8); - } - - public void setLimit(long new_limit) { - limit = new_limit; - QLog.getLogger().d(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB"); - } - - public Track get(Integer id) { - try { - if (!cache.containsKey(id)) - return null; - return cache.get(id); - } catch (NullPointerException ex) { - return null; - } - } - - public void put(Integer id, Track track) { - try { - if (cache.containsKey(id)) - size -= getSizeInBytes(cache.get(id)); - cache.put(id, track); - size += getSizeInBytes(track); - checkSize(); - } catch (Throwable th) { - th.printStackTrace(); - } - } - - /** - * 严格控制堆内存,如果超过将首先替换最近最少使用的那个图片缓存 - * - */ - private void checkSize() { - QLog.getLogger().d(TAG, "cache size=" + size / 1024. / 1024.+ "MB, length=" + cache.size()); - if (size > limit) { - // 先遍历最近最少使用的元素 - Iterator> iter = cache.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - size -= getSizeInBytes(entry.getValue()); - iter.remove(); - if (size <= limit) - break; - } - QLog.getLogger().d(TAG, "Clean cache. New size " + cache.size()); - } - } - - public void clear() { - cache.clear(); - } - - /** - * 图片占用的内存 - * - * @param bitmap - * @return - */ - long getSizeInBytes(Track track) { - if ( track == null) - return 0; - return track.getTrackBean().getTrkseg().size()*500 - +track.getTrackBean().getRoadWps().size()*1000 - +track.getTrackBean().getMdWps().size()*1000; - } -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/TrackInterface.java b/qy/src/main/java/com/qiyou/mb/android/utils/TrackInterface.java deleted file mode 100644 index 352f055..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/TrackInterface.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.qiyou.mb.android.utils; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.concurrent.CopyOnWriteArrayList; - -//import org.alternativevision.gpx.GPXParser; -//import org.alternativevision.gpx.beans.GPX; - -import android.content.Context; -import android.os.Handler; -import android.os.Message; -import android.text.TextUtils; -import android.widget.Toast; - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.enums.TrackStatus; -import com.qiyou.mb.android.utils.log.QLog; - -public class TrackInterface { - public static final String TAG = "com.qiyou.mb.android.utils.TrackInterface"; - public static final String dTAG = "com.qiyou"; - - public TrackInterface() { - // TODO Auto-generated constructor stub - } - - private String mDestXmlFilename = QiYouConstant.SD_PATH +"export.xml"; - public String exportGPX(final Context context,final Track track) { - - /*final Handler handler = new Handler(){ - - @Override - public void handleMessage(Message msg) { - - //关闭ProgressDialog -// progressDialog.dismiss(); - - //更新UI -// switchButtonStatus(); - - if(msg.what==1){ -// - Toast.makeText(context,"数据已导出至 "+mDestXmlFilename,Toast.LENGTH_SHORT ).show(); - }else - { - Toast.makeText(context,"数据导出出现错误,导出失败。",Toast.LENGTH_SHORT ).show(); - } - - - - }};*/ - -// new Thread(){ -// @Override -// public void run() { - try { -// -// int id =track.getTrackBean().getTrackId(); - - File file=new File(QiYouConstant.EXP_PATH ); - if(!file.exists()){ //在SD卡上创建目录: - file.mkdir(); - QLog.getLogger().d(dTAG, "Utils: "+ "App Path created on SD as "+ QiYouConstant.EXP_PATH); - - } -// mDestXmlFilename = QiYouConstant.EXP_PATH + "GPX_"+ id+".gpx"; - mDestXmlFilename = QiYouConstant.EXP_PATH + "GPX_"+ track.getTrackBean().getName()+".gpx"; - Exporter mExporter =new Exporter(mDestXmlFilename); - mExporter.startGPXExport(); - /* CopyOnWriteArrayList wbs =track.getTrackBean().getTrkseg(); - CopyOnWriteArrayList rdwbs =track.getTrackBean().getRoadWps();*/ - ArrayList wbs =track.getTrackBean().getTrkseg(); - ArrayList rdwbs =track.getTrackBean().getRoadWps(); - String trackptFmt="\n\n%.2f\n\n%.2f\n" + - "%s\n"+ - "%s\n"+ - "%s\n"+ - ""; - String trackpt ; - String cmt=""; - - - for(Waypoint_bean wb :wbs){ - if(wb==null)continue; - int i=0; - for(Waypoint_bean rdwb:rdwbs){ - i++; - if(rdwb!=null && wb.getTime()==rdwb.getTime()){ - wb=rdwb; - break; - } - } -// Waypoint_bean nextWb=i\n"; - private static final String GPX_HEAD="\n" - ; - private static final String GPX_META= - "\n" - +"\n" - +"\n" - +"\n" - ; - private static final String GPX_TRK_START= - "\n" - +"\n" - +"\n" - +"" - ; - private static final String GPX_TRK_END="\n\n\n"; - - private BufferedOutputStream mbufferos; - - public Exporter(String mDestXmlFilename) throws FileNotFoundException { - - try { - // create a file on the sdcard to export the - // database contents to - File myFile = new File(mDestXmlFilename); - myFile.createNewFile(); - - FileOutputStream fOut = new FileOutputStream(myFile); - mbufferos = new BufferedOutputStream(fOut); -// this(new BufferedOutputStream( new FileOutputStream(mDestXmlFilename))); - - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - - } - -// public Exporter(BufferedOutputStream bos) { -// mbufferos = bos; -// } - - public void close() throws IOException { - if (mbufferos != null) { - mbufferos.close(); - } - } - - public void startGPXExport() throws IOException { - String stg = XML_HEAD + GPX_HEAD + GPX_META +GPX_TRK_START; - mbufferos.write(stg.getBytes()); - } - - public void endGPXExport() throws IOException { - mbufferos.write(GPX_TRK_END.getBytes()); - close(); - } - - public void addTrkpt(String trkpt) throws IOException { -// String stg = trkpt; - mbufferos.write(trkpt.getBytes()); - } - - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/Utils.java b/qy/src/main/java/com/qiyou/mb/android/utils/Utils.java deleted file mode 100644 index e37d718..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/Utils.java +++ /dev/null @@ -1,2247 +0,0 @@ -/** - * - */ -package com.qiyou.mb.android.utils; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.content.ContentUris; -import android.content.Context; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; -import android.content.pm.PackageManager; -import android.database.Cursor; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.location.Location; -import android.location.LocationManager; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.preference.PreferenceManager; -import android.provider.DocumentsContract; -import android.provider.MediaStore; -import android.text.TextUtils; -import android.util.Log; -import android.view.View; -import android.view.View.MeasureSpec; -import android.view.inputmethod.InputMethodManager; - -import com.baidu.mapapi.model.LatLng; -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; -import com.loopj.android.http.Base64; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.beans.Track; -import com.qiyou.mb.android.beans.basic.Track_bean; -import com.qiyou.mb.android.beans.basic.User_bean; -import com.qiyou.mb.android.beans.basic.Waypoint_bean; -import com.qiyou.mb.android.utils.enums.TrackType; -import com.qiyou.mb.android.utils.enums.wpFlag; -import com.qiyou.mb.android.utils.log.QLog; - -import org.alternativevision.gpx.GPXParser; -import org.alternativevision.gpx.beans.GPX; -import org.apache.http.util.EncodingUtils; -import org.xml.sax.SAXException; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.parsers.ParserConfigurationException; -/** - * @author mwang - * - */ -public class Utils { - public static final String dTAG ="com.qiyou"; - public static final String TAG ="com.qiyou.Utils"; - - /** - * - */ - public Utils() { - // TODO Auto-generated constructor stub - } - - public static boolean isNumeric(String str) { - Pattern pattern = Pattern.compile("[0-9]*"); - return pattern.matcher(str).matches(); - } - - - public static String getGPXformatedTime(Long time) - { - - if(time==0) return ""; - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss"); - return df.format(new Date(time)); - } - - public static String getFormatedTime(Long time) - { - - if(time==0) return ""; - SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - return df.format(new Date(time)); - - } - - public static String getFormatedTime(String format,Long time) - { - - if(time==0) return ""; - SimpleDateFormat df = new SimpleDateFormat(format); - return df.format(new Date(time)); - - } - public static String getFormatedTime (Long time,String format) - { - - if(time==0) return ""; - SimpleDateFormat df = new SimpleDateFormat(format); - return df.format(new Date(time)); - - } - - public static String getFormatedTimeMonthDay(Long time) - { - - if(time==0) return ""; - SimpleDateFormat df = new SimpleDateFormat("MM/dd HH:mm"); - return df.format(new Date(time)); - - } - public static String getShortFormatedTime(Long time) - { - - if(time==0) return ""; - SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd"); - return df.format(new Date(time)); - - /* - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); - - Date dt =null;dt.getd getDateTimeInstance() - try { - dt = df.parse(time.toString()); - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return dt; - */ - - } - - public static String getTimeCnt(Long time ){ - return getTimeCnt( time,true); - } - - public static String getTimeMS(Long time) - { - // int hour =Integer.valueOf(String.valueOf(time/1000/60/60)); -/* long hour = time/1000/60/60; - long minute = (time - hour*3600*1000)/1000/60; - long second = (time -hour*3600*1000 - minute*60*1000)/1000; - int ish =Integer.valueOf(String.valueOf(hour)); - int ism = Integer.valueOf(String.valueOf(minute)); - int iss = Integer.valueOf(String.valueOf(second)); - String sh = Integer.valueOf(String.valueOf(hour))>0 ? Integer.valueOf(String.valueOf(hour)).toString() :"00"; - String sm = Integer.valueOf(String.valueOf(minute))>0 ? Integer.valueOf(String.valueOf(minute)).toString() :"00"; - String ss = Integer.valueOf(String.valueOf(second))>0 ? Integer.valueOf(String.valueOf(second)).toString() :"00"; - if (10>ish && ish>0)sh ="0"+sh; - if (10>ism && ism>0)sm ="0"+sm; - if (10>iss && iss>0)ss ="0"+ss;*/ - - int ish = (int) (time/1000/60/60); - int ism = (int) ((time - ish*3600*1000)/1000/60); - int iss = (int) ((time -ish*3600*1000 - ism*60*1000)/1000); -// int ish =Integer.valueOf(String.valueOf(hour)); -// int ism = Integer.valueOf(String.valueOf(minute)); -// int iss = Integer.valueOf(String.valueOf(second)); - String sh = String.valueOf( ish>0 ?ish :"00") ; - String sm = String.valueOf(ism>0 ? ism :"00") ; - String ss = String.valueOf(iss>0 ?iss :"00" ) ; - if (10>ish && ish>0)sh ="0"+sh; - if (10>ism && ism>0)sm ="0"+sm; - if (10>iss && iss>0)ss ="0"+ss; - - if(ish>0){ - sm+=ish*60; - } - return sm +":"+ss; - } - - //return xx小时xx分钟xx秒 - public static String getTimeCnt(Long time,boolean isIncludeSec) - { - // int hour =Integer.valueOf(String.valueOf(time/1000/60/60)); -/* long hour = time/1000/60/60; - long minute = (time - hour*3600*1000)/1000/60; - long second = (time -hour*3600*1000 - minute*60*1000)/1000; - int ish =Integer.valueOf(String.valueOf(hour)); - int ism = Integer.valueOf(String.valueOf(minute)); - int iss = Integer.valueOf(String.valueOf(second)); - String sh = Integer.valueOf(String.valueOf(hour))>0 ? Integer.valueOf(String.valueOf(hour)).toString() :"00"; - String sm = Integer.valueOf(String.valueOf(minute))>0 ? Integer.valueOf(String.valueOf(minute)).toString() :"00"; - String ss = Integer.valueOf(String.valueOf(second))>0 ? Integer.valueOf(String.valueOf(second)).toString() :"00"; - if (10>ish && ish>0)sh ="0"+sh; - if (10>ism && ism>0)sm ="0"+sm; - if (10>iss && iss>0)ss ="0"+ss;*/ - /* - int ish = (int) (time/1000/60/60); - int ism = (int) ((time - ish*3600*1000)/1000/60); - int iss = (int) ((time -ish*3600*1000 - ism*60*1000)/1000); -// int ish =Integer.valueOf(String.valueOf(hour)); -// int ism = Integer.valueOf(String.valueOf(minute)); -// int iss = Integer.valueOf(String.valueOf(second)); - String sh = String.valueOf( ish>0 ?ish :"00") ; - String sm = String.valueOf(ism>0 ? ism :"00") ; - String ss = String.valueOf(iss>0 ?iss :"00" ) ; - if (10>ish && ish>0)sh ="0"+sh; - if (10>ism && ism>0)sm ="0"+sm; - if (10>iss && iss>0)ss ="0"+ss; - - if(!isIncludeSec) - return sh +":" + sm; - return sh +":" + sm +":"+ss; - */ - /* - Integer ss = 1000; - Integer mi = ss * 60; - Integer hh = mi * 60; - Integer dd = hh * 24; - - Long day = time / dd; - Long hour = (ms - day * dd) / hh; - Long minute = (ms - day * dd - hour * hh) / mi; - Long second = (ms - day * dd - hour * hh - minute * mi) / ss; - Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss; - */ - - Integer ss = 1000; - Integer mi = ss * 60; - Integer hh = mi * 60; - - Long hour = time / hh; - Long minute = (time - hour * hh) / mi; - Long second = (time - hour * hh - minute * mi) / ss; -// Long milliSecond = time - hour * hh - minute * mi - second * ss; - String sh = String.valueOf( hour>0 ?hour :"00") ; - String sm = String.valueOf(minute>0 ? minute :"00") ; - String sss = String.valueOf(second>0 ?second :"00" ) ; - - if (10>hour && hour>0) sh ="0"+hour; - if (10>minute && minute>0)sm ="0"+sm; - if (10>second && second>0)sss ="0"+sss; - - if(!isIncludeSec) - return sh +":" + sm; - return sh +":" + sm +":"+sss; - } - //return xx小时xx分钟xx秒 - public static String getTimeCnt4Read(Long time,boolean isIncludeSec) - { - int ish = (int) (time/1000/60/60); - int ism = (int) ((time - ish*3600*1000)/1000/60); - int iss = (int) ((time -ish*3600*1000 - ism*60*1000)/1000); -// int ish =Integer.valueOf(String.valueOf(hour)); -// int ism = Integer.valueOf(String.valueOf(minute)); -// int iss = Integer.valueOf(String.valueOf(second)); - String sh = String.valueOf( ish>0 ?ish+"小时" :"") ; - String sm = String.valueOf(ism>0 ? ism +"分" :"") ; - String ss = String.valueOf(iss>0 ?iss +"秒":"钟" ) ; -// if (10>ish && ish>0)sh ="0"+sh; - if (ish>0&& 10>ism && ism>0)sm ="0"+sm; - if (ism>0 && 10>iss && iss>0)ss ="0"+ss; - - if(!isIncludeSec) - return sh + sm +(ish==0?(ism>0 ? "钟" :""):""); - - return sh + sm +ss; - } - - public static int getDayscnt(Long time ) - { - int days =(int) (time/1000/60/60/24); - if(days>0){ - days++; - } - return days; - } - - public static long getUTC(String bdTime) { - Date dt = new Date(); // 2013-12-16 15:45:09 - //TODO check the hint To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates. - SimpleDateFormat sdf = new SimpleDateFormat(); - - try { - dt = sdf.parse(bdTime); - - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return dt.getTime(); - - } - private static double x_pi = 3.14159265358979324 * 3000.0 / 180.0; - -/* void bd_encrypt(double gg_lat, double gg_lon, double bd_lat, double bd_lon) - { - double x = gg_lon, y = gg_lat; - double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi); - double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi); - bd_lon = z * Math.cos(theta) + 0.0065; - bd_lat = z * Math.sin(theta) + 0.006; - } - - public static void bd_decrypt(double bd_lat, double bd_lon, double gg_lat, double gg_lon) - { - double x = bd_lon - 0.0065, y = bd_lat - 0.006; - double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi); - double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi); - gg_lon = z * Math.cos(theta); - gg_lat = z * Math.sin(theta); - } - */ - public static double getggLat(double bd_lat, double bd_lon) - { - double bdLat =getbdLat(bd_lat,bd_lon) ; -// x=2*x1-x2; y=2*y1-y2; - return bd_lat*2-bdLat; - - } - public static double getggLon(double bd_lat, double bd_lon) - { - double bdLon =getbdLon(bd_lat,bd_lon) ; -// x=2*x1-x2; y=2*y1-y2; - return bd_lon*2-bdLon; - - } - - /* public static double getggLon(double bd_lat, double bd_lon) - { - double x = bd_lon - 0.0065, y = bd_lat - 0.006; - double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi); - double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi); - return z * Math.cos(theta); - - } */ - - public static double getbdLat(double wg_lat, double wg_lon) - { - double x = getCJLon(wg_lat,wg_lon), y = getCJLat(wg_lat,wg_lon); - double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi); - double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi); - return z * Math.sin(theta) + 0.006; - } - - public static double getbdLon(double wg_lat, double wg_lon) - { - double x = getCJLon(wg_lat,wg_lon), y = getCJLat(wg_lat,wg_lon); - double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi); - double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi); - return z * Math.cos(theta) + 0.0065; - } - - - - - - /* - * get lat from WGS84 to GCJ-02 - */ - public static double getCJLat(double wgLat, double wgLon) - { - if (outOfChina(wgLat, wgLon)) - { - return wgLat; - } - double dLat = transformLat(wgLon - 105.0, wgLat - 35.0); - double dLon = transformLon(wgLon - 105.0, wgLat - 35.0); - double radLat = wgLat / 180.0 * pi; - double magic = Math.sin(radLat); - magic = 1 - ee * magic * magic; - double sqrtMagic = Math.sqrt(magic); - dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi); - dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi); - return wgLat + dLat; - } - - /* - * get lon from WGS84 to GCJ-02 - */ - public static double getCJLon(double wgLat, double wgLon) - { - if (outOfChina(wgLat, wgLon)) - { - return wgLat; - } - double dLat = transformLat(wgLon - 105.0, wgLat - 35.0); - double dLon = transformLon(wgLon - 105.0, wgLat - 35.0); - double radLat = wgLat / 180.0 * pi; - double magic = Math.sin(radLat); - magic = 1 - ee * magic * magic; - double sqrtMagic = Math.sqrt(magic); - dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi); - dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi); - return wgLon + dLon; - - } - - - - static double pi = 3.14159265358979324; - static double a = 6378245.0; - static double ee = 0.00669342162296594323; - - - /* public static void transform(double wgLat, double wgLon, double mgLat, double mgLon) - { - if (outOfChina(wgLat, wgLon)) - { - mgLat = wgLat; - mgLon = wgLon; - return; - } - double dLat = transformLat(wgLon - 105.0, wgLat - 35.0); - double dLon = transformLon(wgLon - 105.0, wgLat - 35.0); - double radLat = wgLat / 180.0 * pi; - double magic = Math.sin(radLat); - magic = 1 - ee * magic * magic; - double sqrtMagic = Math.sqrt(magic); - dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi); - dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi); - mgLat = wgLat + dLat; - mgLon = wgLon + dLon; - }*/ - - - static boolean outOfChina(double lat, double lon) - { - if (lon < 72.004 || lon > 137.8347) - return true; - if (lat < 0.8293 || lat > 55.8271) - return true; - return false; - } - - static double transformLat(double x, double y) - { - double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x)); - ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0; - ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0; - ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0; - return ret; - } - - static double transformLon(double x, double y) - { - double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x)); - ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0; - ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0; - ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0; - return ret; - } - - - public static String getDistanceRange(float range,float lat,float lon){ - - if(range>0){ - return getFormatedDistance(range); - }else if(lat>0 && lon>0) - return getFormatedDistance((float) getDistanceFromXtoY(lat,lon, QiYouConstant.PV_LAST_LAT, QiYouConstant.PV_LAST_LON)); - else return ""; - - } - - public static int get_updatedb_invterval(TrackType trackType) - { - int rt =0; - switch(trackType) - { - case BIKE: {rt = QiYouConstant.MAX_TIME_UPDATE_DB;break;} //TODO: read reference for types - case MOTOR: {rt = QiYouConstant.MAX_TIME_UPDATE_DB;break;} - case HIKE: {rt = QiYouConstant.MAX_TIME_UPDATE_DB;break;} - case FLY: {rt = QiYouConstant.MAX_TIME_UPDATE_DB;break;} - case DIVE: {rt = QiYouConstant.MAX_TIME_UPDATE_DB;break;} - case OTHER: {rt = QiYouConstant.MAX_TIME_UPDATE_DB;break;} - default:rt = QiYouConstant.MAX_TIME_UPDATE_DB; - } - - return rt; - } - - public static int get_updatedb_cachsize(TrackType trackType) - { - int rt =0; - switch(trackType) - { - case BIKE: {rt = QiYouConstant.MAX_WPS_UPDATE_DB;break;} //TODO: read reference for types - case MOTOR: {rt = QiYouConstant.MAX_WPS_UPDATE_DB;break;} - case HIKE: {rt = QiYouConstant.MAX_WPS_UPDATE_DB;break;} - case FLY: {rt = QiYouConstant.MAX_WPS_UPDATE_DB;break;} - case DIVE: {rt = QiYouConstant.MAX_WPS_UPDATE_DB;break;} - case OTHER: {rt = QiYouConstant.MAX_WPS_UPDATE_DB;break;} - default: rt = QiYouConstant.MAX_WPS_UPDATE_DB; - } - - return rt; - } - -/* public static int get_updatedb_wpsDistance(int trackType) - { - int rt =0; - switch(trackType) - { - case 0: {rt = QiYouConstant.MIN_WPS_DISTANCE_FACTOR;break;} //TODO: read reference for types - case 1: {rt = QiYouConstant.MIN_WPS_DISTANCE_FACTOR;break;} - case 2: {rt = QiYouConstant.MIN_WPS_DISTANCE_FACTOR;break;} - } - - return rt; - } - */ - public static int get_updatedb_wpsElesumcnt(TrackType trackType) - { - int rt =0; - switch(trackType) - { - case BIKE: {rt = QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT;break;} //TODO: read reference for types - case MOTOR: {rt = QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT;break;} - case HIKE: {rt = QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT;break;} - case FLY: {rt = QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT;break;} - case DIVE: {rt = QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT;break;} - case OTHER: {rt = QiYouConstant.MAX_WPS_EVERAGE_ELE_CNT;break;} - } - - return rt; - } - - public static float getDistance(Location loc1, Location loc2) - { - return (float) getDistanceFromXtoY(loc1.getLatitude(),loc1.getLongitude(),loc2.getLatitude(),loc2.getLongitude()); -// return (float) getDistance2(loc1,loc2); - } - - - public static double getDistanceFromXtoY(double lat_a, double lng_a, - double lat_b, double lng_b){ - - - if(lat_a<=0 || lat_b<=0 ||lng_a<=0 ||lng_b<=0)return 0; - - - double pk = 180 / 3.14169; - - double a1 = lat_a / pk; - double a2 = lng_a / pk; - double b1 = lat_b / pk; - double b2 = lng_b / pk; - - double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2); - double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2); - double t3 = Math.sin(a1) * Math.sin(b1); - double tt = Math.acos(t1 + t2 + t3); - - double rt = 6366000 * tt; - -// if(rt ==Double.NaN) { - if(Double.isNaN(rt)) { - - QLog.getLogger().dLog("com.qiyou.utils", "getDistanceFromXtoY,Distance is NaN. return value: "+ rt); - rt =0.0; - } - if(rt>0) - return rt; - else return 0; - - } - - - public static double getDistance2( Location currentLoc, Location lastLoc) - { - - double distance=0d; - if(currentLoc != null &&lastLoc!=null && currentLoc.getTime()>lastLoc.getTime()){ - -// double distanceTo = currentLoc.distanceTo(lastLoc); - - /* double getDistance =getDistance( currentLoc, lastLoc); - -// QLog.getLogger().dLog(dTAG," getDistance "+ getDistance ); -// QLog.getLogger().dLog(dTAG," getDistance - distanceTo "+ ( getDistance - currentLoc.distanceTo(lastLoc))); - - if(getDistance >0 && currentLoc.hasAccuracy() && lastLoc.hasAltitude()){ - double opposite =currentLoc.getAltitude() - lastLoc.getAltitude(); -// distance2 = (float) Math.atan(((double)opposite/distance)); - double gradient =Math.abs(opposite/getDistance*100); -// QLog.getLogger().dLog(dTAG," ele opposite "+String.format("%.2f", opposite)); -// QLog.getLogger().dLog(dTAG," location gradients "+String.format("%.2f", gradient)); - if(gradient<20){ - distance=Math.sqrt(Math.pow(opposite, 2)+Math.pow(getDistance,2)); - -// QLog.getLogger().dLog(dTAG," location distance before fix "+getDistance); -// QLog.getLogger().dLog(dTAG," location distance after fix "+distance); -// QLog.getLogger().dLog(dTAG," location distance delta is "+(distance-getDistance)); - } - else{ - distance=getDistance; - } - - - } */ -// distance2=distance3; - distance =getDistance( currentLoc, lastLoc); - } - return distance; - } - - public static double getDistance3( Location currentLoc, Location lastLoc) - { - - double distance=0d; - if(currentLoc != null &&lastLoc!=null && currentLoc.getTime()>lastLoc.getTime()){ - -// double distanceTo = currentLoc.distanceTo(lastLoc); - - double getDistance =getDistance( currentLoc, lastLoc); - -// QLog.getLogger().dLog(dTAG," getDistance "+ getDistance ); -// QLog.getLogger().dLog(dTAG," getDistance - distanceTo "+ ( getDistance - currentLoc.distanceTo(lastLoc))); - - if(getDistance >0 && currentLoc.hasAccuracy() && lastLoc.hasAltitude()){ - double opposite =currentLoc.getAltitude() - lastLoc.getAltitude(); -// distance2 = (float) Math.atan(((double)opposite/distance)); - double gradient =Math.abs(opposite/getDistance*100); -// QLog.getLogger().dLog(dTAG," ele opposite "+String.format("%.2f", opposite)); -// QLog.getLogger().dLog(dTAG," location gradients "+String.format("%.2f", gradient)); - if(gradient<20){ - distance=Math.sqrt(Math.pow(opposite, 2)+Math.pow(getDistance,2)); - -// QLog.getLogger().dLog(dTAG," location distance before fix "+getDistance); -// QLog.getLogger().dLog(dTAG," location distance after fix "+distance); -// QLog.getLogger().dLog(dTAG," location distance delta is "+(distance-getDistance)); - } - else{ - distance=getDistance; - } - - - } -// distance2=distance3; - } - return distance; - } - - /* public boolean isScreenOff(){ - PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); - - return !(pm.isScreenOn()); - } - - public boolean appNotOnTop(){ - ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); - List runningTaskInfos = manager.getRunningTasks(100); - - if(runningTaskInfos.size() > 0){ - - System.out.println("---------------包名-----------"+runningTaskInfos.get(0).topActivity.getPackageName()); - - //应用程序位于堆栈的顶层 - - if("com.chexiaodi.android.cxd".equals(runningTaskInfos.get(0).topActivity.getPackageName())){ - - return false; - - } - - } - - return true; - }*/ - - public static String sqliteEscape(String keyWord){ - keyWord = keyWord.replace("/", "//"); - keyWord = keyWord.replace("'", "''"); - keyWord = keyWord.replace("[", "/["); - keyWord = keyWord.replace("]", "/]"); - keyWord = keyWord.replace("%", "/%"); - keyWord = keyWord.replace("&","/&"); - keyWord = keyWord.replace("_", "/_"); - keyWord = keyWord.replace("(", "/("); - keyWord = keyWord.replace(")", "/)"); - return keyWord; - } - - public static void logStackTrace(Exception e,String TAG){ - - if(!QiYouConstant.LOG_LEVEL_DEBUG && !QiYouConstant.LOG_LEVEL_ERROR) return; - - StackTraceElement[] ste= e.getStackTrace(); - int stelength=ste.length; - Log.e(TAG,e.toString()); - Log.e(dTAG,e.toString()); - String err_msg=""; -// String mDestXmlFilename = QiYouConstant.SD_PATH + "error" +Calendar.YEAR+ Calendar.DATE + Calendar.DAY_OF_MONTH +".log"; - String mDestXmlFilename = QiYouConstant.SD_PATH + "error" + - new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE) .format(Calendar.getInstance().getTime()) - +".log"; - File myFile = new File(mDestXmlFilename); - try { - if(!myFile.exists()){ - myFile.createNewFile(); - } - FileOutputStream fOut = new FileOutputStream(myFile,true); -// BufferedOutputStream bos = new BufferedOutputStream(fOut); - fOut.write((Utils.getFormatedTime(System.currentTimeMillis())+"\n").getBytes()); - - fOut.write((e.toString()+"\n").getBytes()); - - for(int i=0;i1000) - return String.format("%.1f",dist /1000.0 )+"公里" ;// + "% %.2f 公里后%转", tb.getRoadWps().size()+1,wp.getWb().getBearDist() /1000.0, turn); - else - return String.format("%.0f",dist) +"米" ; - } - - - public static String getWeather(){ -// String weather=" 苏州天气不错,晴转多云,19摄氏度,空气质量一级.\n"; - String weather=""; - return weather; - } - - /* public static String getDirection(float bearing){ - -// float bear = bearing/30; - int dir =(int)roundF(bearing/30,2); - dir=dir==0?12:dir; - return String.format("%s %s 点钟方向 ",getDirection(bearing), dir ); - - - } */ - - public static String getBearMsg(float bearing,boolean fineData){ - -// float bear = bearing/30; - -// return String.format("%.0f", bearing/30 ); - if(bearing<0)bearing+=360; - bearing =Utils.roundF(bearing,1); - String rt =""; - String dir=""; - final String NORTH="北"; - final String SOUTH="南"; - final String WEST="西"; - final String EAST="东"; - final String Pian ="偏"; - final String Zheng ="正"; - - final int iN=0; - final int iE=3; - final int iS=6; - final int iW=9; - - final float cha=1.5f; - - float direction = roundF(bearing/30,2); - float tf=direction+0.5f; - - int idir =(int)(roundF(tf ,0)); - if(idir>=12)idir=0; - switch(idir){ - case iN:{ - rt=Zheng +NORTH; - return rt; - } - case iE:{ - rt=Zheng +EAST; - return rt; - } - case iW:{ - rt=Zheng +WEST; - return rt; - } - case iS:{ - rt=Zheng +SOUTH; - return rt; - } - } - - tf=direction-0.5f; -// int idir =Integer.valueOf(String.format("%.0f",bearing/30)); - idir =(int)(roundF(tf ,0)); - - switch(idir){ - case iN:{ - rt=Zheng +NORTH; - return rt; - } - case iE:{ - rt=Zheng +EAST; - return rt; - } - case iW:{ - rt=Zheng +WEST; - return rt; - } - case iS:{ - rt=Zheng +SOUTH; - return rt; - } - } - - tf=direction; -// int idir =Integer.valueOf(String.format("%.0f",bearing/30)); - idir =(int)(roundF(tf ,0)); - - switch(idir){ - case iN:{ - rt=Zheng +NORTH; - return rt; - } - case iE:{ - rt=Zheng +EAST; - return rt; - } - case iW:{ - rt=Zheng +WEST; - return rt; - } - case iS:{ - rt=Zheng +SOUTH; - return rt; - } - } - - - float diff=0; - if(direction<=12 && direction>12-cha){ - dir =NORTH; - if(direction<=cha) - dir=dir+Pian+EAST; - else - dir=dir+Pian+WEST; - diff=(direction-12)*30; - } - else - if(direction<=iN+cha && direction>iN){ - dir =NORTH; - if(direction<=cha) - dir=dir+Pian+EAST; - else - dir=dir+Pian+WEST; - diff=(direction-iN)*30; - } - else - if(direction<=iE+cha && direction>iE-cha){ - dir =EAST; - if(!fineData && direction ==iE+cha) - return dir+SOUTH; - else - if(direction>iE) - dir=dir+Pian+SOUTH; - else - dir=dir+Pian+NORTH; - diff=(direction-iE)*30; - }else - if(direction<=iS+cha && direction>iS-cha){ - dir =SOUTH; - - if(!fineData && direction ==iS+cha) - return WEST+SOUTH; - - if(direction>iS) - dir=dir+Pian+WEST; - else - dir=dir+Pian+EAST; - diff=(direction-iS)*30; - }else - if(direction<=iW+cha && direction>iW-cha){ - dir =WEST; - if(!fineData && direction ==iW+cha) - return WEST+NORTH; - - if(direction>iW) - dir=dir+Pian+NORTH; - else - dir=dir+Pian+SOUTH; - diff=(direction-iW)*30; - } - if(TextUtils.isEmpty(dir)){ -// Utils.logStackTrace(new Exception("NO Direction Found:"+bearing),dTAG); - QLog.getLogger().d(String.valueOf(bearing), dTAG); - } - if(fineData) - return String.format("%s%.0f度", dir,Math.abs(diff)); - else - return String.format("%s", dir); - } - - public static String getSdRootPath(Context context){ - if(!Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)){ - return context.getCacheDir().getAbsolutePath(); -// Log.e(dTAG, "Utils: "+ "SD卡不可用. sd status: " +Environment.getExternalStorageState()); -// logStackTrace(new Exception("SD卡不可用. sd status: " +Environment.getExternalStorageState()),TAG); -// if(QiYouConstant.DEVELOPER_MODE) -// SDPATH="/qiyouapp"; - //return; - }else - return Environment.getExternalStorageDirectory().toString(); - } - - - public static void initialSDPaths(){ - QiYouConstant.MEDIA_PATH =QiYouConstant.SD_PATH+"medias/"; - - QiYouConstant.FOOTMARK_PATH =QiYouConstant.SD_PATH+"footmarks/"; - QiYouConstant.PHOTO_CACHE_PATH =QiYouConstant.SD_PATH+"photoCache/"; - QiYouConstant.EXP_PATH =QiYouConstant.SD_PATH+"exp/"; - QiYouConstant.IMP_PATH =QiYouConstant.SD_PATH+"imp/"; - QiYouConstant.CONTENT_SD_DIR=QiYouConstant.SD_PATH+"dbcontent/"; - - QiYouConstant.GPX_CACHE_PATH= QiYouConstant.SD_PATH + "gpxcache/"; - QiYouConstant.ACT_CACHE_PATH= QiYouConstant.SD_PATH + "actcache/"; - } - - public static void initSdPath(Context context){ - /* String SDPATH=""; - if(!Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)){ - SDPATH=context.getCacheDir().getAbsolutePath(); -// Log.e(dTAG, "Utils: "+ "SD卡不可用. sd status: " +Environment.getExternalStorageState()); -// logStackTrace(new Exception("SD卡不可用. sd status: " +Environment.getExternalStorageState()),TAG); -// if(QiYouConstant.DEVELOPER_MODE) -// SDPATH="/qiyouapp"; - //return; - }else - SDPATH=Environment.getExternalStorageDirectory().toString(); */ - String SDPATH=getSdRootPath(context); - SDPATH=SDPATH+"/"+QiYouConstant.APP_SD_DIR +"/"; - QLog.getLogger().d(dTAG, "Utils: "+ "App Path on SD: "+ SDPATH); -// 判断SD卡上的文件夹是否存在:通过File对象的exists()方法。 - File file=new File(SDPATH); - if(!file.exists()){ //在SD卡上创建目录: - file.mkdir(); - QLog.getLogger().d(dTAG, "Utils: "+ "App Path created on SD as "+ SDPATH); - - } - QiYouConstant.SD_PATH = SDPATH; - initialSDPaths(); - file=new File(QiYouConstant.IMP_PATH); - if(!file.exists()){ //在SD卡上创建目录: - file.mkdir(); - QLog.getLogger().d(dTAG, "Utils: "+ "IMP_PATH created on SD as "+ QiYouConstant.IMP_PATH); - - } - - if(QiYouConstant.DEVELOPER_MODE){ - QiYouConstant.CONTENT_SD_DIR=QiYouConstant.CONTENT_SD_DIR.substring(0,QiYouConstant.CONTENT_SD_DIR.length()-1)+"Dev"+File.separator; - file=new File(QiYouConstant.CONTENT_SD_DIR); - if(!file.exists()){ //在SD卡上创建目录: - file.mkdir(); - - QLog.getLogger().d(dTAG, "Utils: "+ "CONTENT_SD_DIR created on SD as "+ QiYouConstant.CONTENT_SD_DIR); - } - }else{ - - /* QiYouConstant.CONTENT_SD_DIR =QiYouConstant.CONTENT_SD_DIR.substring(0,QiYouConstant.CONTENT_SD_DIR.length()-1)+"Dev"+File.separator; - //temp codes to migrate dbcontent from sd to app data - file=new File(QiYouConstant.CONTENT_SD_DIR); - if(file.exists()){ - try { - FileUtil.copyDirectiory(QiYouConstant.CONTENT_SD_DIR, context.getDir("dbcontent", 0).getAbsolutePath()); - FileUtil.del(QiYouConstant.CONTENT_SD_DIR); - FileUtil.del(QiYouConstant.CONTENT_SD_DIR); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - //----> - - // file=new File(QiYouConstant.CONTENT_SD_DIR); - String DATABASE_NAME = "tracks.db"; - file = new File(QiYouConstant.SD_PATH + DATABASE_NAME);// 创建文件 - if(file.exists()){ - // FileUtil.copyDirectiory(QiYouConstant.CONTENT_SD_DIR, context.getDir("dbcontent", 0).getAbsolutePath()); - // FileUtil.del(QiYouConstant.CONTENT_SD_DIR); - // FileUtil.del(QiYouConstant.SD_PATH + DATABASE_NAME); - file.delete(); - } - */ - - //below is to be kept - QiYouConstant.CONTENT_SD_DIR =context.getDir("dbcontent", 0).getAbsolutePath(); - QiYouConstant.CONTENT_SD_DIR+=File.separator; - - } - - QiYouConstant.BEAR_TEXT =QiYouConstant.CONTENT_SD_DIR+ QiYouConstant.BEAR_TEXT; - //create beartext file - file=new File(QiYouConstant.BEAR_TEXT); -// file=new File(QiYouConstant.CONTENT_SD_DIR+"/a/test.txt"); - if(!file.exists()){ - try { - file.createNewFile(); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - if(QiYouConstant.DEVELOPER_MODE){ - QiYouConstant.STAT_TEXT =QiYouConstant.SD_PATH+ QiYouConstant.STAT_TEXT; - }else { - QiYouConstant.STAT_TEXT =QiYouConstant.CONTENT_SD_DIR+ QiYouConstant.STAT_TEXT; - } - //create STAT file - file=new File(QiYouConstant.STAT_TEXT); -// file=new File(QiYouConstant.CONTENT_SD_DIR+"/a/test.txt"); - if(!file.exists()){ - try { - file.createNewFile(); - } catch (IOException e) { - // TODO Auto-generated catch block - Utils.logStackTrace(e, TAG); - } - } - - } - - public static String getContentPah(int TrackId){ - if(TrackId<=0) - return ""; - return QiYouConstant.CONTENT_SD_DIR + TrackId+".txt"; - } - - public static String getBearContentPah(int TrackId){ - if(TrackId<=0) - return ""; - return QiYouConstant.CONTENT_SD_DIR + TrackId+"b.txt"; - } - - - public static boolean isContentExist(String filePath){ - if(TextUtils.isEmpty(filePath)) - return false; - File file = new File(filePath); - return file.exists(); - - } - - public static String readSDFile(String fileName) throws IOException { - - File file = new File(fileName); - - if(!file.exists()) return null; - - FileInputStream fis = new FileInputStream(file); - - int length = fis.available(); - - byte [] buffer = new byte[length]; - fis.read(buffer); - - String res = EncodingUtils.getString(buffer, "UTF-8"); - - fis.close(); - return res; - } - - //写文件 - public static void writeSDFile(String fileName, String write_str) throws IOException{ - - /* File file = new File(fileName); - - FileOutputStream fos = new FileOutputStream(file); - - - byte [] bytes = write_str.getBytes(); - - fos.write(bytes); - - - fos.close(); */ - writeSDFile(fileName, write_str, false); - } - - - - //写文件 - public static void writeSDFile(String fileName, String write_str,boolean isAppend) throws IOException{ - - if(TextUtils.isEmpty(write_str))return; - File file = new File(fileName); - - FileOutputStream fos = new FileOutputStream(file,isAppend); -// FileOutputStream fos1 = new FileOutputStream(file, isAppend) ; - - byte [] bytes = write_str.getBytes(); - - fos.write(bytes); - - - fos.close(); - } - - - public static String getShortString(String str,int lng){ -// String value =cursor.getString(6); - str =TextUtils.isEmpty(str)?str:str.length()>lng?str.substring(0,lng)+"...":str; - str =TextUtils.isEmpty(str)?str:" "+str.replaceAll( "\\s", "" ); - -// if (str!=null) { -//// Pattern p = Pattern.compile("\\s*|\t|\r|\n"); -//// Matcher m = p.matcher(str); -//// str = m.replaceAll(""); -// str.replaceAll( "\\s", "" ); -// } - return str; - } - - - - - - - public static boolean isLocOfGPS(Location loc){ - if(loc==null)return false; - return loc.getProvider().equalsIgnoreCase(LocationManager.GPS_PROVIDER); - } - public static boolean isLocOfForceUpdate(Location loc){ - if(loc==null)return false; - return loc.getProvider().equalsIgnoreCase(QiYouConstant.LOCATION_FORCE_UPDATE); - } - public static boolean isLocOfMonitor(Location loc){ - if(loc==null)return false; - return loc.getProvider().equalsIgnoreCase(QiYouConstant.LOCATION_MONITOR); - } - - public static boolean isLocOfBD(Location loc){ - if(loc==null)return false; - return loc.getProvider().equalsIgnoreCase(QiYouConstant.LOCATION_BD_LOC); - } - public static boolean isLocOfRD(Location loc){ - if(loc==null)return false; - return loc.getProvider().equalsIgnoreCase(QiYouConstant.LOCATION_RD_LOC); - } - - public static boolean canUpdateOffmap(Context context){ - - getlastGeoRequestTime(context); - - QLog.getLogger().d(dTAG,TAG+" "+ " System.currentTimeMillis()- QiYouConstant.LAST_OFFMAP_UPDATE : " + ( System.currentTimeMillis()- QiYouConstant.LAST_OFFMAP_UPDATE )); - QLog.getLogger().d(dTAG,TAG+" "+ " QiYouConstant.OFFMAP_UPDATE_INTERVAL*1000*60 : " + ( QiYouConstant.OFFMAP_UPDATE_INTERVAL*1000*60)); - - QLog.getLogger().d(dTAG,TAG+" "+ " QiYouConstant.CAN_OFFMAP_UPDATE: " + QiYouConstant.CAN_OFFMAP_UPDATE); - return QiYouConstant.CAN_OFFMAP_UPDATE; - } - public static boolean canUpdateGEOfootmark(Context context){ - - if(QiYouConstant.IS_PROCESSING_GEO_FOOTMARK) return false; - - getlastGeoRequestTime(context); - - QLog.getLogger().d(dTAG,TAG+" "+ " System.currentTimeMillis()- QiYouConstant.LAST_GEO_UPDATE : " + ( System.currentTimeMillis()- QiYouConstant.LAST_GEO_UPDATE )); - QLog.getLogger().d(dTAG,TAG+" "+ " QiYouConstant.GEO_UPDATE_INTERVAL*1000*60 : " + ( QiYouConstant.GEO_UPDATE_INTERVAL*1000*60)); - - QLog.getLogger().d(dTAG,TAG+" "+ " QiYouConstant.CAN_GEO_UPDATE: " + QiYouConstant.CAN_GEO_UPDATE); - return QiYouConstant.CAN_GEO_UPDATE; - } - public static void getlastGeoRequestTime(Context context){ - - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); - - QiYouConstant.LAST_OFFMAP_UPDATE =settings.getLong(QiYouConstant.PK_LONG_LAST_OFFMAP_UPDATE, 0); - QiYouConstant.CAN_OFFMAP_UPDATE = System.currentTimeMillis()- QiYouConstant.LAST_OFFMAP_UPDATE > QiYouConstant.OFFMAP_UPDATE_INTERVAL*1000*60; - - QiYouConstant.LAST_GEO_UPDATE =settings.getLong(QiYouConstant.PK_LONG_LAST_GEO_UPDATE, 0); - QiYouConstant.CAN_GEO_UPDATE = System.currentTimeMillis()- QiYouConstant.LAST_GEO_UPDATE > QiYouConstant.GEO_UPDATE_INTERVAL*1000*60; - -// QLog.getLogger().d(dTAG,TAG+" "+ " #@#$!#%#$%@###last time offMap requested: " + Utils.getFormatedTime(QiYouConstant.LAST_GEO_UPDATE) +", past time:" + -// Utils.getTimeCnt(System.currentTimeMillis()-QiYouConstant.LAST_GEO_UPDATE,true) + -// " ,times since last geo update:" + QiYouConstant.TIME_SINCE_LAST_GEO_UPDATE +", " -// + (System.currentTimeMillis()-QiYouConstant.LAST_GEO_UPDATE)+","+System.currentTimeMillis()); - - /*QLog.getLogger().d(dTAG,TAG+" "+ " #@#$!#%#$%@###last time offMap requested: " + Utils.getFormatedTime(QiYouConstant.LAST_OFFMAP_UPDATE) +", past time:" + - Utils.getTimeCnt(System.currentTimeMillis()-QiYouConstant.LAST_OFFMAP_UPDATE,true) + - " ,times since last offmap update:" + (System.currentTimeMillis()-QiYouConstant.LAST_OFFMAP_UPDATE) ); - - QLog.getLogger().d(dTAG,TAG+" "+ " #@#$!#%#$%@###last time geo requested: " + Utils.getFormatedTime(QiYouConstant.LAST_GEO_UPDATE) +", past time:" + - Utils.getTimeCnt(System.currentTimeMillis()-QiYouConstant.LAST_GEO_UPDATE,true) + - " ,times since last geo update:" + (System.currentTimeMillis()-QiYouConstant.LAST_GEO_UPDATE) ); */ - - } -public static boolean canProcessWifiConn(Context context){ - - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); - - QiYouConstant.LAST_WIFI_TIME =settings.getLong(QiYouConstant.PK_LONG_LAST_WIFI_TIME, 0); - QiYouConstant.CAN_WIFI_PROCESS = System.currentTimeMillis()- QiYouConstant.LAST_WIFI_TIME > QiYouConstant.WIFI_CONNECT_CHANGE_INTERVAL*1000*60; - - if(QiYouConstant.CAN_WIFI_PROCESS ){ - Editor edit =settings.edit(); - edit.putLong(QiYouConstant.PK_LONG_LAST_WIFI_TIME, System.currentTimeMillis()); - edit.commit(); - } - - QLog.getLogger().d(dTAG,TAG+" "+ " #@#$!#%#$%@### can Wifi connection process? " +QiYouConstant.CAN_WIFI_PROCESS); - - return QiYouConstant.CAN_WIFI_PROCESS; - - - } - - public static long getMondayOfTheWeek(){ - return getFirstDay(true); - } - public static long getFirstDayOfTheMonth(){ - return getFirstDay(false); - } - - static long getFirstDay(boolean isWeek){ - Calendar cal =Calendar.getInstance(); - int year =cal.get(Calendar.YEAR); - int month =cal.get(Calendar.MONTH); - int day=1; - if(isWeek)day = cal.get(Calendar.DAY_OF_MONTH) - cal.get(Calendar.DAY_OF_WEEK) +1 ; //Get date of Monday - cal.clear(); - cal.set(year, month, day); -// startDate = endDate - cal.get(Calendar.MONDAY)*missPerday; - return cal.getTimeInMillis(); - - } - - public static boolean canUpdateUI(Context context){ -// SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); - return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(QiYouConstant.PK_BL_CAN_UPDATE_UI, false); - } - - public static int daysBetween(long start,long end){ - return (int)(end -start)/(24*3600*1000); -// Date startDt = new Date(start); -// Date endDt = new Date(end); -// return endDt.compareTo(startDt); - } - -public static boolean isGpsEnabled(Context context) { - LocationManager locationManager =((LocationManager)context.getSystemService(Context.LOCATION_SERVICE)); - return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER); - -} - - -public static boolean isGpsPermited(Context context){ - PackageManager pkm = context.getPackageManager(); - boolean has_permission = (PackageManager.PERMISSION_GRANTED -// == pkm.checkPermission("android.permission.ACCESS_GPS", "com.qiyou.mb.android"));android.permission.WRITE_EXTERNAL_STORAGE - == pkm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "com.qiyou.mb.android"));//android.permission.WRITE_EXTERNAL_STORAGE - - return has_permission; -} - - -/* -@SuppressLint("NewApi") -public static void setTabhostStyle(TabHost tabhost,int height,int width){ - TabWidget tabWidget = tabhost.getTabWidget(); - for (int i =0; i < tabWidget.getChildCount(); i++) { - tabWidget.getChildAt(i).getLayoutParams().height = height; - tabWidget.getChildAt(i).getLayoutParams().width = width; - TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title); - // tv.setTextSize(15); - tv.setTextColor( getResources().getColorStateList(android.R.color.darker_gray)); - } - tabhost.getTabWidget().setStripEnabled(false); -}*/ - - -public static float getMets(TrackType trackType,float speed){ - switch(trackType) - { - case BIKE: { - if(speed>28) - return 11.94f; - if(speed>27) - return 11.42f; - if(speed>26) - return 10.9f; - if(speed>25) - return 10.42f; - if(speed>24) - return 9.9f; - if(speed>23) - return 9.28f; - if(speed>22) - return 8.6f; - if(speed>21) - return 8; - if(speed >20) - return 7.5f; - if(speed >19) - return 6.8f; - if(speed >18) - return 6.2f; - if(speed >16) - return 6; - return 4; - } //TODO: read reference for types - case MOTOR: {return 0;} - case HIKE: { - if(speed >20) - return 25; - if(speed >16) - return 20; - if(speed >12) - return 15; - if(speed >8) - return 10; - if(speed >5.5f) - return 5.8f; - return 2; - } - case FLY: { - - if(speed >20) - return 25; - if(speed >16) - return 20; - if(speed >12) - return 15; - if(speed >8) - return 10; - if(speed >5.5f) - return 5.8f; - return 4; - - } - - case DIVE: { - if(speed >20) - return 25; - if(speed >16) - return 20; - if(speed >12) - return 15; - if(speed >8) - return 10; - if(speed >5.5f) - return 5.8f; - return 2; - } - case OTHER: {return 0;} - case GPX:{ - if(speed>28) - return 11.94f; - if(speed>27) - return 11.42f; - if(speed>26) - return 10.9f; - if(speed>25) - return 10.42f; - if(speed>24) - return 9.9f; - if(speed>23) - return 9.28f; - if(speed>22) - return 8.6f; - if(speed>21) - return 8; - if(speed >20) - return 7.5f; - if(speed >19) - return 6.8f; - if(speed >18) - return 6.2f; - if(speed >16) - return 6; - return 4; - } - default:return 0 ; - } - - - } - -public static void hideSoftKeyboard(Activity activity) { - try{ - InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); - inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); - }catch(Exception e){ - logStackTrace(e, TAG); - } -} - - -public static double getCalories(TrackType type,double speed,long sportTime,float upDist){ - - float mets =Utils.getMets(type,(float)speed); - float weight=QiYouConstant.PV_USER_WEIGHT; - float hours =sportTime/(3600f*1000f); - float calories =mets*weight*(hours); - /*float eUp =tb.getEsumUp() ; - float mgh =0; - if(calories>0 && eUp>0){ - mgh =weight*9.8f*eUp; - mgh =mgh/4.184f; - - }*/ -// calories +=mgh; - calories =calories>0?calories:0; - - //客服重力做功 - float w =mets>0?QiYouConstant.PV_USER_WEIGHT*9.8f*upDist:0; - - //1焦耳(J)=0.2389卡(cal) - //w*0.2389f/1000; 为大卡? - calories+=w*0.2389f/1000; - - calories =calories>0?calories:0; - return calories; -} - - -public static GPX pareseGpx(InputStream in){ - - - GPXParser gp =new GPXParser(); - try { - return gp.parseGPX(in); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SAXException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; -} - - -public static GPX pareseGpx(String gpxfileName){ - - - QLog.getLogger().d(dTAG, " begin to parese GPX file "+gpxfileName); - - File file = new File(gpxfileName); - - if(!file.exists()) return null; - - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - } catch (FileNotFoundException e) { - - // e.printStackTrace(); - Utils.logStackTrace(e, TAG); - - return null; - } catch(Exception er){ - // QLog.getLogger().d(dTAG, " 读文件错误"); - Utils.logStackTrace(er, TAG); - return null; - } - // InputStream in = new BufferedInputStream(fis); - // GPX gpx ; - // gpx= Utils.pareseGpx(in); - return pareseGpx(new BufferedInputStream(fis)); - // activity.app.setGpxTrack(new Track(gpx)); - // activity.app.getGpxTrack().getTrackBean().setSrc(gpxfileName); - // Intent serviceIntent = new Intent(activity, TrackDbServiceBackground.class); - // serviceIntent.putExtra(QiYouConstant.NEW_GPX_TRACK,""); - // activity.startService(serviceIntent); - - } - -@TargetApi(Build.VERSION_CODES.KITKAT) -public static String getPath(final Context context, final Uri uri) { - - final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; - - // DocumentProvider - if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { - // ExternalStorageProvider - if (isExternalStorageDocument(uri)) { - final String docId = DocumentsContract.getDocumentId(uri); - final String[] split = docId.split(":"); - final String type = split[0]; - - if ("primary".equalsIgnoreCase(type)) { - return Environment.getExternalStorageDirectory() + "/" + split[1]; - } - - // TODO handle non-primary volumes - } - // DownloadsProvider - else if (isDownloadsDocument(uri)) { - - final String id = DocumentsContract.getDocumentId(uri); - final Uri contentUri = ContentUris.withAppendedId( - Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); - - return getDataColumn(context, contentUri, null, null); - } - // MediaProvider - else if (isMediaDocument(uri)) { - final String docId = DocumentsContract.getDocumentId(uri); - final String[] split = docId.split(":"); - final String type = split[0]; - - Uri contentUri = null; - if ("image".equals(type)) { - contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; - } else if ("video".equals(type)) { - contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; - } else if ("audio".equals(type)) { - contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; - } - - final String selection = "_id=?"; - final String[] selectionArgs = new String[] { - split[1] - }; - - return getDataColumn(context, contentUri, selection, selectionArgs); - } - } - // MediaStore (and general) - else if ("content".equalsIgnoreCase(uri.getScheme())) { - - // Return the remote address - if (isGooglePhotosUri(uri)) - return uri.getLastPathSegment(); - - return getDataColumn(context, uri, null, null); - } - // File - else if ("file".equalsIgnoreCase(uri.getScheme())) { - return uri.getPath(); - } - - return null; -} - -/** - * Get the value of the data column for this Uri. This is useful for - * MediaStore Uris, and other file-based ContentProviders. - * - * @param context The context. - * @param uri The Uri to query. - * @param selection (Optional) Filter used in the query. - * @param selectionArgs (Optional) Selection arguments used in the query. - * @return The value of the _data column, which is typically a file path. - */ -public static String getDataColumn(Context context, Uri uri, String selection, - String[] selectionArgs) { - - Cursor cursor = null; - final String column = "_data"; - final String[] projection = { - column - }; - - try { - cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, - null); - if (cursor != null && cursor.moveToFirst()) { - final int index = cursor.getColumnIndexOrThrow(column); - return cursor.getString(index); - } - } finally { - if (cursor != null) - cursor.close(); - } - return null; -} - - -/** - * @param uri The Uri to check. - * @return Whether the Uri authority is ExternalStorageProvider. - */ -public static boolean isExternalStorageDocument(Uri uri) { - return "com.android.externalstorage.documents".equals(uri.getAuthority()); -} - -/** - * @param uri The Uri to check. - * @return Whether the Uri authority is DownloadsProvider. - */ -public static boolean isDownloadsDocument(Uri uri) { - return "com.android.providers.downloads.documents".equals(uri.getAuthority()); -} - -/** - * @param uri The Uri to check. - * @return Whether the Uri authority is MediaProvider. - */ -public static boolean isMediaDocument(Uri uri) { - return "com.android.providers.media.documents".equals(uri.getAuthority()); -} - -/** - * @param uri The Uri to check. - * @return Whether the Uri authority is Google Photos. - */ -public static boolean isGooglePhotosUri(Uri uri) { - return "com.google.android.apps.photos.content".equals(uri.getAuthority()); -} - - -/*public static LatLng getGeoPoint(double lat ,double lon){ -// double mLat = Utils.getbdLat(lat,lon); -// double mLon = Utils.getbdLon(lat, lon); -// int lat = (int) (mLat*1E6); -// int lon = (int) (mLon*1E6); -// int lat = (int) (tb.getStartWp().getWb().getLatitude()*1E6); -// int lon = (int) (tb.getStartWp().getWb().getLongitude()*1E6); - return new LatLng((int)(getbdLat(lat,lon)*1E6), (int)(getbdLon(lat,lon)*1E6)); -}*/ - -public static LatLng getLatLng(double lat ,double lon){ - - return new LatLng(getbdLat(lat,lon), getbdLon(lat,lon)); -} - -// 判断手机中是否安装了讯飞语音+ -public static boolean checkSpeechServiceInstall(Context context){ - return true; - /* - String packageName = "com.iflytek.speechcloud"; - List packages = context.getPackageManager().getInstalledPackages(0); - for(int i = 0; i < packages.size(); i++){ - PackageInfo packageInfo = packages.get(i); - if(packageInfo.packageName.equals(packageName)){ - return true; - }else{ - continue; - } - } - return false; - */ -} - - -/*public static String buildPathPoints(CopyOnWriteArrayList wps,Track track,boolean is4Baidu,int size)throws NullPointerException{ -*/ -public static String buildPathPoints( ArrayList wps,Track track,boolean is4Baidu,int size)throws NullPointerException{ - - - - if(wps.size()<2)return ""; - - Waypoint_bean wb; -// Waypoint_bean lastWb = null; - Waypoint_bean lastWb4map = null; -// final int MAXLATLNGS=50-3; -// float trackDist =track.getLastWp().getWb().getSumDist(); - - Waypoint_bean startwp =track.getStartWp()!=null?track.getStartWp().getWb():wps.get(0); - Waypoint_bean endwp =track.getLastWp()!=null?track.getLastWp().getWb():wps.get(wps.size()-1); - Waypoint_bean maxwp =track.getMaxDistWp()!=null?track.getMaxDistWp().getWb():wps.get(wps.size()-1); - - float trackDist =endwp.getSumDist(); - float stepValue =wps.size()>size &&trackDist>0 ?trackDist/size:0; - String pathPoints=""; - float skipDist=0; -// float skiptDist=0; -// QLog.getLogger().d(dTAG, TAG+" wps.size() is " + wps.size() +"----------------------------"); -// QLog.getLogger().d(dTAG, TAG+" MAXLATLNGS is " + MAXLATLNGS ); -// QLog.getLogger().d(dTAG, TAG+" trackDist/MAXLATLNGS " + trackDist/MAXLATLNGS ); -// -// QLog.getLogger().d(dTAG, TAG+" stepValue is " + stepValue); - - for(int i=0;ilastWb4map.getTime()) -// QLog.getLogger().d(dTAG, TAG+" No.i,lastwb.gettime():"+i+"," + Utils.getFormatedTime(lastWb4map.getTime())); -// QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()" + (wb.getSumDist()-lastWb.getSumDist())); -// QLog.getLogger().d(dTAG, TAG+" skipDist" + skipDist); -// QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()+skipDist" + (wb.getSumDist()-lastWb.getSumDist()+skipDist)); - float f =wb.getSumDist()-lastWb4map.getSumDist()+skipDist; -// QLog.getLogger().d(dTAG, TAG+" current dist " + f +", stepvalue is "+ stepValue +" dist >stepvalue?"+(f>=stepValue)); - if(TextUtils.isEmpty(pathPoints) - ||wps.size()<=size - ||f>=stepValue - ||wb.getTime()==startwp.getTime() - ||wb.getTime()==endwp.getTime() - ||wb.getTime()==maxwp.getTime()) - /*||wb.getTime()==track.getStartWp().getWb().getTime() - ||wb.getTime()==track.getLastWp().getWb().getTime() - ||wb.getTime()==track.getMaxDistWp().getWb().getTime()) */{ - - if(is4Baidu) - pathPoints=pathPoints+ getbdLon(wb.getLatitude(), wb.getLongitude())+","+ getbdLat(wb.getLatitude(), wb.getLongitude())+";"; - else - pathPoints=pathPoints+ wb.getLatitude() +","+ wb.getLongitude() +"|"; - - skipDist=0; - } - else - skipDist +=wb.getSumDist()-lastWb4map.getSumDist(); - - lastWb4map =wb; - -// lastWb=wb; -// if(wb.getTime()0?pathPoints.substring(0,pathPoints.length()-1):""; - } - - -public static ArrayList zipPathPoints( Track_bean track,int targetSizePerKm)throws NullPointerException{ - - QLog.getLogger().d(dTAG, "zip wps, target size is "+ targetSizePerKm + ",current size is "+ track.getTrkseg().size() ); - -// if ( track.getDistance() < 1000 ) { -// return track.getTrkseg(); -// } -// -// int targetSizePerKm = 10 ; // per km 10 wps - double trackSizePerKm = track.getDistance() < 1000 ? track.getTrkseg().size() : track.getTrkseg().size()/(track.getDistance()/1000.0); - - if(trackSizePerKm <= targetSizePerKm ){ - - return track.getTrkseg(); - } - - int targetSize = (int) (track.getDistance()/1000.0 * targetSizePerKm) ; - - - if(track.getTrkseg().size() < targetSize ){ - - return track.getTrkseg(); - } - - ArrayList wps = track.getTrkseg(); - ArrayList returnWps = new ArrayList() ; - Waypoint_bean wb; -// Waypoint_bean lastWb = null; - Waypoint_bean lastWb4map = null; -// final int MAXLATLNGS=50-3; -// float trackDist =track.getLastWp().getWb().getSumDist(); - - Waypoint_bean startwp =track.getStartWp()!=null?track.getStartWp().getWb():wps.get(0); - Waypoint_bean endwp =track.getLastWp()!=null?track.getLastWp().getWb():wps.get(wps.size()-1); - Waypoint_bean maxwp =track.getMaxDistWp()!=null?track.getMaxDistWp().getWb():wps.get(wps.size()-1); - - float trackDist =endwp.getSumDist(); - float stepValue =wps.size()>targetSize &&trackDist>0 ?trackDist/targetSize:0; -// String pathPoints=""; - float skipDist=0; -// float skiptDist=0; -// QLog.getLogger().d(dTAG, TAG+" wps.size() is " + wps.size() +"----------------------------"); -// QLog.getLogger().d(dTAG, TAG+" MAXLATLNGS is " + MAXLATLNGS ); -// QLog.getLogger().d(dTAG, TAG+" trackDist/MAXLATLNGS " + trackDist/MAXLATLNGS ); -// -// QLog.getLogger().d(dTAG, TAG+" stepValue is " + stepValue); - float lastSumdist = 0; - for(int i=0;ilastWb4map.getTime()) -// QLog.getLogger().d(dTAG, TAG+" No.i,lastwb.gettime():"+i+"," + Utils.getFormatedTime(lastWb4map.getTime())); -// QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()" + (wb.getSumDist()-lastWb.getSumDist())); -// QLog.getLogger().d(dTAG, TAG+" skipDist" + skipDist); -// QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()+skipDist" + (wb.getSumDist()-lastWb.getSumDist()+skipDist)); - float f =wb.getSumDist()-lastWb4map.getSumDist()+skipDist; -// QLog.getLogger().d(dTAG, TAG+" current dist " + f +", stepvalue is "+ stepValue +" dist >stepvalue?"+(f>=stepValue)); - if(returnWps.isEmpty() - ||f>=stepValue - ||wb.getTime()==startwp.getTime() - ||wb.getTime()==endwp.getTime() - ||wb.getTime()==maxwp.getTime() - ||!wb.getMedias().isEmpty() - ||wb.getTurnFlag()!=wpFlag.NORMAL - || wb.getKmflag() > 0 - - /*||wb.getTime()==track.getStartWp().getWb().getTime() - ||wb.getTime()==track.getLastWp().getWb().getTime() - ||wb.getTime()==track.getMaxDistWp().getWb().getTime()) */){ - wb.setDistance(wb.getSumDist() - lastSumdist); - returnWps.add(wb); - lastSumdist = wb.getSumDist(); - skipDist=0; - } - else{ - skipDist +=wb.getSumDist()-lastWb4map.getSumDist(); - QLog.getLogger().d(dTAG, "zip wps, skipDist" + skipDist +" wb is skipt: "+ wb.getSumDist()); - } - - lastWb4map =wb; - -// lastWb=wb; -// if(wb.getTime()*/ ArrayList wpsIn,Track track,boolean is4Baidu,int size)throws NullPointerException{ - - /* CopyOnWriteArrayList wps = new CopyOnWriteArrayList();*/ - ArrayList wps = new ArrayList(); - for(Waypoint_bean wb:wpsIn){ - if(wb!=null) - wps.add(wb); - } - if(wps.size()==0)return""; - Waypoint_bean startwp =/*track.getStartWp()!=null?track.getStartWp().getWb():*/wps.get(0); - Waypoint_bean endwp =/*track.getLastWp()!=null?track.getLastWp().getWb():*/wps.get(wps.size()-1); - int width ; - int height ; -// int scale=1; -// String center=""; - String pathStyle ; - String format; -// String staticMapUrl; - final int maxWidth=1024/2; - String baiduUrl ="https://api.map.baidu.com/staticimage"; - QLog.getLogger().d(dTAG, "screen width * height:" +QiYouConstant.PV_INT_SCREEN_WIDTH+"*"+QiYouConstant.PV_INT_SCREEN_HEIGHT); - width= QiYouConstant.PV_INT_SCREEN_WIDTH>0? QiYouConstant.PV_INT_SCREEN_WIDTH:720; - -// width= QiYouConstant.PV_INT_SCREEN_HEIGHT>0? QiYouConstant.PV_INT_SCREEN_HEIGHT:540; - width =width/2; - width=width>maxWidth?maxWidth:width; -// height=width/3; -// width =width/2; -// height=height/2; - height=width*QiYouConstant.PV_INT_SCREEN_WIDTH/QiYouConstant.PV_INT_SCREEN_HEIGHT; -// center=""; - pathStyle="0xff0000,4,1"; - - String startpoint=startwp==null?"" - : getbdLon(startwp.getLatitude(), startwp.getLongitude()) - +"," - + getbdLat(startwp.getLatitude(), startwp.getLongitude()) - ; - String endpoint=endwp==null?"" - : getbdLon(endwp.getLatitude(), endwp.getLongitude()) - +"," - + getbdLat(endwp.getLatitude(), endwp.getLongitude()) - ; - - format ="?" - +"width=%s&height=%s&paths=%s&pathStyles=%s" -// +"©right=1&scale=%s" - +"©right=1" - +"&markers=%s&markerStyles=-1,https://www.i7lv.net/icon_start.png|-1,https://www.i7lv.net/icon_end.png" - ; - - return baiduUrl+String.format(format, width,height,buildPathPoints( wps, track, is4Baidu, size),pathStyle, startpoint +"|"+endpoint); -} - -public static String getBaiduStaticMapUrl( Track track ){ - String url=""; - try{ - url= track.getTrackBean().getTrkseg().size()>2?Utils.getBaiduStaticUrl(track.getTrackBean().getTrkseg() - ,track - ,true - ,50-3):""; - }catch(NullPointerException e){ - logStackTrace(e,dTAG); - } - QLog.getLogger().d(dTAG, " displaying static image of " + url); - return url; -} - - public static String getBaiduStaticUrlFromServer(int svrNo){ - return QiYouConstant.BASE_STATIC_URL+svrNo; - } - - private static Pattern pattern; - private static Matcher matcher; - //Email Pattern - private static final String EMAIL_PATTERN = - "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" - + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - - /** - * Validate Email with regular expression - * - * @param email - * @return true for Valid Email and false for Invalid Email - */ - public static boolean validate(String email) { - pattern = Pattern.compile(EMAIL_PATTERN); - matcher = pattern.matcher(email); - return matcher.matches(); - - } - /** - * Checks for Null String object - * - * @param txt - * @return true for not null and false for null String object - */ - public static boolean isNotNull(String txt){ -// return txt!=null && txt.trim().length()>0 ? true: false; - return TextUtils.isEmpty(txt); - } - - static Gson gson=null; - public static Gson getGson(){ - if(gson==null) - gson= new Gson(); - return gson; - } - public static String getGsonString(Object obj){ - - return getGson().toJson(obj).toString(); - } - - public static Object getGsonObject(String json ,Class T)throws JsonSyntaxException { -// QLog.getLogger().dLog(TAG,"json is:" + json); - return getGson().fromJson(json, T); - } - - /* - * MD5加密 - */ - public static String getMD5Str(String str) { - MessageDigest messageDigest = null; - - try { - messageDigest = MessageDigest.getInstance("MD5"); - - messageDigest.reset(); - - messageDigest.update(str.getBytes("UTF-8")); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - - byte[] byteArray = messageDigest.digest(); - - StringBuffer md5StrBuff = new StringBuffer(); - - for (int i = 0; i < byteArray.length; i++) { - if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) - md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); - else - md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); - } - //16位加密,从第9位到25位 - return md5StrBuff.substring(8, 24).toString().toUpperCase(); - } - - - /* public static CopyOnWriteArrayList getCleanWbs(CopyOnWriteArrayList owbs){ - CopyOnWriteArrayList wbs=new CopyOnWriteArrayList(); - long lastTime=0; - for(Waypoint_bean wb:owbs){ - if(wb==null)continue; - if( wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt() || wb.getTime()>lastTime){ - wbs.add(wb); - lastTime =wb.getTime(); - } - } - return wbs; - }*/ - public static ArrayList getCleanWbs( ArrayList owbs){ - ArrayList wbs=new ArrayList(); - long lastTime=0; - for(Waypoint_bean wb:owbs){ - if(wb==null)continue; - if( wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt() || wb.getTime()>lastTime){ - wbs.add(wb); - lastTime =wb.getTime(); - } - } - return wbs; - } - public static int getAndroidSDKVersion() { - int version = 0; - try { - version = Integer.valueOf(android.os.Build.VERSION.SDK); - } catch (NumberFormatException e) { - logStackTrace(e, TAG); - } - return version; - } - - - public static Bitmap getBitmapFromView(View view ) { -// int widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY); -// int heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY); -// view.measure(widthSpec, heightSpec); -// view.layout(0, 0, width, height); - - Bitmap bitmap = Bitmap.createBitmap(view.getWidth() , view.getHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmap); - Drawable bgDrawable =view.getBackground(); - if (bgDrawable!=null) - bgDrawable.draw(canvas); - else -// canvas.drawColor(R.color.ivory);//#FFFFF0 - canvas.drawColor(Color.parseColor("#FFFFFF") ); - - view.draw(canvas); -// canvas.drawBitmap(bitmap, 0,0, null); - return bitmap; - } - - public static Bitmap convertViewToBitmap(View view){ - view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); - view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); - view.buildDrawingCache(); - Bitmap bitmap = view.getDrawingCache(); - - return bitmap; - } - - - public static int getTrackType(){ - - return QiYouConstant.DEVELOPER_MODE? - R.array.trackType:R.array.trackType; -// R.array.trackType_develop_use:R.array.trackType; - } - - - public static String getCacheFileName(String fileName) - { - File localFile = new File(QiYouConstant.GPX_CACHE_PATH); - if (!localFile.exists()) { - localFile.mkdirs(); - } - return localFile.getAbsolutePath() + File.separator + fileName + ".txt"; - } - - - public static Track getTrackFromWebCache(String paramString) throws IOException,JsonSyntaxException{ - String str = Utils.readSDFile(getCacheFileName(paramString)); - QLog.getLogger().d(dTAG, TAG +"reading track from gpx cache" +getCacheFileName(paramString)); - if (TextUtils.isEmpty(str)) { - return null; - } - QLog.getLogger().d(dTAG, TAG +"reading track from gpx cache ... success " +str); - return new Track((Track_bean)Utils.getGsonObject(str, Track_bean.class)); - } - - - public static String getProvince(String province){ - - if(TextUtils.isEmpty(province))return ""; - - if(province.startsWith("黑龙江"))return "黑龙江"; - if(province.startsWith("新疆"))return "新疆"; - if(province.startsWith("西藏"))return "西藏"; - if(province.startsWith("广西"))return "广西"; - if(province.startsWith("宁夏"))return "宁夏"; - if(province.startsWith("西藏"))return "西藏"; - return province.substring(0,3); - } - - public static String getGeoDistrict(String geoIn,int length){ - - - if(TextUtils.isEmpty(geoIn))return geoIn; - int lng=length>> " + enToStr); - return enToStr; - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/base/IStrictMode.java b/qy/src/main/java/com/qiyou/mb/android/utils/base/IStrictMode.java deleted file mode 100644 index 43cc566..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/base/IStrictMode.java +++ /dev/null @@ -1,14 +0,0 @@ - -package com.qiyou.mb.android.utils.base; - -/** - * This Interface definition allows you to create OS version-specific - * implementations that offer the full Strict Mode functionality - * available in each platform release. - */ -public interface IStrictMode { - /** - * Enable {@link StrictMode} using whichever platform-specific flags you wish. - */ - public void enableStrictMode(); -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/base/IlocationFragment.java b/qy/src/main/java/com/qiyou/mb/android/utils/base/IlocationFragment.java deleted file mode 100644 index c5eb9f4..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/base/IlocationFragment.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.qiyou.mb.android.utils.base; - -import android.location.Location; - -//import com.baidu.location.BDLocation; - -public interface IlocationFragment { -// public Boolean isOnPause =false; -//public void updateUI(Location location, Boolean isOnPause,Boolean isNoSignal); - public void updateUI(Location location, Boolean isOnPause); - public void navInfo( Location location); - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/bmap/MyItem.java b/qy/src/main/java/com/qiyou/mb/android/utils/bmap/MyItem.java deleted file mode 100644 index fe771fd..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/bmap/MyItem.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.qiyou.mb.android.utils.bmap; - - import android.graphics.Bitmap; - -import com.baidu.mapapi.map.BitmapDescriptor; -import com.baidu.mapapi.map.BitmapDescriptorFactory; -import com.baidu.mapapi.model.LatLng; - -/** - * 每个Marker点,包含Marker点坐标以及图标 - */ -public class MyItem /* implements ClusterItem */{ - private final LatLng mPosition; - private final Bitmap bitmap; - public MyItem(LatLng latLng,Bitmap bit) { - mPosition = latLng; - bitmap =bit; - } - - public LatLng getPosition() { - return mPosition; - } - - - public BitmapDescriptor getBitmapDescriptor() { - return BitmapDescriptorFactory - .fromBitmap(bitmap); - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/bmap/ZoomControlView.java b/qy/src/main/java/com/qiyou/mb/android/utils/bmap/ZoomControlView.java deleted file mode 100644 index daa1d23..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/bmap/ZoomControlView.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.qiyou.mb.android.utils.bmap; - -import com.baidu.mapapi.map.MapStatusUpdate; -import com.baidu.mapapi.map.MapStatusUpdateFactory; -import com.baidu.mapapi.map.MapView ; -import com.qiyou.mb.android.R; -import android.annotation.TargetApi; -import android.content.Context; -import android.os.Build; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.Button; -import android.widget.RelativeLayout; -import android.widget.Toast; -import android.view.View.OnClickListener; - -public class ZoomControlView extends RelativeLayout implements OnClickListener{ - private Button mButtonZoomin; - private Button mButtonZoomout; - private MapView mapView; - private float maxZoomLevel; - private float minZoomLevel; - - public ZoomControlView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public ZoomControlView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(); - } - - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - private void init() { - View view = LayoutInflater.from(getContext()).inflate(R.layout.zoom_controls_layout, null); - mButtonZoomin = (Button) view.findViewById(R.id.zoomin); - mButtonZoomout = (Button) view.findViewById(R.id.zoomout); - mButtonZoomin.setOnClickListener(this); - mButtonZoomout.setOnClickListener(this); - float alpha=0.5f; - mButtonZoomin.setAlpha(alpha); - mButtonZoomout.setAlpha(alpha); - - addView(view); - } - - @Override - public void onClick(View v) { - if(mapView == null){ - throw new NullPointerException("you can call setMapView(MapView mapView) at first"); - } -// mBaiduMap = mapView.getMap(); - - switch (v.getId()) { - case R.id.zoomin:{ - - MapStatusUpdate u = MapStatusUpdateFactory.zoomIn(); - mapView.getMap().animateMapStatus(u); - - - break; - } - case R.id.zoomout:{ - MapStatusUpdate u = MapStatusUpdateFactory.zoomOut(); - mapView.getMap().animateMapStatus(u); - break; - } - } - } - - /** - * 与MapView设置关联 - * @param mapView - */ - public void setMapView(MapView mapView) { - this.mapView = mapView; - // 获取最大的缩放级别 - maxZoomLevel = mapView.getMap().getMaxZoomLevel(); - // 获取最大的缩放级别 - minZoomLevel = mapView.getMap().getMinZoomLevel(); - } - - - /** - * 根据MapView的缩放级别更新缩放按钮的状态,当达到最大缩放级别,设置mButtonZoomin - * 为不能点击,反之设置mButtonZoomout - * @param level - */ - public void refreshZoomButtonStatus(int level){ - if(mapView == null){ - throw new NullPointerException("you can call setMapView(MapView mapView) at first"); - } - if(level > minZoomLevel && level < maxZoomLevel){ - if(!mButtonZoomout.isEnabled()){ - mButtonZoomout.setEnabled(true); - } - if(!mButtonZoomin.isEnabled()){ - mButtonZoomin.setEnabled(true); - } - } - else if(level == minZoomLevel ){ - mButtonZoomout.setEnabled(false); - } - else if(level == maxZoomLevel){ - mButtonZoomin.setEnabled(false); - } - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/ActivityStatus.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/ActivityStatus.java deleted file mode 100644 index 070beaa..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/ActivityStatus.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum ActivityStatus { - -//0,1,2,3,...(pending,recording,paused,finished,...) -PENING(0),ACTIVE(1),INACTIVE(2),EXPIRED(3),CLOSED(4),CANCLED(5); - -ActivityStatus(int status){ -this.status=status; -} -private int status=0; -@Override -public String toString() { - -return String.valueOf(this.status); - -} -public int toInt() { - -return status; - -} -public static ActivityStatus valueOf(int type) { -// TODO Auto-generated method stub -switch(type){ - case 0:{return PENING;} - case 1:{return ACTIVE;} - case 2:return INACTIVE; - case 3:return EXPIRED; - case 4:return CLOSED; - case 5:return CANCLED; - default: return ACTIVE; - } -} -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/ActivityType.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/ActivityType.java deleted file mode 100644 index c46d780..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/ActivityType.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum ActivityType { - -PUBLIC(0),CYCLE(1),PRIVATE(2);; - -ActivityType(int type){ - this.type=type; -} -private int type=0; -@Override -public String toString() { - - return String.valueOf(this.type); - -} -public int toInt() { - - return type; - -} - - -public String toCHString() { - - switch(type){ - case 0:{return "自由加入";} - case 1:{return "圈内";} - default:return "私有"; - } - -} - -public static ActivityType valueOf(int type) { - // TODO Auto-generated method stub - switch(type){ - case 0:{return PUBLIC;} - case 1:{return CYCLE;} - case 2:{return PRIVATE;} - default: return PUBLIC; - } - - } -public String getChString() { - return toCHString(); -} - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/BBSCate.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/BBSCate.java deleted file mode 100644 index 11dc451..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/BBSCate.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum BBSCate { - NORMAL(0),ACT(1),GROUP(2) ,TRACK(3) ,USER(4) ,GEO(5),LEARNING(6),BIKECARE(7),QANDA(8),QXTD(9),PYJL(10),TBDS(11) ; //QXTD(9),PYJL(10),TBDS(11) "骑行天地","跑友交流","徒步户外", - - - BBSCate(int FLAG){ - this.FLAG=FLAG; - } - private int FLAG=0; - - - public String toCHString() { - - switch(FLAG){ - - case 0:{return "聚义厅";} - case 1:{return "活动";} - case 2:return "队伍"; - case 3:return "轨迹"; - case 4:return "驴友"; - case 5:return "地区"; - case 6:return "软件使用"; - case 7:return "运动装备"; - case 8:return "问题反馈"; - case 9:return "骑行天地"; - case 10:return "跑友交流"; - case 11:return "徒步户外"; - - default: return "聚义厅"; - } - - } - - public int toInt() { - - return FLAG; - - } - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/FootmarkLevel.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/FootmarkLevel.java deleted file mode 100644 index 40aadc9..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/FootmarkLevel.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum FootmarkLevel { - -STANDARD(0),GEO(1),NOPIC(2),NOWORD(3); - -FootmarkLevel(int level){ - this.level=level; -} -private int level=0; -@Override -public String toString() { - - return String.valueOf(this.level); - -} - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/MessageType.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/MessageType.java deleted file mode 100644 index c0a8b71..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/MessageType.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum MessageType { - - NORMAL_MESSAGE(0),REQUEST_JOIN_ACTIVITY(1),REQUEST_JOIN_TEAM(2),INVITE_JOIN_ACTIVITY(3); - -MessageType(int type){ - this.type=type; -} -private int type=0; -@Override -public String toString() { - - return String.valueOf(this.type); - -} -public int toInt() { - - return type; - -} - - - -public static MessageType valueOf(int type) { - // TODO Auto-generated method stub - switch(type){ - case 0:{return NORMAL_MESSAGE;} - case 1:{return REQUEST_JOIN_ACTIVITY;} - case 2:{return REQUEST_JOIN_TEAM;} - case 3:{return INVITE_JOIN_ACTIVITY;} - default: return REQUEST_JOIN_ACTIVITY; - } - - } - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/OperationType.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/OperationType.java deleted file mode 100644 index d7e6593..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/OperationType.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum OperationType { - - NORMAL(0),INPROGRESS(1),DONE(2),FAILED(3); - -OperationType(int type){ - this.type=type; -} -private int type=0; -@Override -public String toString() { - - return String.valueOf(this.type); - -} -public int toInt() { - - return type; - -} - - -public static OperationType valueOf(int type) { - // TODO Auto-generated method stub - switch(type){ - case 0:{return NORMAL;} - case 1:{return INPROGRESS;} - case 2:{return DONE;} - case 3:{return FAILED;} - - default: return NORMAL; - } - - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackAvStatus.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackAvStatus.java deleted file mode 100644 index fab1f04..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackAvStatus.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.qiyou.mb.android.utils.enums; -/* - * available status - */ -public enum TrackAvStatus { -ACTIVE(0),INACTIVE(1),DELETED(2),PUBLIC(3),PRIVATE(4),CYCLE(5); - -TrackAvStatus(int status){ -this.status=status; -} -private int status=0; -@Override -public String toString() { - -return String.valueOf(this.status); - -} -public int toInt() { - -return status; - -} -public static TrackAvStatus valueOf(int type) { -switch(type){ - case 0:{return ACTIVE;} - case 1:{return INACTIVE;} - case 2:return DELETED; - case 3:{return PUBLIC;} - case 4:return PRIVATE; - case 5:return CYCLE; - default: return ACTIVE; - } -} -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackStatus.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackStatus.java deleted file mode 100644 index 621af0d..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackStatus.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum TrackStatus { - -//0,1,2,3,...(pending,recording,paused,finished,...) -PENING(0),RECORDING(1),PAUSED(2),FINISHED(3),DELETED(4),ACTIVE(5),INACTIVE(6); - -TrackStatus(int status){ -this.status=status; -} -private int status=0; -@Override -public String toString() { - -return String.valueOf(this.status); - -} -public int toInt() { - -return status; - -} -public static TrackStatus valueOf(int type) { -// TODO Auto-generated method stub -switch(type){ - case 0:{return PENING;} - case 1:{return RECORDING;} - case 2:return PAUSED; - case 3:return FINISHED; - case 4:return DELETED; - case 5:return ACTIVE; - case 6:return INACTIVE; - default: return DELETED; - } -} -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackType.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackType.java deleted file mode 100644 index 4dcf546..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/TrackType.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum TrackType { - -BIKE(0),HIKE(1),MOTOR(2),FLY(3),DIVE(4),GPX(5),OTHER(6),COPY(7); - -TrackType(int type){ - this.type=type; -} -private int type=0; -@Override -public String toString() { - - return String.valueOf(this.type); - -} -public int toInt() { - - return type; - -} - -public String toCHString() { - - switch(type){ - case 0:{return "骑行";} - case 1:{return "徒步";} - case 2:return "机动"; - case 3:return "轮滑"; - case 4:return "踏板"; - case 5:return "路书"; - case 7:return "拷贝"; - case 6:return "其他"; - default:return "骑行"; - } - -} -//public TrackType getType(final int type){ -// switch(type){ -// case 0:{return BIKE;} -// case 1:{return HIKE;} -// case 2:return MOTOR; -// case 3:return FLY; -// case 4:return DIVE; -// case 5:return OTHER; -// default: return BIKE; -// } -// } -public static TrackType valueOf(int type) { - // TODO Auto-generated method stub - switch(type){ - case 0:{return BIKE;} - case 1:{return HIKE;} - case 2:return MOTOR; - case 3:return FLY; - case 4:return DIVE; - case 5:return GPX; - case 7:return COPY; - case 6:return OTHER; - default: return BIKE; - } - - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/WebQueryCate.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/WebQueryCate.java deleted file mode 100644 index 30965e1..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/WebQueryCate.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum WebQueryCate { - -//-1,0,1,2,3,...(turnLeft,start,turnRight,paused,finished,...) - //NORMAL(-2),TURNLEFT(-1),START(0),TURNRIGHT(1),TURNBACK(2),MAXR(3),END(4),CUST(5),TENT(6),REST(7),CHECK(8),HAND(9); - LATEST(0),MYNEARBY(1),GEO(2) ,KEYWORD(3) ,MINE(4) ,USER(5),SVRNO(6),BIKE(7),GPX(8),HIKE(9),MOTOR(10),SCORE(11) - ,ACTIVITY(12),GROUP(13),LEARNING(14),BIKECARE(15),QANDA(16),QXTD(17),PYJL(18),TBDS(19), - -CITY(20) ; //city always be the last one - -WebQueryCate(int FLAG){ - this.FLAG=FLAG; -} -private int FLAG=0; -/*@Override -public String toString() { - return String.valueOf(this.FLAG); -}*/ - -public String toCHString() { - - switch(FLAG){ - case 0:{return "最新";} - case 1:{return "周边";} - case 2:return "按地区查找"; - case 3:return "按关键字查找"; - case 4:return "我的"; - case 5:return "按驴友名称查找"; - case 6:return "按编号查找"; - case 7:return "骑行类型的"; - case 8:return "路书类型的"; - case 9:return "徒步类型的"; - case 10:return "机动类型的"; - case 11:return "按积分排序"; - - case 12:{return "活动相关的说说";} - case 13:return "队伍相关的说说"; - case 14:return "新手乐园,软件的基本使用都可以在这里讨论"; - case 16:return "问题反馈,软件使用中的问题和建议"; - case 15:return "运动装备,爱车养护,装备相关分享都可以在这里讨论"; - case 17:return "骑行天地,骑行话题都来这里说吧"; - case 18:return "跑友交流,喜欢跑步的朋友到这里来吧"; - case 19:return "徒步户外,喜欢徒步爬山的朋友来这里啦"; - case 20:return "地方论坛,本地驴友到这里聚聚吧"; - - default: return "最新"; - } - -} - -public int toInt() { - -return FLAG; - -} -/* -public static WebQueryCate valueOf(int type) { -// TODO Auto-generated method stub -switch(type){ - case 0:{return LATEST;} - case 1:{return MYNEARBY;} - case 2:{return GEO;} - case 3:{return KEYWORD;} - case 4:return MINE; - case 5:return USER; - case 6:return SVRNO; - case 7:return BIKE; - case 8:return GPX; - case 9:return HIKE; - case 10:return MOTOR; - case 11:return SCORE; - case 12:return ACTIVITY; - case 13:return GROUP; - case 14:return LEARNING; - case 15:return QANDA; - case 16:return BIKECARE; - case 17:return CITY; -// case 18:return GPX; -// case 19:return HIKE; - - default: return LATEST; - } -} -*/ -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/WorkingTrackType.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/WorkingTrackType.java deleted file mode 100644 index 37c370b..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/WorkingTrackType.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum WorkingTrackType { - -RECORDING(0),DETAIL(1),PLAYBACK(2),GPX(3),ROUTE(4); - -WorkingTrackType(int workTrackType){ - this.workTrackType=workTrackType; -} -private int workTrackType=0; -@Override -public String toString() { - - return String.valueOf(this.workTrackType); - -} - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/mediaStatus.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/mediaStatus.java deleted file mode 100644 index 71d5fda..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/mediaStatus.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum mediaStatus { - -NORMAL(0),DELETED(1),SHARED(2),HIDED(3),UPLOADED(4),; - -mediaStatus(int type){ - this.type=type; -} -private int type=0; -@Override -public String toString() { - - return String.valueOf(this.type); - -} -public int toInt() { - - return type; - -} -public static mediaStatus valueOf(int type) { - // TODO Auto-generated method stub - switch(type){ - case 0:{return NORMAL;} - case 1:{return DELETED;} - case 2:return SHARED; - case 3:return HIDED; - case 4:return UPLOADED; - default: return NORMAL; - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/mediaType.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/mediaType.java deleted file mode 100644 index cc24982..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/mediaType.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum mediaType { - -PIC(0),MAP(1),VIDEO(2),SOUND(3); - -mediaType(int type){ - this.type=type; -} -private int type=0; -@Override -public String toString() { - - return String.valueOf(this.type); - -} -public int toInt() { - - return type; - -} -public static mediaType valueOf(int type) { - // TODO Auto-generated method stub - switch(type){ - case 0:{return PIC;} - case 1:{return MAP;} - case 2:return VIDEO; - case 3:return SOUND; - default: return PIC; - } - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/enums/wpFlag.java b/qy/src/main/java/com/qiyou/mb/android/utils/enums/wpFlag.java deleted file mode 100644 index 6c9eee7..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/enums/wpFlag.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.qiyou.mb.android.utils.enums; - -public enum wpFlag { - -//-1,0,1,2,3,...(turnLeft,start,turnRight,paused,finished,...) - NORMAL(-2),TURNLEFT(-1),START(0),TURNRIGHT(1),TURNBACK(2),MAXR(3),END(4),CUST(5),TENT(6),REST(7),CHECK(8),HAND(9); - -wpFlag(int FLAG){ - this.FLAG=FLAG; -} -private int FLAG=-2; -/*@Override -public String toString() { - return String.valueOf(this.FLAG); -}*/ - -public String toCHString() { - - switch(FLAG){ - case -2:{return "普通";} - case -1:{return "左转";} - case 0:{return "起点";} - case 1:{return "右转";} - case 2:return "掉头"; - case 3:return "最远"; - case 4:return "终点"; - case 5:return "途径"; - case 6:return "扎营"; - case 7:return "休息"; - case 8:return "打卡"; - case 9:return "手绘"; - default: return "普通"; - } - -} - - - -public int toInt() { - -return FLAG; - -} -public static wpFlag valueOf(int type) { -// TODO Auto-generated method stub -switch(type){ - case -2:{return NORMAL;} - case -1:{return TURNLEFT;} - case 0:{return START;} - case 1:{return TURNRIGHT;} - case 2:return TURNBACK; - case 3:return MAXR; - case 4:return END; - case 5:return CUST; - case 6:return TENT; - case 7:return REST; - case 8:return CHECK; - case 9:return HAND; - default: return NORMAL; - } -} -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/exception/NoWebObjectException.java b/qy/src/main/java/com/qiyou/mb/android/utils/exception/NoWebObjectException.java deleted file mode 100644 index f423c8c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/exception/NoWebObjectException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.qiyou.mb.android.utils.exception; - -public class NoWebObjectException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -3894614973550601139L; - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/image/ImageGridAdapter.java b/qy/src/main/java/com/qiyou/mb/android/utils/image/ImageGridAdapter.java deleted file mode 100644 index 73483d3..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/image/ImageGridAdapter.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.qiyou.mb.android.utils.image; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; - -import com.nostra13.universalimageloader.core.ImageLoader; -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.R; - -public class ImageGridAdapter extends BaseAdapter { - private String[] files; - - private LayoutInflater mLayoutInflater; - - public ImageGridAdapter(String[] files, Context context) { - this.files = files; - mLayoutInflater = LayoutInflater.from(context); - } - - @Override - public int getCount() { - return files == null ? 0 : files.length; - } - - @Override - public String getItem(int position) { - return files[position]; - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - MyGridViewHolder viewHolder; - if (convertView == null) { - viewHolder = new MyGridViewHolder(); - convertView = mLayoutInflater.inflate(R.layout.gridview_item, - parent, false); - viewHolder.imageView = (QimageView) convertView - .findViewById(R.id.album_image); - - convertView.setTag(viewHolder); - } else { - viewHolder = (MyGridViewHolder) convertView.getTag(); - } - String url = getItem(position); - viewHolder.imageView.getLayoutParams().height= (int) (QiYouConstant.PV_INT_SCREEN_WIDTH/4.5); - viewHolder.imageView.getLayoutParams().width=(int) (QiYouConstant.PV_INT_SCREEN_WIDTH/4.5); -// QLog.getLogger().d(dTAG, "imageloader to display url is:"+url); - ImageLoader.getInstance().displayImage(url, viewHolder.imageView); -// IL.DisplayImage(url, viewHolder.imageView); - return convertView; - } - - private static class MyGridViewHolder { - QimageView imageView; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/image/ImageUtil.java b/qy/src/main/java/com/qiyou/mb/android/utils/image/ImageUtil.java deleted file mode 100644 index f231292..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/image/ImageUtil.java +++ /dev/null @@ -1,254 +0,0 @@ -package com.qiyou.mb.android.utils.image; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.LinkedList; -import java.util.List; - -import com.qiyou.mb.android.utils.log.QLog; - -import android.annotation.SuppressLint; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Matrix; -import android.media.ExifInterface; - -public class ImageUtil { - public static final String TAG = "com.qiyou.mb.android.utils.ImageUtil"; - public static final String dTAG = "com.qiyou"; - @SuppressLint("NewApi") - public static Bitmap get_Picture_bitmap(String imagePath) { - - long size_file = getFileSize(new File(imagePath)); - - size_file = (size_file) / 1000;// in Kb now - int ample_size = 1; - - if (size_file <= 250) { - - System.out.println("SSSSS1111= " + size_file); - ample_size = 2; - - } else if (size_file > 251 && size_file < 1500) { - - System.out.println("SSSSS2222= " + size_file); - ample_size = 4; - - } else if (size_file >= 1500 && size_file < 3000) { - - System.out.println("SSSSS3333= " + size_file); - ample_size = 8; - - } else if (size_file >= 3000 && size_file <= 4500) { - - System.out.println("SSSSS4444= " + size_file); - ample_size = 12; - - } else if (size_file >= 4500) { - - System.out.println("SSSSS4444= " + size_file); - ample_size = 16; - } - - Bitmap bitmap = null; - - BitmapFactory.Options bitoption = new BitmapFactory.Options(); - bitoption.inSampleSize = ample_size; - - Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption); - - ExifInterface exif = null; - try { - exif = new ExifInterface(imagePath); - } catch (IOException e) { - // Auto-generated catch block - e.printStackTrace(); - } - int orientation = exif - .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); - Matrix matrix = new Matrix(); - - if ((orientation == 3)) { - matrix.postRotate(180); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } else if (orientation == 6) { - matrix.postRotate(90); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } else if (orientation == 8) { - matrix.postRotate(270); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } else { - matrix.postRotate(0); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } - - return bitmap; - - } - public static long getFileSize(final File file) { - if (file == null || !file.exists()) - return 0; - if (!file.isDirectory()) - return file.length(); - final List dirs = new LinkedList(); - dirs.add(file); - long result = 0; - while (!dirs.isEmpty()) { - final File dir = dirs.remove(0); - if (!dir.exists()) - continue; - final File[] listFiles = dir.listFiles(); - if (listFiles == null || listFiles.length == 0) - continue; - for (final File child : listFiles) { - result += child.length(); - if (child.isDirectory()) - dirs.add(child); - } - } - - return result; - } - - /** - * Calcuate how much to compress the image - * @param options - * @param reqWidth - * @param reqHeight - * @return - */ - public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth) { - // Raw height and width of image - final int height = options.outHeight; - final int width = options.outWidth; - int reqHeight = (int) (height * reqWidth / (double) width); // casts to avoid truncating - - int inSampleSize = 1; - - if (height > reqHeight || width > reqWidth) { - - final int halfHeight = height / 2; - final int halfWidth = width / 2; - - // Calculate the largest inSampleSize value that is a power of 2 and keeps both - // height and width larger than the requested height and width. - while ((halfHeight / inSampleSize) > reqHeight - && (halfWidth / inSampleSize) > reqWidth) { - inSampleSize *= 2; - } - } - - return inSampleSize; - } - - /** - * resize image to 480x800 - * @param filePath - * @return - */ - @SuppressLint("NewApi") - public static Bitmap getSmallBitmap(String filePath, int targetWidth) { - - File file = new File(filePath); - long originalSize = file.length(); -// int targetWidth = 640; // your arbitrary fixed limit - - QLog.getLogger().d(dTAG,TAG+"Original image size is: " + originalSize + " bytes."); - - final BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeFile(filePath, options); - - // Calculate inSampleSize based on a preset ratio - options.inSampleSize = calculateInSampleSize(options, targetWidth); - - // Decode bitmap with inSampleSize set - options.inJustDecodeBounds = false; - - Bitmap compressedImage = BitmapFactory.decodeFile(filePath, options); - - /* OutputStream imagefile = new FileOutputStream("/your/file/name.jpg"); - // Write 'bitmap' to file using JPEG and 80% quality hint for JPEG: - bitmap.compress(CompressFormat.JPEG, 80, imagefile);*/ - getCorrectDirection(filePath,compressedImage); - QLog.getLogger().d(dTAG,TAG+" Compressed image size is " + compressedImage.getByteCount() + " bytes, percent:" + (compressedImage.getByteCount()*100/originalSize)); - - - return compressedImage; - } - - @SuppressLint("NewApi") - static Bitmap getCorrectDirection(String imagePath,Bitmap bitmapPhoto ){ - - if (bitmapPhoto == null){ - return null; - } - - ExifInterface exif = null; - Bitmap bitmap =bitmapPhoto; - try { - exif = new ExifInterface(imagePath); - } catch (IOException e) { - // Auto-generated catch block - e.printStackTrace(); - } - int orientation = exif - .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); - Matrix matrix = new Matrix(); - - if ((orientation == 3)) { - matrix.postRotate(180); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } else if (orientation == 6) { - matrix.postRotate(90); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } else if (orientation == 8) { - matrix.postRotate(270); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } else { - matrix.postRotate(0); - bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - } - - return bitmap; - } - static Bitmap rotateImage(Bitmap bitmapPhoto,int degree ){ - - Matrix matrix = new Matrix(); - matrix.postRotate(degree); - Bitmap bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, - bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, - true); - - - return bitmap; - } -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/image/QRCodeUtil.java b/qy/src/main/java/com/qiyou/mb/android/utils/image/QRCodeUtil.java deleted file mode 100644 index 05da4cf..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/image/QRCodeUtil.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.qiyou.mb.android.utils.image; -import android.graphics.Bitmap; -import android.graphics.Canvas; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.EncodeHintType; -import com.google.zxing.WriterException; -import com.google.zxing.common.BitMatrix; -import com.google.zxing.qrcode.QRCodeWriter; -import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -/** - * Created by wangmi on 17/1/5. - */ - -public class QRCodeUtil { - /** - * 生成二维码Bitmap - * - * @param content 内容 - * @param widthPix 图片宽度 - * @param heightPix 图片高度 - * @param logoBm 二维码中心的Logo图标(可以为null) - * @param filePath 用于存储二维码图片的文件路径 - * @return 生成二维码及保存文件是否成功 - */ - public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) { - try { - if (content == null || "".equals(content)) { - return false; - } - - //配置参数 - Map hints = new HashMap<>(); - hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); - //容错级别 - hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); - //设置空白边距的宽度 -// hints.put(EncodeHintType.MARGIN, 2); //default is 4 - - // 图像数据转换,使用了矩阵转换 - BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints); - int[] pixels = new int[widthPix * heightPix]; - // 下面这里按照二维码的算法,逐个生成二维码的图片, - // 两个for循环是图片横列扫描的结果 - for (int y = 0; y < heightPix; y++) { - for (int x = 0; x < widthPix; x++) { - if (bitMatrix.get(x, y)) { - pixels[y * widthPix + x] = 0xff000000; - } else { - pixels[y * widthPix + x] = 0xffffffff; - } - } - } - - // 生成二维码图片的格式,使用ARGB_8888 - Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888); - bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix); - - if (logoBm != null) { - bitmap = addLogo(bitmap, logoBm); - } - - //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大! - return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath)); - } catch (WriterException | IOException e) { - e.printStackTrace(); - } - - return false; - } - - /** - * 在二维码中间添加Logo图案 - */ - private static Bitmap addLogo(Bitmap src, Bitmap logo) { - if (src == null) { - return null; - } - - if (logo == null) { - return src; - } - - //获取图片的宽高 - int srcWidth = src.getWidth(); - int srcHeight = src.getHeight(); - int logoWidth = logo.getWidth(); - int logoHeight = logo.getHeight(); - - if (srcWidth == 0 || srcHeight == 0) { - return null; - } - - if (logoWidth == 0 || logoHeight == 0) { - return src; - } - - //logo大小为二维码整体大小的1/5 - float scaleFactor = srcWidth * 1.0f / 5 / logoWidth; - Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888); - try { - Canvas canvas = new Canvas(bitmap); - canvas.drawBitmap(src, 0, 0, null); - canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2); - canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null); - - canvas.save(Canvas.ALL_SAVE_FLAG); - canvas.restore(); - } catch (Exception e) { - bitmap = null; - e.getStackTrace(); - } - - return bitmap; - } - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/image/QimageView.java b/qy/src/main/java/com/qiyou/mb/android/utils/image/QimageView.java deleted file mode 100644 index fd1144c..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/image/QimageView.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.qiyou.mb.android.utils.image; - -import android.content.Context; -import android.graphics.Canvas; -import android.util.AttributeSet; -import android.widget.ImageView; - -import com.qiyou.mb.android.utils.log.QLog; - -public class QimageView extends QroundimageView { - public static final String dTAG = "com.qiyou"; - public QimageView (Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - protected void onDraw(Canvas canvas) { - try { - super.onDraw(canvas); - } catch (Exception e) { - QLog.getLogger().d(dTAG,"trying to use a recycled bitmap"); - } - } - } \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/image/QroundimageView.java b/qy/src/main/java/com/qiyou/mb/android/utils/image/QroundimageView.java deleted file mode 100644 index ade9f46..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/image/QroundimageView.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.qiyou.mb.android.utils.image; - - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.graphics.Bitmap.Config; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.PorterDuff; -import android.graphics.PorterDuffXfermode; -import android.graphics.RectF; -import android.util.AttributeSet; -import android.widget.ImageView; - -import com.qiyou.mb.android.R; -import com.qiyou.mb.android.utils.log.QLog; - -public class QroundimageView extends ImageView { - public static final String dTAG = "com.qiyou"; - - - @Override - protected void onDraw(Canvas canvas) { - try { - super.onDraw(canvas); - } catch (Exception e) { - QLog.getLogger().d(dTAG,"trying to use a recycled bitmap"); - } - } - - private Paint paint; - /** - * 个人理解是 - * - * 这两个都是画圆的半径 - */ - private int roundWidth = 5; - private int roundHeight = 5; - private Paint paint2; - - public QroundimageView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(context, attrs); - } - - public QroundimageView(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs); - } - - public QroundimageView(Context context) { - super(context); - init(context, null); - } - - private void init(Context context, AttributeSet attrs) { - - if (attrs != null) { - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundAngleImageView); - roundWidth = a.getDimensionPixelSize(R.styleable.RoundAngleImageView_roundWidth, roundWidth); - roundHeight = a.getDimensionPixelSize(R.styleable.RoundAngleImageView_roundHeight, roundHeight); - } else { - float density = context.getResources().getDisplayMetrics().density; - roundWidth = (int) (roundWidth * density); - roundHeight = (int) (roundHeight * density); - } - - paint = new Paint(); - paint.setColor(Color.WHITE); - paint.setAntiAlias(true); - paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); - - paint2 = new Paint(); - paint2.setXfermode(null); - } - - @Override - public void draw(Canvas canvas) { - Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888); - Canvas canvas2 = new Canvas(bitmap); - super.draw(canvas2); - drawLiftUp(canvas2); - drawLiftDown(canvas2); - drawRightUp(canvas2); - drawRightDown(canvas2); - canvas.drawBitmap(bitmap, 0, 0, paint2); - bitmap.recycle(); - } - - private void drawLiftUp(Canvas canvas) { - Path path = new Path(); - path.moveTo(0, roundHeight); - path.lineTo(0, 0); - path.lineTo(roundWidth, 0); - path.arcTo(new RectF(0, 0, roundWidth * 2, roundHeight * 2), -90, -90); - path.close(); - canvas.drawPath(path, paint); - } - - private void drawLiftDown(Canvas canvas) { - Path path = new Path(); - path.moveTo(0, getHeight() - roundHeight); - path.lineTo(0, getHeight()); - path.lineTo(roundWidth, getHeight()); - path.arcTo(new RectF(0, getHeight() - roundHeight * 2, roundWidth * 2, getHeight()), 90, 90); - path.close(); - canvas.drawPath(path, paint); - } - - private void drawRightDown(Canvas canvas) { - Path path = new Path(); - path.moveTo(getWidth() - roundWidth, getHeight()); - path.lineTo(getWidth(), getHeight()); - path.lineTo(getWidth(), getHeight() - roundHeight); - path.arcTo(new RectF(getWidth() - roundWidth * 2, getHeight() - roundHeight * 2, getWidth(), getHeight()), -0, 90); - path.close(); - canvas.drawPath(path, paint); - } - - private void drawRightUp(Canvas canvas) { - Path path = new Path(); - path.moveTo(getWidth(), roundHeight); - path.lineTo(getWidth(), 0); - path.lineTo(getWidth() - roundWidth, 0); - path.arcTo(new RectF(getWidth() - roundWidth * 2, 0, getWidth(), 0 + roundHeight * 2), -90, 90); - path.close(); - canvas.drawPath(path, paint); - } - } \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/log/Logger.java b/qy/src/main/java/com/qiyou/mb/android/utils/log/Logger.java deleted file mode 100644 index 3e894a3..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/log/Logger.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.qiyou.mb.android.utils.log; - -/** - * interface for a logger class to replace the static calls to {@link android.util.Log} - */ -public interface Logger { - /** - * Send a {@link android.util.Log#VERBOSE} log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - int v(String tag, String msg); - - /** - * Send a {@link android.util.Log#VERBOSE} log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - int v(String tag, String msg, Throwable tr); - - /** - * Send a {@link android.util.Log#DEBUG} log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - int d(String tag, String msg); - int dLog(String dTag, String msg) ; - int dLog(String dTag,String Tag, String msg) ; - /** - * Send a {@link android.util.Log#DEBUG} log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - int d(String tag, String msg, Throwable tr); - - /** - * Send an {@link android.util.Log#INFO} log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - int i(String tag, String msg); - - /** - * Send a {@link android.util.Log#INFO} log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - int i(String tag, String msg, Throwable tr); - - /** - * Send a {@link android.util.Log#WARN} log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - int w(String tag, String msg); - - /** - * Send a {@link android.util.Log#WARN} log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - int w(String tag, String msg, Throwable tr); - - /** - * Send an {@link android.util.Log#ERROR} log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - int e(String tag, String msg); - - /** - * Send a {@link android.util.Log#ERROR} log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - int e(String tag, String msg, Throwable tr); -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/log/QLog.java b/qy/src/main/java/com/qiyou/mb/android/utils/log/QLog.java deleted file mode 100644 index 621f4ca..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/log/QLog.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.qiyou.mb.android.utils.log; - - -import android.util.Log; - -/** - * class that holds the {@link Logger} for this library, defaults to {@link LoggerDefault} to send logs to android {@link Log} - */ -public final class QLog { - - private static Logger logger = new mLog(); - - public static void setLogger(Logger newLogger) { - logger = newLogger; - } - - public static Logger getLogger() { - return logger; - } - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/log/mLog.java b/qy/src/main/java/com/qiyou/mb/android/utils/log/mLog.java deleted file mode 100644 index 93b0911..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/log/mLog.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.qiyou.mb.android.utils.log; - - -import com.qiyou.mb.android.QiYouConstant; -import com.qiyou.mb.android.utils.Utils; - -import android.util.Log; - -/** - * Helper class to redirect {@link LogManager#logger} to {@link Log} - */ -public class mLog implements Logger { - - @Override - public int v(String tag, String msg) { - return Log.v(tag, msg); - } - - @Override - public int v(String tag, String msg, Throwable tr) { - return Log.v(tag, msg, tr); - } - - @Override - public int d(String tag, String msg) { - if(msg!=null && QiYouConstant.LOG_LEVEL_DEBUG) - return Log.i(tag, msg); - else - return -1; - } - @Override - public int dLog(String dTag, String msg) { - if(QiYouConstant.LOG_LEVEL_DEBUG_FILE){ - Utils.logDbugTrace(dTag, msg); - } - - return d(dTag, msg); - } - @Override - public int dLog(String dTag,String Tag, String msg) { - if(QiYouConstant.LOG_LEVEL_DEBUG_FILE){ - Utils.logDbugTrace(Tag, msg); - } - return d(Tag, msg); -// return d(dTag, msg); - } - - - - @Override - public int d(String tag, String msg, Throwable tr) { - return Log.d(tag, msg, tr); - } - - @Override - public int i(String tag, String msg) { - return Log.i(tag, msg); - } - - @Override - public int i(String tag, String msg, Throwable tr) { - return Log.i(tag, msg, tr); - } - - @Override - public int w(String tag, String msg) { - return Log.w(tag, msg); - } - - @Override - public int w(String tag, String msg, Throwable tr) { - return Log.w(tag, msg, tr); - } - - @Override - public int e(String tag, String msg) { - return Log.e(tag, msg); - } - - @Override - public int e(String tag, String msg, Throwable tr) { - return Log.e(tag, msg, tr); - } - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/server/RestMethods.java b/qy/src/main/java/com/qiyou/mb/android/utils/server/RestMethods.java deleted file mode 100644 index 9844a26..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/server/RestMethods.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.qiyou.mb.android.utils.server; - -public class RestMethods { - - /*public static String ACT_P_IMPORT="/activity/"; - public static String ACT_P_ADD_MEMBER="/activity/addmember"; - public static String ACT_P_DEL_MEMBER="/activity/delmember"; - public static String ACT_P_UPDATE_ROODBOOK="/activity/roadbook"; - public static String ACT_G_LIST="/activity/list"; -// public static String ACT_G_NEARBY_LIST="/activity/nearbylist"; - public static String ACT_G_FIND_BY_ID="/activity/"; - public static String ACT_G_IS_MEMBER_HAS_ACT="/activity/isMemberHasAct"; -// public static String ACT_G_MEMBER_LIST="/user/actusers"; - - - public static String USER_G_FIND_BY_ID="/user/"; - public static String USER_G_FIND_BY_ACCOUNT="/account/"; - public static String USER_P_SUBMIT="/user/regist"; - public static String USER_P_USER_LOGIN="/user/loginNew"; - public static String USER_P_USER_STAT="/user/statistics"; - public static String USER_G_USER_STAT_STATUS="/user/statistics/status"; - public static String USER_G_USER_STAT="/user/statistics"; -// public static String USER_G_LIST_BY_ACTGRP="/user/actgrp"; - public static String USER_G_LIST="/user/list"; - - public static String GROUP_G_MEMBER_LIST="/user/groupusers"; - - public static String TRACK_G_LIST ="/track/list"; - public static String TRACK_G_FIND_BY_ID ="/track/"; - public static String TRACK_P_IMPORT ="/track/"; - public static String TRACK_P_UPLOAD_FILE ="/track/file"; - public static String TRACK_P_UPDATE_STATUS ="/track/status"; -// public static String TRACK_G_FIND_BY_ACT_GRP="/track/actgrp"; -// public static String TRACK_G_FIND_BY_GRP="/track/group"; - public static String LIVE_P_SHARE_LOCATION ="/sharelocation/"; - public static String LIVE_G_SHARE_LIST ="/sharelocation/list"; - - public static String GRP_P_IMPORT="/group/"; - public static String GRP_P_ADD_MEMBER="/group/addmember"; - public static String GRP_P_DEL_MEMBER="/group/delmember"; - public static String GRP_G_LIST="/group/list"; -// public static String GRP_G_NEARBY_LIST="/group/nearbylist"; - public static String GRP_G_FIND_BY_ID="/group/"; - public static String GRP_G_IS_MEMBER_HAS_GRP="/group/isMemberHasGrp"; - public static String GRP_G_MEMBER_LIST="/user/grpusers";*/ - - public static String ACT_P_IMPORT="/activity/"; - public static String ACT_P_ADD_MEMBER="/activity/addmember"; - public static String ACT_P_DEL_MEMBER="/activity/delmember"; - public static String ACT_P_UPDATE_ROODBOOK="/activity/roadbook"; - public static String ACT_G_LIST="/activity/list"; -// public static String ACT_G_NEARBY_LIST="/activity/nearbylist"; - public static String ACT_G_FIND_BY_ID="/activity/"; - public static String ACT_G_IS_MEMBER_HAS_ACT="/activity/isMemberHasAct"; - public static String ACT_P_UPLOAD_ALBUM="/activity/album"; - -// public static String ACT_G_MEMBER_LIST="/user/actusers"; -// public static String USER_G_LIST_BY_ACTGRP="/user/actgrp"; - public static String USER_G_LIST="/user/list"; - - - public static String USER_G_FIND_BY_ID="/user/"; - public static String USER_G_FIND_BY_ACCOUNT="/account/"; - public static String USER_P_UPDATE="/user/update"; - public static String USER_P_REGIST="/security/regist"; - public static String USER_P_USER_LOGIN="/security/login"; - public static String USER_P_USER_STAT="/user/statistics"; - public static String USER_G_USER_STAT_STATUS="/user/statistics/status"; - public static String USER_G_USER_STAT="/user/statistics"; - public static String USER_P_UPLOAD_ALBUM="/user/album"; - - public static String GROUP_G_MEMBER_LIST="/user/groupusers"; - - public static String TRACK_G_LIST ="/track/list"; - public static String TRACK_G_FIND_BY_ID ="/track/"; - public static String TRACK_P_IMPORT ="/track/"; - public static String TRACK_P_UPLOAD_FILE ="/track/file"; - public static String TRACK_P_UPDATE_STATUS ="/track/status"; -// public static String TRACK_G_FIND_BY_ACT_GRP="/track/actgrp"; -// public static String TRACK_G_FIND_BY_GRP="/track/group"; - public static String LIVE_P_SHARE_LOCATION ="/sharelocation/"; - public static String LIVE_G_SHARE_LIST ="/sharelocation/list"; - - public static String GRP_P_IMPORT="/group/"; - public static String GRP_P_ADD_MEMBER="/group/addmember"; - public static String GRP_P_DEL_MEMBER="/group/delmember"; - public static String GRP_G_LIST="/group/list"; - public static String GRP_G_NEARBY_LIST="/group/list"; - public static String GRP_G_FIND_BY_ID="/group/"; - public static String GRP_G_IS_MEMBER_HAS_GRP="/group/isMemberHasGrp"; - public static String GRP_G_MEMBER_LIST="/user/grpusers"; - public static String GRP_P_UPLOAD_ALBUM="/group/album"; - - public static String SECURITY_INVALIDE ="/mb/security/invalid"; - - public static String NOTE_P_IMPORT="/note/"; - public static String NOTE_G_LIST="/note/list"; - public static String NOTE_G_FIND_BY_ID="/note/"; - public static String NOTE_P_DEL="/note/del"; - - public static String NOTEMSG_P_IMPORT="/note/reply/"; - public static String NOTEMSG_G_LIST="/note/reply/list"; - public static String NOTEMSG_G_FIND_BY_ID="/note/reply/"; - public static String NOTEMSG_P_DEL="/note/reply/del"; -} diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/server/SharedLocation.java b/qy/src/main/java/com/qiyou/mb/android/utils/server/SharedLocation.java deleted file mode 100644 index 561c6e1..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/server/SharedLocation.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.qiyou.mb.android.utils.server; - - public class SharedLocation{ - public SharedLocation(){ } - - public double getLat() { - return lat; - } - public void setLat(double lat) { - this.lat = lat; - } - public double getLon() { - return lon; - } - public void setLon(double lon) { - this.lon = lon; - } - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - public float getBear() { - return bear; - } - - public void setBear(float f) { - this.bear = f; - } - public float getEle() { - return ele; - } - - public void setEle(float ele) { - this.ele = ele; - } - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - public float getSpeed() { - return speed; - } - - public void setSpeed(float speed) { - this.speed = speed; - } - public int getFace() { - return face; - } - - public void setFace(int face) { - this.face = face; - } - public float getDist() { - return dist; - } - - public void setDist(float dist) { - this.dist = dist; - } - - public int getExpired() { - return expired; - } - - public void setExpired(int expired) { - this.expired = expired; - } - - private double lat; - private double lon; - private float speed; - private long time; - private float ele; - private float bear; - private int type; //0: normal, 1:sos - private String msg; - private String name; //account - private int id; //user id - private int face; //face icon - private float dist; - private int expired; //expired in xx hours - -} \ No newline at end of file diff --git a/qy/src/main/java/com/qiyou/mb/android/utils/trackTransform.java b/qy/src/main/java/com/qiyou/mb/android/utils/trackTransform.java deleted file mode 100644 index 0722060..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/utils/trackTransform.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.qiyou.mb.android.utils; - -public class trackTransform { - public static final String dTAG ="com.qiyou"; - public static final String TAG ="com.qiyou.utils.trackTransform"; - - - -} diff --git a/qy/src/main/java/com/qiyou/mb/android/wxapi/WXEntryActivity.java b/qy/src/main/java/com/qiyou/mb/android/wxapi/WXEntryActivity.java deleted file mode 100644 index f197818..0000000 --- a/qy/src/main/java/com/qiyou/mb/android/wxapi/WXEntryActivity.java +++ /dev/null @@ -1,8 +0,0 @@ - -package com.qiyou.mb.android.wxapi; - -import com.umeng.socialize.weixin.view.WXCallbackActivity; - -public class WXEntryActivity extends WXCallbackActivity { - -} diff --git a/qy/src/main/java/org/alternativevision/gpx/GPXConstants.java b/qy/src/main/java/org/alternativevision/gpx/GPXConstants.java deleted file mode 100644 index c4d3da2..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/GPXConstants.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * GPXConstants.java - * - * Copyright (c) 2012-2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx; - -public interface GPXConstants { - /*GPX file header constants*/ - public static final String XMLNS_ATTR = "xmlns"; - public static final String XMLNS_1_1_VALUE = "http://www.topografix.com/GPX/1/1"; - public static final String XMLNS_XSI_ATTR = "xmlns:xsi"; - public static final String XMLNS_XSI_1_1_VALUE = "http://www.w3.org/2001/XMLSchema-instance"; - public static final String XMLNS_XSI_SCHEMALOC_ATTR = "xsi:schemaLocation"; - public static final String XMLNS_XSI_SCHEMALOC_1_1_VALUE = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"; - /*End GPX file header constants*/ - - /*GPX nodes and attributes*/ - public static final String GPX_NODE = "gpx"; - public static final String WPT_NODE = "wpt"; - public static final String TRK_NODE = "trk"; - public static final String VERSION_ATTR = "version"; - public static final String CREATOR_ATTR = "creator"; - /*End GPX nodes and attributes*/ - - /*Waypoint nodes and attributes*/ - public static final String LAT_ATTR = "lat"; - public static final String LON_ATTR = "lon"; - public static final String ELE_NODE = "ele"; - public static final String TIME_NODE = "time"; - public static final String NAME_NODE = "name"; - public static final String CMT_NODE = "cmt"; - public static final String PIC_NODE = "pics"; - public static final String DESC_NODE = "desc"; - public static final String SRC_NODE = "src"; - public static final String MAGVAR_NODE = "magvar"; - public static final String GEOIDHEIGHT_NODE = "geoidheight"; - public static final String LINK_NODE = "link"; - public static final String SYM_NODE = "sym"; - public static final String TYPE_NODE = "type"; - public static final String FIX_NODE = "fix"; - public static final String SAT_NODE = "sat"; - public static final String HDOP_NODE = "hdop"; - public static final String VDOP_NODE = "vdop"; - public static final String PDOP_NODE = "pdop"; - public static final String AGEOFGPSDATA_NODE = "ageofdgpsdata"; - public static final String DGPSID_NODE = "dgpsid"; - public static final String SPEED_NODE = "speed"; - public static final String EXTENSIONS_NODE = "extensions"; - /*End Waypoint nodes and attributes*/ - - /*Track nodes and attributes*/ - public static final String NUMBER_NODE = "number"; - public static final String TRKSEG_NODE = "trkseg"; - public static final String TRKPT_NODE = "trkpt"; - /*End Track nodes and attributes*/ - - /*Route Nodes*/ - public static final String RTE_NODE = "rte"; - public static final String RTEPT_NODE = "rtept"; - /*End route nodes*/ - -} diff --git a/qy/src/main/java/org/alternativevision/gpx/GPXParser.java b/qy/src/main/java/org/alternativevision/gpx/GPXParser.java deleted file mode 100644 index 9e6afbb..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/GPXParser.java +++ /dev/null @@ -1,785 +0,0 @@ -/* - * GPXParser.java - * - * Copyright (c) 2012-2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.TimeZone; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.alternativevision.gpx.beans.GPX; -import org.alternativevision.gpx.beans.Route; -import org.alternativevision.gpx.beans.Track; -import org.alternativevision.gpx.beans.Waypoint; -import org.alternativevision.gpx.extensions.IExtensionParser; -//import org.alternativevision.gpx.log.FacadeLogger; -//import org.alternativevision.gpx.log.ILogger; -import org.alternativevision.gpx.types.FixType; -//import org.apache.log4j.// logger; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import com.qiyou.mb.android.utils.log.QLog; - -/** - *

This class defines methods for parsing and writing gpx files.

- *
- * Usage for parsing a gpx file into a {@link GPX} object:
- * - * GPXParser p = new GPXParser();
- * FileInputStream in = new FileInputStream("inFile.gpx");
- * GPX gpx = p.parseGPX(in);
- *
- *
- * Usage for writing a {@link GPX} object to a file:
- * - * GPXParser p = new GPXParser();
- * FileOutputStream out = new FileOutputStream("outFile.gpx");
- * p.writeGPX(gpx, out);
- * out.close();
- *
- */ -public class GPXParser { - - private ArrayList extensionParsers = new ArrayList(); - - /** - * Adds a new extension parser to be used when parsing a gpx steam - * - * @param parser an instance of a {@link IExtensionParser} implementation - */ - public void addExtensionParser(IExtensionParser parser) { - extensionParsers.add(parser); - } - - /** - * Removes an extension parser previously added - * - * @param parser an instance of a {@link IExtensionParser} implementation - */ - public void removeExtensionParser(IExtensionParser parser) { - extensionParsers.remove(parser); - } - -// private ILogger // logger = FacadeLogger.getInstance().getLogger(this.getClass().getName()); - - /** - * Parses a stream containing GPX data - * - * @param in the input stream - * @return {@link GPX} object containing parsed data, or null if no gpx data was found in the seream - * @throws ParserConfigurationException - * @throws SAXException - * @throws IOException - */ - public GPX parseGPX(InputStream in) throws ParserConfigurationException, SAXException, IOException { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.parse(in); - Node firstChild = doc.getFirstChild(); - if( firstChild != null && GPXConstants.GPX_NODE.equals(firstChild.getNodeName())) { - GPX gpx = new GPX(); - NamedNodeMap attrs = firstChild.getAttributes(); - for(int idx = 0; idx < attrs.getLength(); idx++) { - Node attr = attrs.item(idx); - if(GPXConstants.VERSION_ATTR.equals(attr.getNodeName())) { - gpx.setVersion(attr.getNodeValue()); - } else if(GPXConstants.CREATOR_ATTR.equals(attr.getNodeName())) { - gpx.setCreator(attr.getNodeValue()); - } - } - NodeList nodes = firstChild.getChildNodes(); - // logger.debug("Found " +nodes.getLength()+ " child nodes. Start parsing ..."); - for(int idx = 0; idx < nodes.getLength(); idx++) { - Node currentNode = nodes.item(idx); - if(GPXConstants.WPT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("Found waypoint node. Start parsing..."); - Waypoint w = parseWaypoint(currentNode); - if(w!= null) { -// logger.info("Add waypoint to gpx data. [waypointName="+ w.getName() + "]"); - gpx.addWaypoint(w); - } - } else if(GPXConstants.TRK_NODE.equals(currentNode.getNodeName())) { - // logger.debug("Found track node. Start parsing..."); - Track trk = parseTrack(currentNode); - if(trk!= null) { - // logger.info("Add track to gpx data. [trackName="+ trk.getName() + "]"); - gpx.addTrack(trk); - gpx.setCreator(trk.getName()); - } - } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { - // logger.debug("Found extensions node. Start parsing..."); - - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - IExtensionParser parser = it.next(); - Object data = parser.parseGPXExtension(currentNode); - gpx.addExtensionData(parser.getId(), data); - } - } else if(GPXConstants.RTE_NODE.equals(currentNode.getNodeName())) { - // logger.debug("Found route node. Start parsing..."); - Route rte = parseRoute(currentNode); - if(rte!= null) { - // logger.info("Add route to gpx data. [routeName="+ rte.getName() + "]"); - gpx.addRoute(rte); - } - } - } - //TODO: parse route node - return gpx; - } else { - // logger.error("FATAL!! - Root node is not gpx."); - } - return null; - } - - /** - * Parses a wpt node into a Waypoint object - * - * @param node - * @return Waypoint object with info from the received node - */ - private Waypoint parseWaypoint(Node node) { - if(node == null) { - // logger.error("null node received"); - return null; - } - Waypoint w = new Waypoint(); - NamedNodeMap attrs = node.getAttributes(); - //check for lat attribute - Node latNode = attrs.getNamedItem(GPXConstants.LAT_ATTR); - if(latNode != null) { - Double latVal = null; - try { - latVal = Double.parseDouble(latNode.getNodeValue()); - } catch(NumberFormatException ex) { - // logger.error("bad lat value in waypoint data: " + latNode.getNodeValue()); - } - w.setLatitude(latVal); - } else { - // logger.warn("no lat value in waypoint data."); - } - //check for lon attribute - Node lonNode = attrs.getNamedItem(GPXConstants.LON_ATTR); - if(lonNode != null) { - Double lonVal = null; - try { - lonVal = Double.parseDouble(lonNode.getNodeValue()); - } catch(NumberFormatException ex) { - // logger.error("bad lon value in waypoint data: " + lonNode.getNodeValue()); - } - w.setLongitude(lonVal); - } else { - // logger.warn("no lon value in waypoint data."); - } - - NodeList childNodes = node.getChildNodes(); - if(childNodes != null) { - for(int idx = 0; idx < childNodes.getLength(); idx++) { - Node currentNode = childNodes.item(idx); - if(GPXConstants.ELE_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found ele node in waypoint data"); - w.setElevation(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.TIME_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found time node in waypoint data"); - w.setTime(getNodeValueAsDate(currentNode)); - } else if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found name node in waypoint data"); - w.setName(getNodeValueAsString(currentNode)); - } else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found cmt node in waypoint data"); - w.setComment(getNodeValueAsString(currentNode)); - QLog.getLogger().d("GPXParser", w.getComment()); - } else if(GPXConstants.PIC_NODE.equals(currentNode.getNodeName())) { - w.setPics(getNodeValueAsString(currentNode)); - QLog.getLogger().d("GPXParser", w.getPics()); - } else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found desc node in waypoint data"); - w.setDescription(getNodeValueAsString(currentNode)); - } else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found src node in waypoint data"); - w.setSrc(getNodeValueAsString(currentNode)); - } else if(GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found magvar node in waypoint data"); - w.setMagneticDeclination(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found geoidheight node in waypoint data"); - w.setGeoidHeight(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found link node in waypoint data"); - //TODO: parse link - //w.setGeoidHeight(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found sym node in waypoint data"); - w.setSym(getNodeValueAsString(currentNode)); - } else if(GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found fix node in waypoint data"); - w.setFix(getNodeValueAsFixType(currentNode)); - } else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found type node in waypoint data"); - w.setType(getNodeValueAsString(currentNode)); - } else if(GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found sat node in waypoint data"); - w.setSat(getNodeValueAsInteger(currentNode)); - } else if(GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found hdop node in waypoint data"); - w.setHdop(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found vdop node in waypoint data"); - w.setVdop(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found pdop node in waypoint data"); - w.setPdop(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found ageofgpsdata node in waypoint data"); - w.setAgeOfGPSData(getNodeValueAsDouble(currentNode)); - } else if(GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found dgpsid node in waypoint data"); - w.setDgpsid(getNodeValueAsInteger(currentNode)); - } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found extensions node in waypoint data"); - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - IExtensionParser parser = it.next(); - Object data = parser.parseWaypointExtension(currentNode); - w.addExtensionData(parser.getId(), data); - } - } else if(GPXConstants.SPEED_NODE.equals(currentNode.getNodeName())) { - // logger.debug("found speed node in waypoint data"); - w.setSpeed(getNodeValueAsDouble(currentNode)); - } - } - } else { - // logger.debug("no child nodes found in waypoint"); - } - - return w; - } - - private Track parseTrack(Node node) { - if(node == null) { - // logger.error("null node received"); - return null; - } - Track trk = new Track(); - NodeList nodes = node.getChildNodes(); - if(nodes != null) { - for(int idx = 0; idx < nodes.getLength(); idx++) { - Node currentNode = nodes.item(idx); - if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node name found"); - trk.setName(getNodeValueAsString(currentNode)); - } else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node cmt found"); - trk.setComment(getNodeValueAsString(currentNode)); - } else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node desc found"); - trk.setDescription(getNodeValueAsString(currentNode)); - } else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node src found"); - trk.setSrc(getNodeValueAsString(currentNode)); - } else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node link found"); - //TODO: parse link - //trk.setLink(getNodeValueAsLink(currentNode)); - } else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) { - // // logger.debug("node number found"); - trk.setNumber(getNodeValueAsInteger(currentNode)); - } else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node type found"); - trk.setType(getNodeValueAsString(currentNode)); - } else if(GPXConstants.TRKSEG_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node trkseg found"); - trk.setTrackPoints(parseTrackSeg(currentNode)); - } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - // logger.debug("node extensions found"); - while(it.hasNext()) { - IExtensionParser parser = it.next(); - Object data = parser.parseTrackExtension(currentNode); - trk.addExtensionData(parser.getId(), data); - } - } - } - } - } - - return trk; - } - - - private Route parseRoute(Node node) { - if(node == null) { - // logger.error("null node received"); - return null; - } - Route rte = new Route(); - NodeList nodes = node.getChildNodes(); - if(nodes != null) { - for(int idx = 0; idx < nodes.getLength(); idx++) { - Node currentNode = nodes.item(idx); - if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node name found"); - rte.setName(getNodeValueAsString(currentNode)); - } else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node cmt found"); - rte.setComment(getNodeValueAsString(currentNode)); - } else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node desc found"); - rte.setDescription(getNodeValueAsString(currentNode)); - } else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node src found"); - rte.setSrc(getNodeValueAsString(currentNode)); - } else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node link found"); - //TODO: parse link - //rte.setLink(getNodeValueAsLink(currentNode)); - } else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node number found"); - rte.setNumber(getNodeValueAsInteger(currentNode)); - } else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node type found"); - rte.setType(getNodeValueAsString(currentNode)); - } else if(GPXConstants.RTEPT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node rtept found"); - Waypoint wp = parseWaypoint(currentNode); - if(wp!=null) { - rte.addRoutePoint(wp); - } - } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - // logger.debug("node extensions found"); - while(it.hasNext()) { - IExtensionParser parser = it.next(); - Object data = parser.parseRouteExtension(currentNode); - rte.addExtensionData(parser.getId(), data); - } - } - } - } - } - - return rte; - } - - private ArrayList parseTrackSeg(Node node) { - if(node == null) { - // logger.error("null node received"); - return null; - } - ArrayList trkpts = new ArrayList(); - - NodeList nodes = node.getChildNodes(); - if(nodes != null) { - for(int idx = 0; idx < nodes.getLength(); idx++) { - Node currentNode = nodes.item(idx); - if(GPXConstants.TRKPT_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node name found"); - Waypoint wp = parseWaypoint(currentNode); - if(wp!=null) { - trkpts.add(wp); - } - } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { - // logger.debug("node extensions found"); - /* - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - IExtensionParser parser = it.next(); - Object data = parser.parseWaypointExtension(currentNode); - //.addExtensionData(parser.getId(), data); - } - */ - } - } - } - return trkpts; - } - - private Double getNodeValueAsDouble(Node node) { - Double val = null; - try { - val = Double.parseDouble(node.getFirstChild().getNodeValue()); - } catch (Exception ex) { - // logger.error("error parsing Double value form node. val=" + node.getNodeValue(), ex); - } - return val; - } - - private Date getNodeValueAsDate(Node node) { - //2012-02-25T09:28:45Z - Date val = null; - try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss"); - val = sdf.parse(node.getFirstChild().getNodeValue()); - } catch (Exception ex) { - // logger.error("error parsing Date value form node. val=" + node.getNodeName(), ex); - } - return val; - } - - private String getNodeValueAsString(Node node) { - String val = null; - try { - val = node.getFirstChild().getNodeValue(); - } catch (Exception ex) { - // logger.error("error getting String value form node. val=" + node.getNodeName(), ex); - } - return val; - } - - private FixType getNodeValueAsFixType(Node node) { - FixType val = null; - try { - val = FixType.returnType(node.getFirstChild().getNodeValue()); - } catch (Exception ex) { - // logger.error("error getting FixType value form node. val=" + node.getNodeName(), ex); - } - return val; - } - - private Integer getNodeValueAsInteger(Node node) { - Integer val = null; - try { - val = Integer.parseInt(node.getFirstChild().getNodeValue()); - } catch (Exception ex) { - // logger.error("error parsing Integer value form node. val=" + node.getNodeValue(), ex); - } - return val; - } - - public void writeGPX(GPX gpx, OutputStream out) throws ParserConfigurationException, TransformerException { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.newDocument(); - Node gpxNode = doc.createElement(GPXConstants.GPX_NODE); - addBasicGPXInfoToNode(gpx, gpxNode, doc); - if(gpx.getWaypoints() != null) { - // logger.debug("Waypoints Found. Begin writing data to stream"); - Iterator itW = gpx.getWaypoints().iterator(); - while(itW.hasNext()) { - addWaypointToGPXNode(itW.next(), gpxNode, doc); - } - // logger.debug("Waypoints Found. End writing data to stream"); - } - if(gpx.getTracks() != null) { - // logger.debug("Tracks Found. Begin writing data to stream"); - Iterator itT = gpx.getTracks().iterator(); - while(itT.hasNext()) { - addTrackToGPXNode(itT.next(), gpxNode, doc); - } - // logger.debug("Tracks Found. End writing data to stream"); - } - if(gpx.getRoutes() != null) { - // logger.debug("Routes Found. Begin writing data to stream"); - Iterator itR = gpx.getRoutes().iterator(); - while(itR.hasNext()) { - addRouteToGPXNode(itR.next(), gpxNode, doc); - } - // logger.debug("Routes Found. End writing data to stream"); - } - - doc.appendChild(gpxNode); - - // logger.debug("Initialize transformer"); - // Use a Transformer for output - TransformerFactory tFactory = TransformerFactory.newInstance(); - Transformer transformer = tFactory.newTransformer(); - - DOMSource source = new DOMSource(doc); - StreamResult result = new StreamResult(out); - // logger.debug("Begin transform"); - transformer.transform(source, result); - // logger.debug("End Transform"); - } - - private void addWaypointToGPXNode(Waypoint wpt, Node gpxNode, Document doc) { - addGenericWaypointToGPXNode(GPXConstants.WPT_NODE, wpt, gpxNode, doc); - } - - private void addGenericWaypointToGPXNode(String tagName,Waypoint wpt, Node gpxNode, Document doc) { - Node wptNode = doc.createElement(tagName); - NamedNodeMap attrs = wptNode.getAttributes(); - if(wpt.getLatitude() != null) { - Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR); - latNode.setNodeValue(wpt.getLatitude().toString()); - attrs.setNamedItem(latNode); - } - if(wpt.getLongitude() != null) { - Node longNode = doc.createAttribute(GPXConstants.LON_ATTR); - longNode.setNodeValue(wpt.getLongitude().toString()); - attrs.setNamedItem(longNode); - } - if(wpt.getElevation() != null) { - Node node = doc.createElement(GPXConstants.ELE_NODE); - node.appendChild(doc.createTextNode(wpt.getElevation().toString())); - wptNode.appendChild(node); - } - if(wpt.getTime() != null) { - Node node = doc.createElement(GPXConstants.TIME_NODE); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - node.appendChild(doc.createTextNode(sdf.format(wpt.getTime()))); - wptNode.appendChild(node); - } - if(wpt.getMagneticDeclination() != null) { - Node node = doc.createElement(GPXConstants.MAGVAR_NODE); - node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString())); - wptNode.appendChild(node); - } - if(wpt.getGeoidHeight() != null) { - Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE); - node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString())); - wptNode.appendChild(node); - } - if(wpt.getName() != null) { - Node node = doc.createElement(GPXConstants.NAME_NODE); - node.appendChild(doc.createTextNode(wpt.getName())); - wptNode.appendChild(node); - } - if(wpt.getComment() != null) { - Node node = doc.createElement(GPXConstants.CMT_NODE); - node.appendChild(doc.createTextNode(wpt.getComment())); - wptNode.appendChild(node); - } - if(wpt.getDescription() != null) { - Node node = doc.createElement(GPXConstants.DESC_NODE); - node.appendChild(doc.createTextNode(wpt.getDescription())); - wptNode.appendChild(node); - } - if(wpt.getSrc() != null) { - Node node = doc.createElement(GPXConstants.SRC_NODE); - node.appendChild(doc.createTextNode(wpt.getSrc())); - wptNode.appendChild(node); - } - //TODO: write link node - if(wpt.getSym() != null) { - Node node = doc.createElement(GPXConstants.SYM_NODE); - node.appendChild(doc.createTextNode(wpt.getSym())); - wptNode.appendChild(node); - } - if(wpt.getType() != null) { - Node node = doc.createElement(GPXConstants.TYPE_NODE); - node.appendChild(doc.createTextNode(wpt.getType())); - wptNode.appendChild(node); - } - if(wpt.getFix() != null) { - Node node = doc.createElement(GPXConstants.FIX_NODE); - node.appendChild(doc.createTextNode(wpt.getFix().toString())); - wptNode.appendChild(node); - } - if(wpt.getSat() != null) { - Node node = doc.createElement(GPXConstants.SAT_NODE); - node.appendChild(doc.createTextNode(wpt.getSat().toString())); - wptNode.appendChild(node); - } - if(wpt.getHdop() != null) { - Node node = doc.createElement(GPXConstants.HDOP_NODE); - node.appendChild(doc.createTextNode(wpt.getHdop().toString())); - wptNode.appendChild(node); - } - if(wpt.getVdop() != null) { - Node node = doc.createElement(GPXConstants.VDOP_NODE); - node.appendChild(doc.createTextNode(wpt.getVdop().toString())); - wptNode.appendChild(node); - } - if(wpt.getPdop() != null) { - Node node = doc.createElement(GPXConstants.PDOP_NODE); - node.appendChild(doc.createTextNode(wpt.getPdop().toString())); - wptNode.appendChild(node); - } - if(wpt.getAgeOfGPSData() != null) { - Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE); - node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString())); - wptNode.appendChild(node); - } - if(wpt.getDgpsid() != null) { - Node node = doc.createElement(GPXConstants.DGPSID_NODE); - node.appendChild(doc.createTextNode(wpt.getDgpsid().toString())); - wptNode.appendChild(node); - } - if(wpt.getExtensionsParsed() > 0) { - Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - it.next().writeWaypointExtensionData(node, wpt, doc); - } - wptNode.appendChild(node); - } - gpxNode.appendChild(wptNode); - } - - private void addTrackToGPXNode(Track trk, Node gpxNode, Document doc) { - Node trkNode = doc.createElement(GPXConstants.TRK_NODE); - - if(trk.getName() != null) { - Node node = doc.createElement(GPXConstants.NAME_NODE); - node.appendChild(doc.createTextNode(trk.getName())); - trkNode.appendChild(node); - } - if(trk.getComment() != null) { - Node node = doc.createElement(GPXConstants.CMT_NODE); - node.appendChild(doc.createTextNode(trk.getComment())); - trkNode.appendChild(node); - } - if(trk.getDescription() != null) { - Node node = doc.createElement(GPXConstants.DESC_NODE); - node.appendChild(doc.createTextNode(trk.getDescription())); - trkNode.appendChild(node); - } - if(trk.getSrc() != null) { - Node node = doc.createElement(GPXConstants.SRC_NODE); - node.appendChild(doc.createTextNode(trk.getSrc())); - trkNode.appendChild(node); - } - //TODO: write link - if(trk.getNumber() != null) { - Node node = doc.createElement(GPXConstants.NUMBER_NODE); - node.appendChild(doc.createTextNode(trk.getNumber().toString())); - trkNode.appendChild(node); - } - if(trk.getType() != null) { - Node node = doc.createElement(GPXConstants.TYPE_NODE); - node.appendChild(doc.createTextNode(trk.getType())); - trkNode.appendChild(node); - } - if(trk.getExtensionsParsed() > 0) { - Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - it.next().writeTrackExtensionData(node, trk, doc); - } - trkNode.appendChild(node); - } - if(trk.getTrackPoints() != null) { - Node trksegNode = doc.createElement(GPXConstants.TRKSEG_NODE); - Iterator it = trk.getTrackPoints().iterator(); - while(it.hasNext()) { - addGenericWaypointToGPXNode(GPXConstants.TRKPT_NODE, it.next(), trksegNode, doc); - } - trkNode.appendChild(trksegNode); - } - gpxNode.appendChild(trkNode); - } - - private void addRouteToGPXNode(Route rte, Node gpxNode, Document doc) { - Node trkNode = doc.createElement(GPXConstants.RTE_NODE); - - if(rte.getName() != null) { - Node node = doc.createElement(GPXConstants.NAME_NODE); - node.appendChild(doc.createTextNode(rte.getName())); - trkNode.appendChild(node); - } - if(rte.getComment() != null) { - Node node = doc.createElement(GPXConstants.CMT_NODE); - node.appendChild(doc.createTextNode(rte.getComment())); - trkNode.appendChild(node); - } - if(rte.getDescription() != null) { - Node node = doc.createElement(GPXConstants.DESC_NODE); - node.appendChild(doc.createTextNode(rte.getDescription())); - trkNode.appendChild(node); - } - if(rte.getSrc() != null) { - Node node = doc.createElement(GPXConstants.SRC_NODE); - node.appendChild(doc.createTextNode(rte.getSrc())); - trkNode.appendChild(node); - } - //TODO: write link - if(rte.getNumber() != null) { - Node node = doc.createElement(GPXConstants.NUMBER_NODE); - node.appendChild(doc.createTextNode(rte.getNumber().toString())); - trkNode.appendChild(node); - } - if(rte.getType() != null) { - Node node = doc.createElement(GPXConstants.TYPE_NODE); - node.appendChild(doc.createTextNode(rte.getType())); - trkNode.appendChild(node); - } - if(rte.getExtensionsParsed() > 0) { - Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - it.next().writeRouteExtensionData(node, rte, doc); - } - trkNode.appendChild(node); - } - if(rte.getRoutePoints() != null) { - Iterator it = rte.getRoutePoints().iterator(); - while(it.hasNext()) { - addGenericWaypointToGPXNode(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc); - } - } - gpxNode.appendChild(trkNode); - } - - private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) { - NamedNodeMap attrs = gpxNode.getAttributes(); - - Node xmlnsNode = doc.createAttribute(GPXConstants.XMLNS_ATTR); - xmlnsNode.setNodeValue(GPXConstants.XMLNS_1_1_VALUE); - attrs.setNamedItem(xmlnsNode); - - Node xmlnsXsiNode = doc.createAttribute(GPXConstants.XMLNS_XSI_ATTR); - xmlnsXsiNode.setNodeValue(GPXConstants.XMLNS_XSI_1_1_VALUE); - attrs.setNamedItem(xmlnsXsiNode); - - Node xmlnsXsiSLocNode = doc.createAttribute(GPXConstants.XMLNS_XSI_SCHEMALOC_ATTR); - xmlnsXsiSLocNode.setNodeValue(GPXConstants.XMLNS_XSI_SCHEMALOC_1_1_VALUE); - attrs.setNamedItem(xmlnsXsiSLocNode); - - if(gpx.getVersion() != null) { - Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR); - verNode.setNodeValue(gpx.getVersion()); - attrs.setNamedItem(verNode); - } - if(gpx.getCreator() != null) { - Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR); - creatorNode.setNodeValue(gpx.getCreator()); - attrs.setNamedItem(creatorNode); - } - - if(gpx.getExtensionsParsed() > 0) { - Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); - Iterator it = extensionParsers.iterator(); - while(it.hasNext()) { - it.next().writeGPXExtensionData(node, gpx, doc); - } - gpxNode.appendChild(node); - } - } -} \ No newline at end of file diff --git a/qy/src/main/java/org/alternativevision/gpx/beans/Extension.java b/qy/src/main/java/org/alternativevision/gpx/beans/Extension.java deleted file mode 100644 index cd2a742..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/beans/Extension.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Extension.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.beans; - -import java.util.HashMap; - -/** - * This class holds generic extension information from any node that can have extensions defined. - *
- *

Any custom extension parser used when parsing a gpx file will return a custom object - * instance that will be kept in properties defined in this class.

- *
- *

Multiple extension parsers can be used when parsing. Every extension parser defines - * an unique id that will be used as a HashMap key for the parsed object values.

- */ -public class Extension { - protected HashMap extensionData; - - public HashMap getExtensionData() { - return extensionData; - } - - /** - * Setter for extension HashMap. - * @param extensionData - A HashMap with extensions parser ids as keys and parsed objects as values. - */ - public void setExtensionData(HashMap extensionData) { - this.extensionData = extensionData; - } - - - /** - * Adds a new parsed extension object into the extension data with the key set by parserId. - * - * @param parserId a unique key representing the id of he extension parser used. - * @param data an object holding the parsed information. This can be any object type and it is - * the extension parser's job to set it properly. - */ - public void addExtensionData(String parserId, Object data) { - if(extensionData == null) { - extensionData = new HashMap(); - } - extensionData.put(parserId, data); - } - - /** - * Returns the extension data parsed by the extension parser with id parserId - * @param parserId a String representing the id of an extension parser - * @return the extension data parsed by the extension parser with id parserId - */ - public Object getExtensionData(String parserId) { - if(extensionData != null) { - return extensionData.get(parserId); - } else { - return null; - } - } - - /** - * Returns the number of extension data objects that are currently set. - * @return the number of extension data objects that are currently set. - */ - public int getExtensionsParsed() { - if(extensionData != null) { - return extensionData.size(); - } else { - return 0; - } - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/beans/GPX.java b/qy/src/main/java/org/alternativevision/gpx/beans/GPX.java deleted file mode 100644 index 788bb1c..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/beans/GPX.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * GPX.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.beans; - -import java.util.HashSet; -/** - * This class holds gpx information from a <gpx> node. - *
- *

GPX specification for this tag:

- * - * <gpx version="1.1" creator=""xsd:string [1]">
- *    <metadata> xsd:string </metadata> [0..1]
- *    <wpt> xsd:string </wpt> [0..1]
- *    <rte> xsd:string </rte> [0..1]
- *    <trk> xsd:string </trk> [0..1]
- *    <extensions> extensionsType </extensions> [0..1]
- * </gpx>
- *
- */ -public class GPX extends Extension{ - - - private String version; - private String creator; - private HashSet waypoints; - private HashSet tracks; - private HashSet routes; - - /** - * Returns the version of a gpx object - * @return A String representing the version of this gpx object - */ - public String getVersion() { - return version; - } - - /** - * Setter for gpx version property. This maps to version attribute value. - * @param version A String representing the version of a gpx file. - */ - public void setVersion(String version) { - this.version = version; - } - - /** - * Returns the creator of this gpx object - * @return A String representing the creator of a gpx object - */ - public String getCreator() { - return creator; - } - - /** - * Setter for gpx creator property. This maps to creator attribute value. - * @param creator A String representing the creator of a gpx file. - */ - public void setCreator(String creator) { - this.creator = creator; - } - - /** - * Getter for the list of waypoints from a gpx objecty - * @return a HashSet of {@link Waypoint} - */ - public HashSet getWaypoints() { - return waypoints; - } - - /** - * Setter for the list of waypoints from a gpx object - * @param waypoints a HashSet of {@link Waypoint} - */ - public void setWaypoints(HashSet waypoints) { - this.waypoints = waypoints; - } - - /** - * Getter for the list of Tracks from a gpx objecty - * @return a HashSet of {@link Track} - */ - public HashSet getTracks() { - return tracks; - } - - /** - * Setter for the list of tracks from a gpx object - * @param tracks a HashSet of {@link Track} - */ - public void setTracks(HashSet tracks) { - this.tracks = tracks; - } - - /** - * Getter for the list of routes from a gpx object - * @return a HashSet of {@link Route} - */ - public HashSet getRoutes() { - return routes; - } - - /** - * Setter for the list of routes from a gpx object - * @param routes a HashSet of {@link Route} - */ - public void setRoutes(HashSet routes) { - this.routes = routes; - } - - /** - * Adds a new waypoint to a gpx object - * @param waypoint a {@link Waypoint} - */ - public void addWaypoint(Waypoint waypoint) { - if(waypoints == null) { - waypoints = new HashSet(); - } - waypoints.add(waypoint); - - } - - /** - * Adds a new track to a gpx object - * @param track a {@link Track} - */ - public void addTrack(Track track) { - if(tracks == null) { - tracks = new HashSet(); - } - tracks.add(track); - } - - /** - * Adds a new Route to a gpx object - * @param route a {@link Route} - */ - public void addRoute(Route route) { - if(routes == null) { - routes = new HashSet(); - } - routes.add(route); - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/beans/Route.java b/qy/src/main/java/org/alternativevision/gpx/beans/Route.java deleted file mode 100644 index ded1640..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/beans/Route.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Route.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.beans; - -import java.util.ArrayList; - -/** - * This class holds route information from a <rte> node. - *
- *

GPX specification for this tag:

- * - * <rte>
- *    <name> xsd:string </name> [0..1]
- *    <cmt> xsd:string </cmt> [0..1]
- *    <desc> xsd:string </desc> [0..1]
- *    <src> xsd:string </src> [0..1]
- *    <link> linkType </link> [0..*]
- *    <number> xsd:nonNegativeInteger </number> [0..1]
- *    <type> xsd:string </type> [0..1]
- *    <extensions> extensionsType </extensions> [0..1]
- *    <rtept> wptType </rtept> [0..*]
- * </rte>
- *
- */ -public class Route extends Extension { - private String name; - private String comment; - private String description; - private String src; - private Integer number; - private String type; - private ArrayList routePoints; - - /** - * Returns the name of this route. - * @return A String representing the name of this route. - */ - public String getName() { - return name; - } - - /** - * Setter for route name property. This maps to <name> tag value. - * @param name A String representing the name of this route. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the comment of this route. - * @return A String representing the comment of this route. - */ - public String getComment() { - return comment; - } - - /** - * Setter for route comment property. This maps to <comment> tag value. - * @param comment A String representing the comment of this route. - */ - public void setComment(String comment) { - this.comment = comment; - } - - /** - * Returns the description of this route. - * @return A String representing the description of this route. - */ - public String getDescription() { - return description; - } - - /** - * Setter for route description property. This maps to <description> tag value. - * @param description A String representing the description of this route. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the src of this route. - * @return A String representing the src of this route. - */ - public String getSrc() { - return src; - } - - /** - * Setter for src type property. This maps to <src> tag value. - * @param src A String representing the src of this route. - */ - public void setSrc(String src) { - this.src = src; - } - - /** - * Returns the number of this route. - * @return A String representing the number of this route. - */ - public Integer getNumber() { - return number; - } - - /** - * Setter for route number property. This maps to <number> tag value. - * @param number An Integer representing the number of this route. - */ - public void setNumber(Integer number) { - this.number = number; - } - - /** - * Returns the type of this route. - * @return A String representing the type of this route. - */ - public String getType() { - return type; - } - - /** - * Setter for route type property. This maps to <type> tag value. - * @param type A String representing the type of this route. - */ - public void setType(String type) { - this.type = type; - } - - /** - * Getter for the list of waypoints of this route. - * @return an ArrayList of {@link Waypoint} representing the points of the route. - */ - public ArrayList getRoutePoints() { - return routePoints; - } - - /** - * Setter for the list of waypoints of this route. - * @param routePoints an ArrayList of {@link Waypoint} representing the points of the route. - */ - public void setRoutePoints(ArrayList routePoints) { - this.routePoints = routePoints; - } - - /** - * Adds this new waypoint to this route. - * @param waypoint a {@link Waypoint}. - */ - public void addRoutePoint(Waypoint waypoint) { - if(routePoints == null) { - routePoints = new ArrayList(); - } - routePoints.add(waypoint); - } - - /** - * Returns a String representation of this track. - */ - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("rte["); - sb.append("name:" + name +" "); - int points = 0; - if(routePoints!= null) { - points = routePoints.size(); - } - sb.append("rtepts:" + points +" "); - sb.append("]"); - return sb.toString(); - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/beans/RoutePoint.java b/qy/src/main/java/org/alternativevision/gpx/beans/RoutePoint.java deleted file mode 100644 index f8b0ce3..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/beans/RoutePoint.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * RoutePoint.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.beans; - -/** - * Defines additional route point information that {@link Waypoint} doesn't define. - *
- * It is currently not used. - */ -public class RoutePoint extends Waypoint{ - -} diff --git a/qy/src/main/java/org/alternativevision/gpx/beans/Track.java b/qy/src/main/java/org/alternativevision/gpx/beans/Track.java deleted file mode 100644 index 4e527e9..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/beans/Track.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Track.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.beans; - -import java.util.ArrayList; -/** - * This class holds track information from a <trk> node. - *
- *

GPX specification for this tag:

- * - * <trk>
- *    <name> xsd:string </name> [0..1]
- *    <cmt> xsd:string </cmt> [0..1]
- *    <desc> xsd:string </desc> [0..1]
- *    <src> xsd:string </src> [0..1]
- *    <link> linkType </link> [0..*]
- *    <number> xsd:nonNegativeInteger </number> [0..1]
- *    <type> xsd:string </type> [0..1]
- *    <extensions> extensionsType </extensions> [0..1]
- *    <trkseg> trksegType </trkseg> [0..*]
- * </trk>
- *
- */ -public class Track extends Extension{ - /* - xsd:string [0..1] ? - xsd:string [0..1] ? - xsd:string [0..1] ? - xsd:string [0..1] ? - linkType [0..*] ? - xsd:nonNegativeInteger [0..1] ? - xsd:string [0..1] ? - extensionsType [0..1] ? - trksegType [0..*] ? - */ - private String name; - private String comment; - private String description; - private String src; - private Integer number; - private String type; - private ArrayList trackPoints; - - /** - * Returns the name of this track. - * @return A String representing the name of this track. - */ - public String getName() { - return name; - } - - /** - * Setter for track name property. This maps to <name> tag value. - * @param name A String representing the name of this track. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the comment of this track. - * @return A String representing the comment of this track. - */ - public String getComment() { - return comment; - } - - /** - * Setter for track comment property. This maps to <comment> tag value. - * @param comment A String representing the comment of this track. - */ - public void setComment(String comment) { - this.comment = comment; - } - - /** - * Returns the description of this track. - * @return A String representing the description of this track. - */ - public String getDescription() { - return description; - } - - /** - * Setter for track description property. This maps to <description> tag value. - * @param description A String representing the description of this track. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the src of this track. - * @return A String representing the src of this track. - */ - public String getSrc() { - return src; - } - - /** - * Setter for src type property. This maps to <src> tag value. - * @param src A String representing the src of this track. - */ - public void setSrc(String src) { - this.src = src; - } - - /** - * Returns the number of this track. - * @return A String representing the number of this track. - */ - public Integer getNumber() { - return number; - } - - /** - * Setter for track number property. This maps to <number> tag value. - * @param number An Integer representing the number of this track. - */ - public void setNumber(Integer number) { - this.number = number; - } - - /** - * Returns the type of this track. - * @return A String representing the type of this track. - */ - public String getType() { - return type; - } - - /** - * Setter for track type property. This maps to <type> tag value. - * @param type A String representing the type of this track. - */ - public void setType(String type) { - this.type = type; - } - - /** - * Getter for the list of waypoints of a track. - * @return an ArrayList of {@link Waypoint} representing the points of the track. - */ - public ArrayList getTrackPoints() { - return trackPoints; - } - - /** - * Setter for the list of waypoints of a track. - * @param trackPoints an ArrayList of {@link Waypoint} representing the points of the track. - */ - public void setTrackPoints(ArrayList trackPoints) { - this.trackPoints = trackPoints; - } - - /** - * Returns a String representation of this track. - */ - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("trk["); - sb.append("name:" + name +" "); - int points = 0; - if(trackPoints!= null) { - points = trackPoints.size(); - } - sb.append("trkseg:" + points +" "); - sb.append("]"); - return sb.toString(); - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/beans/TrackPoint.java b/qy/src/main/java/org/alternativevision/gpx/beans/TrackPoint.java deleted file mode 100644 index c8bf27f..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/beans/TrackPoint.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * TrackPoint.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.beans; -/** - * Defines additional track point information that {@link Waypoint} doesn't define. - *
- * It is currently not used. - */ -public class TrackPoint extends Waypoint{ - -} diff --git a/qy/src/main/java/org/alternativevision/gpx/beans/Waypoint.java b/qy/src/main/java/org/alternativevision/gpx/beans/Waypoint.java deleted file mode 100644 index f891ec6..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/beans/Waypoint.java +++ /dev/null @@ -1,495 +0,0 @@ -/* - * Waypoint.java - * - * Copyright (c) 2012-2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.beans; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; - -import org.alternativevision.gpx.types.FixType; - -/** - * This class holds waypoint information from a <wpt> node. - *
- *

GPX specification for this tag:

- * - * <wpt
- *    lat="latitudeType [1]"
- *    lon="longitudeType [1]">
- *    <ele> xsd:decimal </ele> [0..1]
- *    <time> xsd:dateTime </time> [0..1]
- *    <magvar> degreesType </magvar> [0..1]
- *    <geoidheight> xsd:decimal </geoidheight> [0..1]
- *    <name> xsd:string </name> [0..1]
- *    <cmt> xsd:string </cmt> [0..1]
- *    <desc> xsd:string </desc> [0..1]
- *    <src> xsd:string </src> [0..1]
- *    <link> linkType </link> [0..*]
- *    <sym> xsd:string </sym> [0..1]
- *    <type> xsd:string </type> [0..1]
- *    <fix> fixType </fix> [0..1]
- *    <sat> xsd:nonNegativeInteger </sat> [0..1]
- *    <hdop> xsd:decimal </hdop> [0..1]
- *    <vdop> xsd:decimal </vdop> [0..1]
- *    <pdop> xsd:decimal </pdop> [0..1]
- *    <ageofdgpsdata> xsd:decimal </ageofdgpsdata> [0..1]
- *    <dgpsid> dgpsStationType </dgpsid> [0..1]
- *    <extensions> extensionsType </extensions> [0..1]
- * </wpt>
- *
- */ -public class Waypoint extends Extension{ - - /* - lat="latitudeType [1] ?" -lon="longitudeType [1] ?"> - xsd:decimal [0..1] ? - [0..1] ? - degreesType [0..1] ? - xsd:decimal [0..1] ? - xsd:string [0..1] ? - xsd:string [0..1] ? - xsd:string [0..1] ? - xsd:string [0..1] ? - linkType [0..*] ? - xsd:string [0..1] ? - xsd:string [0..1] ? - fixType [0..1] ? - xsd:nonNegativeInteger [0..1] ? - xsd:decimal [0..1] ? - xsd:decimal [0..1] ? - xsd:decimal [0..1] ? - xsd:decimal [0..1] ? - dgpsStationType [0..1] ? - extensionsType [0..1] ? - */ - private Double latitude=0d; - private Double longitude=0d; - private Double elevation=0d; - private Date time; - private Double magneticDeclination; - private Double geoidHeight; - private String name; - private String comment; - private String description; - private String src; - private String sym; - private String type; - private FixType fix; - private Integer sat; - private Double hdop; - private Double vdop; - private Double pdop; - private Double ageOfGPSData; - private Integer dgpsid; - private Double speed=0d; - private String pics; - - /** - * Returns the latitude of this waypoint. - * @return a Double value representing the latitude of this waypoint. - */ - public Double getLatitude() { - return latitude; - } - - /** - * Setter for waypoint latitude property. This maps to "lat" attribute value. - * @param latitude a Doube value representing the latitude of this waypoint. - */ - public void setLatitude(Double latitude) { - this.latitude = latitude; - } - - /** - * Returns the longitude of this waypoint. - * @return a Double value representing the longitude of this waypoint. - */ - public Double getLongitude() { - return longitude; - } - - /** - * Setter for waypoint longitude property. This maps to "long" attribute value. - * @param longitude a Doube value representing the longitude of this waypoint. - */ - public void setLongitude(Double longitude) { - this.longitude = longitude; - } - - /** - * Returns the elevation of this waypoint. - * @return A Double representing the elevation of this waypoint. - */ - public Double getElevation() { - return elevation; - } - - /** - * Setter for waypoint elevation property. This maps to <ele> tag value. - * @param elevation a Double value representing the elevation of this waypoint. - */ - public void setElevation(Double elevation) { - this.elevation = elevation; - } - - /** - * Returns the time of this waypoint. - * @return a Date representing the name of this waypoint. - */ - public Date getTime() { - return time; - } - - /** - * Setter for waypoint time property. This maps to <time> tag value. - * @param time a Date representing the time of this waypoint. - */ - public void setTime(Date time) { - this.time = time; - } - - /** - * Returns the magnetic declination of this waypoint. - * @return A Double representing the magnetic declination of this waypoint. - */ - public Double getMagneticDeclination() { - return magneticDeclination; - } - - /** - * Setter for waypoint magnetic declination property. This maps to <magvar> tag value. - * @param magneticDeclination A String representing the magnetic declination of this waypoint. - */ - public void setMagneticDeclination(Double magneticDeclination) { - this.magneticDeclination = magneticDeclination; - } - - /** - * Returns the geoid height of this waypoint. - * @return A String representing the geoid height of this waypoint. - */ - public Double getGeoidHeight() { - return geoidHeight; - } - - /** - * Setter for waypoint geoid height property. This maps to <geoidheight> tag value. - * @param geoidHeight A String representing the geoid height of this waypoint. - */ - public void setGeoidHeight(Double geoidHeight) { - this.geoidHeight = geoidHeight; - } - - /** - * Returns the name of this waypoint. - * @return A String representing the name of this waypoint. - */ - public String getName() { - return name; - } - - /** - * Setter for waypoint name property. This maps to <name> tag value. - * @param name A String representing the name of this waypoint. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the comment of this waypoint. - * @return a String representing the comment of this waypoint. - */ - public String getComment() { - return comment; - } - - /** - * Setter for waypoint comment property. This maps to <cmt> tag value. - * @param comment A String representing the comment of this waypoint. - */ - public void setComment(String comment) { - this.comment = comment; - } - - /** - * Returns the description of this waypoint. - * @return a String representing the description of this waypoint. - */ - public String getDescription() { - return description; - } - - /** - * Setter for waypoint description property. This maps to <desc> tag value. - * @param description A String representing the description of this waypoint. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the src of this waypoint. - * @return A String representing the src of this waypoint. - */ - public String getSrc() { - return src; - } - - /** - * Setter for waypoint src property. This maps to <src> tag value. - * @param src a String representing the src of this waypoint. - */ - public void setSrc(String src) { - this.src = src; - } - - /** - * Returns the sym of this waypoint. - * @return A String representing the sym of this waypoint. - */ - public String getSym() { - return sym; - } - - /** - * Setter for waypoint sym property. This maps to <sym> tag value. - * @param sym a String representing the sym of this waypoint. - */ - public void setSym(String sym) { - this.sym = sym; - } - - /** - * Returns the type of this waypoint. - * @return A String representing the type of this waypoint. - */ - public String getType() { - return type; - } - - /** - * Setter for waypoint type property. This maps to <type> tag value. - * @param type a String representing the type of this waypoint. - */ - public void setType(String type) { - this.type = type; - } - - /** - * Returns the fix of this waypoint. - * @return A {@link FixType} representing the fix of this waypoint. - */ - public FixType getFix() { - return fix; - } - - /** - * Setter for waypoint fix property. This maps to <fix> tag value. - * @param fix a {@link FixType} representing the fix of this waypoint. - */ - public void setFix(FixType fix) { - this.fix = fix; - } - - /** - * Returns the sat of this waypoint. - * @return an Integer representing the sat of this waypoint. - */ - public Integer getSat() { - return sat; - } - - /** - * Setter for waypoint sat property. This maps to <sat> tag value. - * @param sat an Integer representing the sat of this waypoint. - */ - public void setSat(Integer sat) { - this.sat = sat; - } - - /** - * Returns the hdop of this waypoint. - * @return a Double representing the hdop of this waypoint. - */ - public Double getHdop() { - return hdop; - } - - /** - * Setter for waypoint hdop property. This maps to <hdop> tag value. - * @param hdop a Double representing the name of this waypoint. - */ - public void setHdop(Double hdop) { - this.hdop = hdop; - } - - /** - * Returns the vdop of this waypoint. - * @return a Double representing the vdop of this waypoint. - */ - public Double getVdop() { - return vdop; - } - - /** - * Setter for waypoint vdop property. This maps to <vdop> tag value. - * @param vdop A String representing the vdop of this waypoint. - */ - public void setVdop(Double vdop) { - this.vdop = vdop; - } - - /** - * Returns the pdop of this waypoint. - * @return a Double representing the pdop of this waypoint. - */ - public Double getPdop() { - return pdop; - } - - /** - * Setter for waypoint pdop property. This maps to <pdop> tag value. - * @param pdop a Double representing the pdop of this waypoint. - */ - public void setPdop(Double pdop) { - this.pdop = pdop; - } - - /** - * Returns the ageOfGPSData of this waypoint. - * @return a Double representing the ageOfGPSData of this waypoint. - */ - public Double getAgeOfGPSData() { - return ageOfGPSData; - } - - /** - * Setter for waypoint ageOfGPSData property. This maps to <ageOfGPSData> tag value. - * @param ageOfGPSData A String representing the ageOfGPSData of this waypoint. - */ - public void setAgeOfGPSData(Double ageOfGPSData) { - this.ageOfGPSData = ageOfGPSData; - } - - /** - * Returns the dgpsid of this waypoint. - * @return an Integer representing the dgpsid of this waypoint. - */ - public Integer getDgpsid() { - return dgpsid; - } - - /** - * Setter for waypoint dgpsid property. This maps to <dgpsid> tag value. - * @param dgpsid an Integer representing the dgpsid of this waypoint. - */ - public void setDgpsid(Integer dgpsid) { - this.dgpsid = dgpsid; - } - - /** - * Returns a String representation of this waypoint. - */ - public String toString() { - StringBuffer sb = new StringBuffer(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); - String date=""; - if(time != null) { - date = sdf.format(time); - } - sb.append("["); - sb.append("name:'"+name+"' "); - sb.append("lat:" + latitude + " "); - sb.append("lon:"+longitude + " "); - sb.append("elv:"+elevation +" "); - sb.append("time:"+date+ " "); - sb.append("fix:"+fix+ " "); - if(extensionData != null) { - sb.append("extensions:{"); - Iterator it = extensionData.keySet().iterator(); - while(it.hasNext()) { - sb.append(it.next()); - if(it.hasNext()) { - sb.append(","); - } - } - sb.append("}"); - } - sb.append("]"); - return sb.toString(); - } - - /** - * Computesthe hasCode for this object based on latitude and longitude values - */ - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((getLatitude() == null) ? 0 : getLatitude().hashCode()); - result = prime * result - + ((getLongitude() == null) ? 0 : getLongitude().hashCode()); - return result; - } - - /** - * Compares two {@link Waypoint} objects based on latitude and longitude only - */ - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Waypoint other = (Waypoint) obj; - if (getLatitude() == null) { - if (other.getLatitude() != null) - return false; - } else if (!getLatitude().equals(other.getLatitude())) - return false; - if (getLongitude() == null) { - if (other.getLongitude() != null) - return false; - } else if (!getLongitude().equals(other.getLongitude())) - return false; - return true; - } - - public Double getSpeed() { - return speed; - } - - public void setSpeed(Double speed) { - this.speed = speed; - } - - public String getPics() { - return pics; - } - - public void setPics(String pics) { - this.pics = pics; - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/extensions/DummyExtensionParser.java b/qy/src/main/java/org/alternativevision/gpx/extensions/DummyExtensionParser.java deleted file mode 100644 index 25a4e4e..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/extensions/DummyExtensionParser.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * BasicExtensionParser.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.extensions; - -import org.alternativevision.gpx.beans.GPX; -import org.alternativevision.gpx.beans.Route; -import org.alternativevision.gpx.beans.Track; -import org.alternativevision.gpx.beans.Waypoint; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -public class DummyExtensionParser implements IExtensionParser { - - public String getId() { - return "Basic Extension Parser"; - } - - public Object parseWaypointExtension(Node node) { - return "Parsed Waypoint data"; - } - - public Object parseTrackExtension(Node node) { - return "Parsed Track data"; - } - - public Object parseGPXExtension(Node node) { - return "Parsed GPX data"; - } - - public Object parseRouteExtension(Node node) { - return "Parsed Route data"; - } - - public void writeGPXExtensionData(Node node, GPX wpt, Document doc) { - // TODO Auto-generated method stub - } - - public void writeWaypointExtensionData(Node node, Waypoint wpt, Document doc) { - Node sampleNode = doc.createElement("mySampleExtension"); - sampleNode.setNodeValue("mySampleWaypointValue"); - node.appendChild(sampleNode); - } - - @Override - public void writeTrackExtensionData(Node node, Track wpt, Document doc) { - Node sampleNode = doc.createElement("mySampleExtension"); - sampleNode.setNodeValue("mySampleTrackValue"); - node.appendChild(sampleNode); - - } - - @Override - public void writeRouteExtensionData(Node node, Route wpt, Document doc) { - Node sampleNode = doc.createElement("mySampleExtension"); - sampleNode.setNodeValue("mySampleRouteValue"); - node.appendChild(sampleNode); - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/extensions/IExtensionParser.java b/qy/src/main/java/org/alternativevision/gpx/extensions/IExtensionParser.java deleted file mode 100644 index 2c504e0..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/extensions/IExtensionParser.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * IExtensionParser - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.extensions; - -import org.alternativevision.gpx.beans.GPX; -import org.alternativevision.gpx.beans.Route; -import org.alternativevision.gpx.beans.Track; -import org.alternativevision.gpx.beans.Waypoint; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -/** - * This interface defines extension parsers methods. - *
- *

All custom extension parser must implement this interface.

- *

Any custom parser must be added to {@link org.alternativevision.gpx.GPXParser} as an extension parser - * before parsing a gpx file, or writing a {@link GPX} to a file. This is done by - * calling addExtensionParser() method of {@link org.alternativevision.gpx.GPXParser} - *

{@link org.alternativevision.gpx.GPXParser} parseGPX method calls several methods from the registered - * extension parsers added at different steps of processing:

- *
    - *
  • parseGPXExtension() for parsing <extensions> of a <gpx> node
  • - *
  • parseTrackExtension() for parsing <extensions> of a <trk> node
  • - *
  • parseRouteExtension() for parsing <extensions> of a <rte> node
  • - *
  • parseWaypointExtension() for parsing <extensions> of a <wpt> node
  • - *
- *
- * - *

{@link org.alternativevision.gpx.GPXParser} writeGPX method also calls several methods from the registered - * extensions parsers at different steps of writing data:

- *
    - *
  • writeGPXExtensionData() when writing the <extensions> from the {@link GPX}
  • - *
  • writeTrackExtensionData() when writing the <extensions> from the {@link Track}
  • - *
  • writeRouteExtensionData() when writing the <extensions> from the {@link Route}
  • - *
  • writeWaypointExtensionData() when writing the <extensions> from the {@link Waypoint}
  • - *
- */ -public interface IExtensionParser { - - public String getId(); - - public Object parseWaypointExtension(Node node); - - public Object parseTrackExtension(Node node); - - public Object parseGPXExtension(Node node); - - public Object parseRouteExtension(Node node); - - public void writeGPXExtensionData(Node node, GPX wpt, Document doc); - - public void writeWaypointExtensionData(Node node, Waypoint wpt, Document doc); - - public void writeTrackExtensionData(Node node, Track wpt, Document doc); - - public void writeRouteExtensionData(Node node, Route wpt, Document doc); - -} diff --git a/qy/src/main/java/org/alternativevision/gpx/log/AbstractLogger.java b/qy/src/main/java/org/alternativevision/gpx/log/AbstractLogger.java deleted file mode 100644 index 2fcd831..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/log/AbstractLogger.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.alternativevision.gpx.log; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public abstract class AbstractLogger implements ILogger{ - public String logClassName = ""; - - protected Object log = null; - protected Class logClass = null; - - protected String tag = "GPSParser"; - - protected void setClassName(String name) { - logClassName = name; - } - - protected void init() { - try { - logClass = Class.forName(logClassName); - //log = logClass.newInstance(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - protected void callMethodWithTag(String methodName, String message) { - Method method = null; - try { - method = logClass.getMethod(methodName, String.class, String.class); - method.invoke(log,tag, message); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - protected void callMethodWithTag(String methodName, String message, Throwable th) { - Method method = null; - try { - method = logClass.getMethod(methodName, String.class, String.class, Throwable.class); - method.invoke(log,tag, message, th); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - protected void callMethod(String methodName, String message) { - Method method = null; - try { - method = logClass.getMethod(methodName, String.class); - method.invoke(log, message); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - protected void callMethod(String methodName, String message, Throwable throwable) { - Method method = null; - try { - method = logClass.getMethod(methodName, String.class, Throwable.class); - method.invoke(log, message, throwable); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - protected void callMethod(Object obj, String methodName, Object message) { - Method method = null; - try { - method = logClass.getMethod(methodName, Object.class); - method.invoke(obj, message); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - protected void callMethod(Object obj, String methodName, Object message, Throwable throwable) { - Method method = null; - try { - method = logClass.getMethod(methodName, String.class, Throwable.class); - method.invoke(obj, message, throwable); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - -} diff --git a/qy/src/main/java/org/alternativevision/gpx/log/AndroidLogger.java b/qy/src/main/java/org/alternativevision/gpx/log/AndroidLogger.java deleted file mode 100644 index ddbf097..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/log/AndroidLogger.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * AndroidLogger.java - * - * Copyright (c) 2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package org.alternativevision.gpx.log; - -public class AndroidLogger extends AbstractLogger implements ILogger { - - public static final String logClassName = "android.util.Log"; - private static final String ANDROIDCLASSNAME = "android.util.Log"; - - public AndroidLogger() { - this.tag = "GPXParser"; - setClassName(ANDROIDCLASSNAME); - init(); - } - - public void debug(Object message) { - callMethodWithTag("d", message.toString()); - } - - public void info(Object message) { - callMethodWithTag("i", message.toString()); - } - - public void error(Object message) { - callMethodWithTag("e", message.toString()); - } - - public void error(Object message, Throwable th) { - callMethodWithTag("e", message.toString(),th); - } - - public void warn(Object message) { - callMethodWithTag("w", message.toString()); - } - - public void setTag(String tag) { - this.tag = tag; - } - -} \ No newline at end of file diff --git a/qy/src/main/java/org/alternativevision/gpx/log/DummyLogger.java b/qy/src/main/java/org/alternativevision/gpx/log/DummyLogger.java deleted file mode 100644 index 365d08f..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/log/DummyLogger.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * DummyLogger.java - * - * Copyright (c) 2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.log; - -/** - * This class is used as default Logging Wrapper in case no other wrapper is specified. - * It doesn't output anything. It is just used as a failback mechanism for all the Logging API. - *
- * This Logging Wrapper can also be used in production, where no logs are necessary to be collected. - */ -public class DummyLogger implements ILogger { - - public void debug(Object log) {} - - public void info(Object log) {} - - public void error(Object log) {} - - public void error(Object log, Throwable th) {} - - public void warn(Object log) {} - - public void setTag(String tag) {} - -} diff --git a/qy/src/main/java/org/alternativevision/gpx/log/FacadeLogger.java b/qy/src/main/java/org/alternativevision/gpx/log/FacadeLogger.java deleted file mode 100644 index dbf0192..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/log/FacadeLogger.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * FacadeLogger.java - * - * Copyright (c) 2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package org.alternativevision.gpx.log; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; - -/** - * In order to be mode flexible, an additional logging layer was created. This layer makes logging abstract - * so multiple logging APIs can be used. Each logging API must have a class that implements the {@link ILogger} interface. - *

- * This class initializes the logging system based on the properties set in gpxparser.properties. - * The property logClass needs to point to a fully qualified class name that implement the {@link ILogger} interface. - * Three classes are provided with the mechanism: {@link DummyLogger}, {@link AndroidLogger} and {@link Log4JLogger}. - *
- *
- * You can change the default setting by changing the logClass property value in the gpxparser.properties:
- * - * logClass=com.yourDomain.yourApplication.logging.yourLoggerAPIwrapperClass - * - *
- *
- */ -public class FacadeLogger { - - public static final String DEFAULT_LOGGER = DummyLogger.class.getName(); - - public static final String GPX_PROPERTY_FILE = "gpxparser.properties"; - - public static final String LOG_CLASS_KEY = "logClass"; - - - - private static String loggerClass = null; - - private static FacadeLogger instance = new FacadeLogger(); - - public static FacadeLogger getInstance() { - return instance; - } - - private FacadeLogger() { - try { - init(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - private void init() throws InstantiationException, IllegalAccessException, ClassNotFoundException { - Properties props = new Properties(); - File propertiesFile = new File(GPX_PROPERTY_FILE); - if(propertiesFile.exists()) { - try { - props.load(new FileInputStream(propertiesFile)); - if(props.containsKey(LOG_CLASS_KEY)) { - loggerClass = props.getProperty(LOG_CLASS_KEY); - } - } catch (IOException ex) { - - } - } else { - //we have no properties file, assuming the default values - loggerClass = DEFAULT_LOGGER; - } - - } - - public ILogger getLogger(String tag) { - ILogger _logger = null; - try { - - _logger = (ILogger) Class.forName(loggerClass).newInstance(); - _logger.setTag(tag); - } catch (Exception ex) { - ex.printStackTrace(); - } - return _logger; - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/log/ILogger.java b/qy/src/main/java/org/alternativevision/gpx/log/ILogger.java deleted file mode 100644 index a775d52..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/log/ILogger.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ILogger.java - * - * Copyright (c) 2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package org.alternativevision.gpx.log; - -/** - * - * This interface defines the logging methods that are used in the GPXParser API. - * Each Logging API Wrappers must write their own implementation for those methods. - * - */ -public interface ILogger { - - /** - * This method sets the name of the entity that requests to write the message - * Equivalent with the tag parameter from Android API, or with classname parameter from Log4J - */ - public void setTag(String tag); - - /** - * This sends a message with level debug to the underlying Logging API - */ - public void debug(Object log); - - /** - * This sends a message with level info to the underlying Logging API - */ - public void info(Object log); - - /** - * This sends a message with level error to the underlying Logging API - */ - public void error(Object log); - - /** - * This sends a message with level error to the underlying Logging API - */ - public void error(Object log, Throwable th); - - /** - * This sends a message with level warn to the underlying Logging API - */ - public void warn(Object log); -} diff --git a/qy/src/main/java/org/alternativevision/gpx/log/Log4JLogger.java b/qy/src/main/java/org/alternativevision/gpx/log/Log4JLogger.java deleted file mode 100644 index 6413727..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/log/Log4JLogger.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Log4JLogger.java - * - * Copyright (c) 2013, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package org.alternativevision.gpx.log; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -//import org.apache.log4j.Logger; - -public class Log4JLogger extends AbstractLogger implements ILogger { - - public static final String LOG4JCLASSNAME = "org.apache.log4j.Logger"; - private Class factoryClass = null; - - Object logger = null; - - public Log4JLogger() { - setClassName(LOG4JCLASSNAME); - init(); - } - - public void setTag(String tag) { - this.tag = tag; - initLogger(tag); - - } - - public void debug(Object message) { - callMethod(logger, "debug",message); - } - - public void info(Object message) { - callMethod(logger,"info",message); - - } - - public void error(Object message) { - callMethod(logger,"error",message); - - } - - public void error(Object message, Throwable th) { - callMethod(logger,"error",message, th); - - } - - public void warn(Object message) { - callMethod(logger,"warn",message); - - } - - protected void initLogger(String tag) { - try { - Method m = logClass.getMethod("getLogger", String.class); - logger = m.invoke(null, tag); - } catch (IllegalAccessException e) { - e.printStackTrace(); - }catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } -} diff --git a/qy/src/main/java/org/alternativevision/gpx/types/FixType.java b/qy/src/main/java/org/alternativevision/gpx/types/FixType.java deleted file mode 100644 index f74d3cf..0000000 --- a/qy/src/main/java/org/alternativevision/gpx/types/FixType.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * FixType.java - * - * Copyright (c) 2012, AlternativeVision. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -package org.alternativevision.gpx.types; -/** - * - *

Type of GPS fix. Value comes from list: {'none'|'2d'|'3d'|'dgps'|'pps'}

- *
- *
    - *
  • none = GPS had no fix.
  • - *
  • pps = military signal used
  • - *
- *

To signify "the fix info is unknown", leave out fixType entirely.

- * - */ -public class FixType { - - private String value; - - private FixType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - public static FixType returnType(String value) { - if(NONE.getValue().equals(value)) { - return NONE; - } else if(TWO_D.getValue().equals(value)) { - return TWO_D; - } else if(THREE_D.getValue().equals(value)) { - return THREE_D; - } else if(DGPS.getValue().equals(value)) { - return DGPS; - } else if(PPS.getValue().equals(value)) { - return PPS; - } - return null; - } - - //'none'|'2d'|'3d'|'dgps'|'pps' - - /** - * Constant that defines 'none' Fix type - */ - public static FixType NONE = new FixType("none"); - /** - * Constant that defines '2d' Fix type - */ - public static FixType TWO_D = new FixType("2d"); - /** - * Constant that defines '3d' Fix type - */ - public static FixType THREE_D = new FixType("3d"); - /** - * Constant that defines 'dgps' Fix type - */ - public static FixType DGPS = new FixType("dgps"); - /** - * Constant that defines 'pps' Fix type - */ - public static FixType PPS = new FixType("pps"); - - public String toString() { - return value; - } -} diff --git a/qy/src/main/java/uk/co/senab/photoview/Compat.java b/qy/src/main/java/uk/co/senab/photoview/Compat.java deleted file mode 100644 index 6faccdf..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/Compat.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview; - -import android.annotation.TargetApi; -import android.os.Build; -import android.os.Build.VERSION; -import android.os.Build.VERSION_CODES; -import android.view.MotionEvent; -import android.view.View; - -public class Compat { - - private static final int SIXTY_FPS_INTERVAL = 1000 / 60; - - public static void postOnAnimation(View view, Runnable runnable) { - if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { - postOnAnimationJellyBean(view, runnable); - } else { - view.postDelayed(runnable, SIXTY_FPS_INTERVAL); - } - } - - @TargetApi(16) - private static void postOnAnimationJellyBean(View view, Runnable runnable) { - view.postOnAnimation(runnable); - } - - public static int getPointerIndex(int action) { - if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) - return getPointerIndexHoneyComb(action); - else - return getPointerIndexEclair(action); - } - - @SuppressWarnings("deprecation") - @TargetApi(Build.VERSION_CODES.ECLAIR) - private static int getPointerIndexEclair(int action) { - return (action & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT; - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - private static int getPointerIndexHoneyComb(int action) { - return (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; - } - -} diff --git a/qy/src/main/java/uk/co/senab/photoview/DefaultOnDoubleTapListener.java b/qy/src/main/java/uk/co/senab/photoview/DefaultOnDoubleTapListener.java deleted file mode 100644 index d0ba1ef..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/DefaultOnDoubleTapListener.java +++ /dev/null @@ -1,98 +0,0 @@ -package uk.co.senab.photoview; - -import android.graphics.RectF; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.widget.ImageView; - -/** - * Provided default implementation of GestureDetector.OnDoubleTapListener, to be overriden with custom behavior, if needed - *

 

- * To be used via {@link uk.co.senab.photoview.PhotoViewAttacher#setOnDoubleTapListener(android.view.GestureDetector.OnDoubleTapListener)} - */ -public class DefaultOnDoubleTapListener implements GestureDetector.OnDoubleTapListener { - - private PhotoViewAttacher photoViewAttacher; - - /** - * Default constructor - * - * @param photoViewAttacher PhotoViewAttacher to bind to - */ - public DefaultOnDoubleTapListener(PhotoViewAttacher photoViewAttacher) { - setPhotoViewAttacher(photoViewAttacher); - } - - /** - * Allows to change PhotoViewAttacher within range of single instance - * - * @param newPhotoViewAttacher PhotoViewAttacher to bind to - */ - public void setPhotoViewAttacher(PhotoViewAttacher newPhotoViewAttacher) { - this.photoViewAttacher = newPhotoViewAttacher; - } - - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (this.photoViewAttacher == null) - return false; - - ImageView imageView = photoViewAttacher.getImageView(); - - if (null != photoViewAttacher.getOnPhotoTapListener()) { - final RectF displayRect = photoViewAttacher.getDisplayRect(); - - if (null != displayRect) { - final float x = e.getX(), y = e.getY(); - - // Check to see if the user tapped on the photo - if (displayRect.contains(x, y)) { - - float xResult = (x - displayRect.left) - / displayRect.width(); - float yResult = (y - displayRect.top) - / displayRect.height(); - - photoViewAttacher.getOnPhotoTapListener().onPhotoTap(imageView, xResult, yResult); - return true; - } - } - } - if (null != photoViewAttacher.getOnViewTapListener()) { - photoViewAttacher.getOnViewTapListener().onViewTap(imageView, e.getX(), e.getY()); - } - - return false; - } - - @Override - public boolean onDoubleTap(MotionEvent ev) { - if (photoViewAttacher == null) - return false; - - try { - float scale = photoViewAttacher.getScale(); - float x = ev.getX(); - float y = ev.getY(); - - if (scale < photoViewAttacher.getMediumScale()) { - photoViewAttacher.setScale(photoViewAttacher.getMediumScale(), x, y, true); - } else if (scale >= photoViewAttacher.getMediumScale() && scale < photoViewAttacher.getMaximumScale()) { - photoViewAttacher.setScale(photoViewAttacher.getMaximumScale(), x, y, true); - } else { - photoViewAttacher.setScale(photoViewAttacher.getMinimumScale(), x, y, true); - } - } catch (ArrayIndexOutOfBoundsException e) { - // Can sometimes happen when getX() and getY() is called - } - - return true; - } - - @Override - public boolean onDoubleTapEvent(MotionEvent e) { - // Wait for the confirmed onDoubleTap() instead - return false; - } - -} diff --git a/qy/src/main/java/uk/co/senab/photoview/IPhotoView.java b/qy/src/main/java/uk/co/senab/photoview/IPhotoView.java deleted file mode 100644 index 554eaf3..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/IPhotoView.java +++ /dev/null @@ -1,283 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview; - -import android.graphics.Bitmap; -import android.graphics.Matrix; -import android.graphics.RectF; -import android.view.View; -import android.widget.ImageView; - - -public interface IPhotoView { - - public static final float DEFAULT_MAX_SCALE = 3.0f; - public static final float DEFAULT_MID_SCALE = 1.75f; - public static final float DEFAULT_MIN_SCALE = 1.0f; - public static final int DEFAULT_ZOOM_DURATION = 200; - - /** - * Returns true if the PhotoView is set to allow zooming of Photos. - * - * @return true if the PhotoView allows zooming. - */ - boolean canZoom(); - - /** - * Gets the Display Rectangle of the currently displayed Drawable. The Rectangle is relative to - * this View and includes all scaling and translations. - * - * @return - RectF of Displayed Drawable - */ - RectF getDisplayRect(); - - /** - * Sets the Display Matrix of the currently displayed Drawable. The Rectangle is considered - * relative to this View and includes all scaling and translations. - * - * @return - true if rectangle was applied successfully - */ - boolean setDisplayMatrix(Matrix finalMatrix); - - /** - * Gets the Display Matrix of the currently displayed Drawable. The Rectangle is considered - * relative to this View and includes all scaling and translations. - * - * @return - true if rectangle was applied successfully - */ - Matrix getDisplayMatrix(); - - /** - * Use {@link #getMinimumScale()} instead, this will be removed in future release - * - * @return The current minimum scale level. What this value represents depends on the current - * {@link android.widget.ImageView.ScaleType}. - */ - @Deprecated - float getMinScale(); - - /** - * @return The current minimum scale level. What this value represents depends on the current - * {@link android.widget.ImageView.ScaleType}. - */ - float getMinimumScale(); - - /** - * Use {@link #getMediumScale()} instead, this will be removed in future release - * - * @return The current middle scale level. What this value represents depends on the current - * {@link android.widget.ImageView.ScaleType}. - */ - @Deprecated - float getMidScale(); - - /** - * @return The current medium scale level. What this value represents depends on the current - * {@link android.widget.ImageView.ScaleType}. - */ - float getMediumScale(); - - /** - * Use {@link #getMaximumScale()} instead, this will be removed in future release - * - * @return The current maximum scale level. What this value represents depends on the current - * {@link android.widget.ImageView.ScaleType}. - */ - @Deprecated - float getMaxScale(); - - /** - * @return The current maximum scale level. What this value represents depends on the current - * {@link android.widget.ImageView.ScaleType}. - */ - float getMaximumScale(); - - /** - * Returns the current scale value - * - * @return float - current scale value - */ - float getScale(); - - /** - * Return the current scale type in use by the ImageView. - */ - ImageView.ScaleType getScaleType(); - - /** - * Whether to allow the ImageView's parent to intercept the touch event when the photo is scroll - * to it's horizontal edge. - */ - void setAllowParentInterceptOnEdge(boolean allow); - - /** - * Use {@link #setMinimumScale(float minimumScale)} instead, this will be removed in future - * release - *

- * Sets the minimum scale level. What this value represents depends on the current {@link - * android.widget.ImageView.ScaleType}. - */ - @Deprecated - void setMinScale(float minScale); - - /** - * Sets the minimum scale level. What this value represents depends on the current {@link - * android.widget.ImageView.ScaleType}. - */ - void setMinimumScale(float minimumScale); - - /** - * Use {@link #setMediumScale(float mediumScale)} instead, this will be removed in future - * release - *

- * Sets the middle scale level. What this value represents depends on the current {@link - * android.widget.ImageView.ScaleType}. - */ - @Deprecated - void setMidScale(float midScale); - - /* - * Sets the medium scale level. What this value represents depends on the current {@link android.widget.ImageView.ScaleType}. - */ - void setMediumScale(float mediumScale); - - /** - * Use {@link #setMaximumScale(float maximumScale)} instead, this will be removed in future - * release - *

- * Sets the maximum scale level. What this value represents depends on the current {@link - * android.widget.ImageView.ScaleType}. - */ - @Deprecated - void setMaxScale(float maxScale); - - /** - * Sets the maximum scale level. What this value represents depends on the current {@link - * android.widget.ImageView.ScaleType}. - */ - void setMaximumScale(float maximumScale); - - /** - * Register a callback to be invoked when the Photo displayed by this view is long-pressed. - * - * @param listener - Listener to be registered. - */ - void setOnLongClickListener(View.OnLongClickListener listener); - - /** - * Register a callback to be invoked when the Matrix has changed for this View. An example would - * be the user panning or scaling the Photo. - * - * @param listener - Listener to be registered. - */ - void setOnMatrixChangeListener(PhotoViewAttacher.OnMatrixChangedListener listener); - - /** - * Register a callback to be invoked when the Photo displayed by this View is tapped with a - * single tap. - * - * @param listener - Listener to be registered. - */ - void setOnPhotoTapListener(PhotoViewAttacher.OnPhotoTapListener listener); - - /** - * Returns a listener to be invoked when the Photo displayed by this View is tapped with a - * single tap. - * - * @return PhotoViewAttacher.OnPhotoTapListener currently set, may be null - */ - PhotoViewAttacher.OnPhotoTapListener getOnPhotoTapListener(); - - /** - * Register a callback to be invoked when the View is tapped with a single tap. - * - * @param listener - Listener to be registered. - */ - void setOnViewTapListener(PhotoViewAttacher.OnViewTapListener listener); - - /** - * Returns a callback listener to be invoked when the View is tapped with a single tap. - * - * @return PhotoViewAttacher.OnViewTapListener currently set, may be null - */ - PhotoViewAttacher.OnViewTapListener getOnViewTapListener(); - - /** - * Changes the current scale to the specified value. - * - * @param scale - Value to scale to - */ - void setScale(float scale); - - /** - * Changes the current scale to the specified value. - * - * @param scale - Value to scale to - * @param animate - Whether to animate the scale - */ - void setScale(float scale, boolean animate); - - /** - * Changes the current scale to the specified value, around the given focal point. - * - * @param scale - Value to scale to - * @param focalX - X Focus Point - * @param focalY - Y Focus Point - * @param animate - Whether to animate the scale - */ - void setScale(float scale, float focalX, float focalY, boolean animate); - - /** - * Controls how the image should be resized or moved to match the size of the ImageView. Any - * scaling or panning will happen within the confines of this {@link - * android.widget.ImageView.ScaleType}. - * - * @param scaleType - The desired scaling mode. - */ - void setScaleType(ImageView.ScaleType scaleType); - - /** - * Allows you to enable/disable the zoom functionality on the ImageView. When disable the - * ImageView reverts to using the FIT_CENTER matrix. - * - * @param zoomable - Whether the zoom functionality is enabled. - */ - void setZoomable(boolean zoomable); - - /** - * Enables rotation via PhotoView internal functions. Name is chosen so it won't collide with - * View.setRotation(float) in API since 11 - * - * @param rotationDegree - Degree to rotate PhotoView by, should be in range 0 to 360 - */ - void setPhotoViewRotation(float rotationDegree); - - /** - * Extracts currently visible area to Bitmap object, if there is no image loaded yet or the - * ImageView is already destroyed, returns {@code null} - * - * @return currently visible area as bitmap or null - */ - Bitmap getVisibleRectangleBitmap(); - - /** - * Allows to change zoom transition speed, default value is 200 (PhotoViewAttacher.DEFAULT_ZOOM_DURATION). - * Will default to 200 if provided negative value - * - * @param milliseconds duration of zoom interpolation - */ - void setZoomTransitionDuration(int milliseconds); -} diff --git a/qy/src/main/java/uk/co/senab/photoview/PhotoView.java b/qy/src/main/java/uk/co/senab/photoview/PhotoView.java deleted file mode 100644 index 922d8a6..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/PhotoView.java +++ /dev/null @@ -1,262 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Matrix; -import android.graphics.RectF; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.util.AttributeSet; -import android.widget.ImageView; - -import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; -import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; -import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; - -public class PhotoView extends ImageView implements IPhotoView { - - private final PhotoViewAttacher mAttacher; - - private ScaleType mPendingScaleType; - - public PhotoView(Context context) { - this(context, null); - } - - public PhotoView(Context context, AttributeSet attr) { - this(context, attr, 0); - } - - public PhotoView(Context context, AttributeSet attr, int defStyle) { - super(context, attr, defStyle); - super.setScaleType(ScaleType.MATRIX); - mAttacher = new PhotoViewAttacher(this); - - if (null != mPendingScaleType) { - setScaleType(mPendingScaleType); - mPendingScaleType = null; - } - } - - @Override - public void setPhotoViewRotation(float rotationDegree) { - mAttacher.setPhotoViewRotation(rotationDegree); - } - - @Override - public boolean canZoom() { - return mAttacher.canZoom(); - } - - @Override - public RectF getDisplayRect() { - return mAttacher.getDisplayRect(); - } - - @Override - public Matrix getDisplayMatrix() { - return mAttacher.getDrawMatrix(); - } - - @Override - public boolean setDisplayMatrix(Matrix finalRectangle) { - return mAttacher.setDisplayMatrix(finalRectangle); - } - - @Override - @Deprecated - public float getMinScale() { - return getMinimumScale(); - } - - @Override - public float getMinimumScale() { - return mAttacher.getMinimumScale(); - } - - @Override - @Deprecated - public float getMidScale() { - return getMediumScale(); - } - - @Override - public float getMediumScale() { - return mAttacher.getMediumScale(); - } - - @Override - @Deprecated - public float getMaxScale() { - return getMaximumScale(); - } - - @Override - public float getMaximumScale() { - return mAttacher.getMaximumScale(); - } - - @Override - public float getScale() { - return mAttacher.getScale(); - } - - @Override - public ScaleType getScaleType() { - return mAttacher.getScaleType(); - } - - @Override - public void setAllowParentInterceptOnEdge(boolean allow) { - mAttacher.setAllowParentInterceptOnEdge(allow); - } - - @Override - @Deprecated - public void setMinScale(float minScale) { - setMinimumScale(minScale); - } - - @Override - public void setMinimumScale(float minimumScale) { - mAttacher.setMinimumScale(minimumScale); - } - - @Override - @Deprecated - public void setMidScale(float midScale) { - setMediumScale(midScale); - } - - @Override - public void setMediumScale(float mediumScale) { - mAttacher.setMediumScale(mediumScale); - } - - @Override - @Deprecated - public void setMaxScale(float maxScale) { - setMaximumScale(maxScale); - } - - @Override - public void setMaximumScale(float maximumScale) { - mAttacher.setMaximumScale(maximumScale); - } - - @Override - // setImageBitmap calls through to this method - public void setImageDrawable(Drawable drawable) { - super.setImageDrawable(drawable); - if (null != mAttacher) { - mAttacher.update(); - } - } - - @Override - public void setImageResource(int resId) { - super.setImageResource(resId); - if (null != mAttacher) { - mAttacher.update(); - } - } - - @Override - public void setImageURI(Uri uri) { - super.setImageURI(uri); - if (null != mAttacher) { - mAttacher.update(); - } - } - - @Override - public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { - mAttacher.setOnMatrixChangeListener(listener); - } - - @Override - public void setOnLongClickListener(OnLongClickListener l) { - mAttacher.setOnLongClickListener(l); - } - - @Override - public void setOnPhotoTapListener(OnPhotoTapListener listener) { - mAttacher.setOnPhotoTapListener(listener); - } - - @Override - public OnPhotoTapListener getOnPhotoTapListener() { - return mAttacher.getOnPhotoTapListener(); - } - - @Override - public void setOnViewTapListener(OnViewTapListener listener) { - mAttacher.setOnViewTapListener(listener); - } - - @Override - public OnViewTapListener getOnViewTapListener() { - return mAttacher.getOnViewTapListener(); - } - - @Override - public void setScale(float scale) { - mAttacher.setScale(scale); - } - - @Override - public void setScale(float scale, boolean animate) { - mAttacher.setScale(scale, animate); - } - - @Override - public void setScale(float scale, float focalX, float focalY, boolean animate) { - mAttacher.setScale(scale, focalX, focalY, animate); - } - - @Override - public void setScaleType(ScaleType scaleType) { - if (null != mAttacher) { - mAttacher.setScaleType(scaleType); - } else { - mPendingScaleType = scaleType; - } - } - - @Override - public void setZoomable(boolean zoomable) { - mAttacher.setZoomable(zoomable); - } - - @Override - public Bitmap getVisibleRectangleBitmap() { - return mAttacher.getVisibleRectangleBitmap(); - } - - @Override - public void setZoomTransitionDuration(int milliseconds) { - mAttacher.setZoomTransitionDuration(milliseconds); - } - - @Override - protected void onDetachedFromWindow() { - mAttacher.cleanup(); - super.onDetachedFromWindow(); - } - -} \ No newline at end of file diff --git a/qy/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java b/qy/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java deleted file mode 100644 index 61042da..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java +++ /dev/null @@ -1,1086 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview; - -import static android.view.MotionEvent.ACTION_CANCEL; -import static android.view.MotionEvent.ACTION_DOWN; -import static android.view.MotionEvent.ACTION_UP; - -import java.lang.ref.WeakReference; - -import uk.co.senab.photoview.gestures.OnGestureListener; -import uk.co.senab.photoview.gestures.VersionedGestureDetector; -import uk.co.senab.photoview.scrollerproxy.ScrollerProxy; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Matrix; -import android.graphics.Matrix.ScaleToFit; -import android.graphics.RectF; -import android.graphics.drawable.Drawable; -import android.util.FloatMath; -import android.util.Log; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnLongClickListener; -import android.view.ViewParent; -import android.view.ViewTreeObserver; -import android.view.animation.AccelerateDecelerateInterpolator; -import android.view.animation.Interpolator; -import android.widget.ImageView; -import android.widget.ImageView.ScaleType; - -import com.qiyou.mb.android.utils.log.QLog; - -public class PhotoViewAttacher implements IPhotoView, View.OnTouchListener, - OnGestureListener, - ViewTreeObserver.OnGlobalLayoutListener { - - private static final String LOG_TAG = "PhotoViewAttacher"; - - // let debug flag be dynamic, but still Proguard can be used to remove from - // release builds - private static final boolean DEBUG = Log.isLoggable(LOG_TAG, Log.ERROR); - - static final Interpolator sInterpolator = new AccelerateDecelerateInterpolator(); - int ZOOM_DURATION = DEFAULT_ZOOM_DURATION; - - static final int EDGE_NONE = -1; - static final int EDGE_LEFT = 0; - static final int EDGE_RIGHT = 1; - static final int EDGE_BOTH = 2; - - private float mMinScale = DEFAULT_MIN_SCALE; - private float mMidScale = DEFAULT_MID_SCALE; - private float mMaxScale = DEFAULT_MAX_SCALE; - - private boolean mAllowParentInterceptOnEdge = true; - - private static void checkZoomLevels(float minZoom, float midZoom, - float maxZoom) { - if (minZoom >= midZoom) { - throw new IllegalArgumentException( - "MinZoom has to be less than MidZoom"); - } else if (midZoom >= maxZoom) { - throw new IllegalArgumentException( - "MidZoom has to be less than MaxZoom"); - } - } - - /** - * @return true if the ImageView exists, and it's Drawable existss - */ - private static boolean hasDrawable(ImageView imageView) { - return null != imageView && null != imageView.getDrawable(); - } - - /** - * @return true if the ScaleType is supported. - */ - private static boolean isSupportedScaleType(final ScaleType scaleType) { - if (null == scaleType) { - return false; - } - - switch (scaleType) { - case MATRIX: - throw new IllegalArgumentException(scaleType.name() - + " is not supported in PhotoView"); - - default: - return true; - } - } - - /** - * Set's the ImageView's ScaleType to Matrix. - */ - private static void setImageViewScaleTypeMatrix(ImageView imageView) { - /** - * PhotoView sets it's own ScaleType to Matrix, then diverts all calls - * setScaleType to this.setScaleType automatically. - */ - if (null != imageView && !(imageView instanceof IPhotoView)) { - if (!ScaleType.MATRIX.equals(imageView.getScaleType())) { - imageView.setScaleType(ScaleType.MATRIX); - } - } - } - - private WeakReference mImageView; - - // Gesture Detectors - private GestureDetector mGestureDetector; - private uk.co.senab.photoview.gestures.GestureDetector mScaleDragDetector; - - // These are set so we don't keep allocating them on the heap - private final Matrix mBaseMatrix = new Matrix(); - private final Matrix mDrawMatrix = new Matrix(); - private final Matrix mSuppMatrix = new Matrix(); - private final RectF mDisplayRect = new RectF(); - private final float[] mMatrixValues = new float[9]; - - // Listeners - private OnMatrixChangedListener mMatrixChangeListener; - private OnPhotoTapListener mPhotoTapListener; - private OnViewTapListener mViewTapListener; - private OnLongClickListener mLongClickListener; - - private int mIvTop, mIvRight, mIvBottom, mIvLeft; - private FlingRunnable mCurrentFlingRunnable; - private int mScrollEdge = EDGE_BOTH; - - private boolean mRotationDetectionEnabled = false; - private boolean mZoomEnabled; - private ScaleType mScaleType = ScaleType.FIT_CENTER; - - public PhotoViewAttacher(ImageView imageView) { - mImageView = new WeakReference(imageView); - - imageView.setDrawingCacheEnabled(true); - imageView.setOnTouchListener(this); - - ViewTreeObserver observer = imageView.getViewTreeObserver(); - if (null != observer) - observer.addOnGlobalLayoutListener(this); - - // Make sure we using MATRIX Scale Type - setImageViewScaleTypeMatrix(imageView); - - if (imageView.isInEditMode()) { - return; - } - // Create Gesture Detectors... - mScaleDragDetector = VersionedGestureDetector.newInstance( - imageView.getContext(), this); - - mGestureDetector = new GestureDetector(imageView.getContext(), - new GestureDetector.SimpleOnGestureListener() { - - // forward long click listener - @Override - public void onLongPress(MotionEvent e) { - if (null != mLongClickListener) { - mLongClickListener.onLongClick(getImageView()); - } - } - }); - - mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this)); - - // Finally, update the UI so that we're zoomable - setZoomable(true); - } - - /** - * Sets custom double tap listener, to intercept default given functions. To reset behavior to - * default, you can just pass in "null" or public field of PhotoViewAttacher.defaultOnDoubleTapListener - * - * @param newOnDoubleTapListener custom OnDoubleTapListener to be set on ImageView - */ - public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener) { - if (newOnDoubleTapListener != null) - this.mGestureDetector.setOnDoubleTapListener(newOnDoubleTapListener); - else - this.mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this)); - } - - @Override - public boolean canZoom() { - return mZoomEnabled; - } - - /** - * Clean-up the resources attached to this object. This needs to be called when the ImageView is - * no longer used. A good example is from {@link android.view.View#onDetachedFromWindow()} or - * from {@link android.app.Activity#onDestroy()}. This is automatically called if you are using - * {@link uk.co.senab.photoview.PhotoView}. - */ - @SuppressWarnings("deprecation") - public void cleanup() { - if (null == mImageView) { - return; // cleanup already done - } - - final ImageView imageView = mImageView.get(); - - if (null != imageView) { - // Remove this as a global layout listener - ViewTreeObserver observer = imageView.getViewTreeObserver(); - if (null != observer && observer.isAlive()) { - observer.removeGlobalOnLayoutListener(this); - } - - // Remove the ImageView's reference to this - imageView.setOnTouchListener(null); - - // make sure a pending fling runnable won't be run - cancelFling(); - } - - if (null != mGestureDetector) { - mGestureDetector.setOnDoubleTapListener(null); - } - - // Clear listeners too - mMatrixChangeListener = null; - mPhotoTapListener = null; - mViewTapListener = null; - - // Finally, clear ImageView - mImageView = null; - } - - @Override - public RectF getDisplayRect() { - checkMatrixBounds(); - return getDisplayRect(getDrawMatrix()); - } - - @Override - public boolean setDisplayMatrix(Matrix finalMatrix) { - if (finalMatrix == null) - throw new IllegalArgumentException("Matrix cannot be null"); - - ImageView imageView = getImageView(); - if (null == imageView) - return false; - - if (null == imageView.getDrawable()) - return false; - - mSuppMatrix.set(finalMatrix); - setImageViewMatrix(getDrawMatrix()); - checkMatrixBounds(); - - return true; - } - - private float mLastRotation = 0; - - @Override - public void setPhotoViewRotation(float degrees) { - degrees %= 360; - mSuppMatrix.postRotate(mLastRotation - degrees); - mLastRotation = degrees; - checkAndDisplayMatrix(); - } - - public ImageView getImageView() { - ImageView imageView = null; - - if (null != mImageView) { - imageView = mImageView.get(); - } - - // If we don't have an ImageView, call cleanup() - if (null == imageView) { - cleanup(); - Log.i(LOG_TAG, - "ImageView no longer exists. You should not use this PhotoViewAttacher any more."); - } - - return imageView; - } - - @Override - @Deprecated - public float getMinScale() { - return getMinimumScale(); - } - - @Override - public float getMinimumScale() { - return mMinScale; - } - - @Override - @Deprecated - public float getMidScale() { - return getMediumScale(); - } - - @Override - public float getMediumScale() { - return mMidScale; - } - - @Override - @Deprecated - public float getMaxScale() { - return getMaximumScale(); - } - - @Override - public float getMaximumScale() { - return mMaxScale; - } - - @Override - public float getScale() { - return (float)Math.sqrt((float) Math.pow(getValue(mSuppMatrix, Matrix.MSCALE_X), 2) + (float) Math.pow(getValue(mSuppMatrix, Matrix.MSKEW_Y), 2)); - } - - @Override - public ScaleType getScaleType() { - return mScaleType; - } - - @Override - public void onDrag(float dx, float dy) { - if (mScaleDragDetector.isScaling()) { - return; // Do not drag if we are already scaling - } - - if (DEBUG) { - QLog.getLogger().d(LOG_TAG, - String.format("onDrag: dx: %.2f. dy: %.2f", dx, dy)); - } - - ImageView imageView = getImageView(); - mSuppMatrix.postTranslate(dx, dy); - checkAndDisplayMatrix(); - - /** - * Here we decide whether to let the ImageView's parent to start taking - * over the touch event. - * - * First we check whether this function is enabled. We never want the - * parent to take over if we're scaling. We then check the edge we're - * on, and the direction of the scroll (i.e. if we're pulling against - * the edge, aka 'overscrolling', let the parent take over). - */ - ViewParent parent = imageView.getParent(); - if (mAllowParentInterceptOnEdge) { - if (mScrollEdge == EDGE_BOTH - || (mScrollEdge == EDGE_LEFT && dx >= 1f) - || (mScrollEdge == EDGE_RIGHT && dx <= -1f)) { - if (null != parent) - parent.requestDisallowInterceptTouchEvent(false); - } - } else { - if (null != parent) { - parent.requestDisallowInterceptTouchEvent(true); - } - } - } - - @Override - public void onFling(float startX, float startY, float velocityX, - float velocityY) { - if (DEBUG) { - QLog.getLogger().d( - LOG_TAG, - "onFling. sX: " + startX + " sY: " + startY + " Vx: " - + velocityX + " Vy: " + velocityY); - } - ImageView imageView = getImageView(); - mCurrentFlingRunnable = new FlingRunnable(imageView.getContext()); - mCurrentFlingRunnable.fling(getImageViewWidth(imageView), - getImageViewHeight(imageView), (int) velocityX, (int) velocityY); - imageView.post(mCurrentFlingRunnable); - } - - @Override - public void onGlobalLayout() { - ImageView imageView = getImageView(); - - if (null != imageView) { - if (mZoomEnabled) { - final int top = imageView.getTop(); - final int right = imageView.getRight(); - final int bottom = imageView.getBottom(); - final int left = imageView.getLeft(); - - /** - * We need to check whether the ImageView's bounds have changed. - * This would be easier if we targeted API 11+ as we could just use - * View.OnLayoutChangeListener. Instead we have to replicate the - * work, keeping track of the ImageView's bounds and then checking - * if the values change. - */ - if (top != mIvTop || bottom != mIvBottom || left != mIvLeft - || right != mIvRight) { - // Update our base matrix, as the bounds have changed - updateBaseMatrix(imageView.getDrawable()); - - // Update values as something has changed - mIvTop = top; - mIvRight = right; - mIvBottom = bottom; - mIvLeft = left; - } - } else { - updateBaseMatrix(imageView.getDrawable()); - } - } - } - - @Override - public void onScale(float scaleFactor, float focusX, float focusY) { - if (DEBUG) { - QLog.getLogger().d( - LOG_TAG, - String.format("onScale: scale: %.2f. fX: %.2f. fY: %.2f", - scaleFactor, focusX, focusY)); - } - - if (getScale() < mMaxScale || scaleFactor < 1f) { - mSuppMatrix.postScale(scaleFactor, scaleFactor, focusX, focusY); - checkAndDisplayMatrix(); - } - } - - @Override - public boolean onTouch(View v, MotionEvent ev) { - boolean handled = false; - - if (mZoomEnabled && hasDrawable((ImageView) v)) { - ViewParent parent = v.getParent(); - switch (ev.getAction()) { - case ACTION_DOWN: - // First, disable the Parent from intercepting the touch - // event - if (null != parent) - parent.requestDisallowInterceptTouchEvent(true); - else - Log.i(LOG_TAG, "onTouch getParent() returned null"); - - // If we're flinging, and the user presses down, cancel - // fling - cancelFling(); - break; - - case ACTION_CANCEL: - case ACTION_UP: - // If the user has zoomed less than min scale, zoom back - // to min scale - if (getScale() < mMinScale) { - RectF rect = getDisplayRect(); - if (null != rect) { - v.post(new AnimatedZoomRunnable(getScale(), mMinScale, - rect.centerX(), rect.centerY())); - handled = true; - } - } - break; - } - - // Try the Scale/Drag detector - if (null != mScaleDragDetector - && mScaleDragDetector.onTouchEvent(ev)) { - handled = true; - } - - // Check to see if the user double tapped - if (null != mGestureDetector && mGestureDetector.onTouchEvent(ev)) { - handled = true; - } - } - - return handled; - } - - @Override - public void setAllowParentInterceptOnEdge(boolean allow) { - mAllowParentInterceptOnEdge = allow; - } - - @Override - @Deprecated - public void setMinScale(float minScale) { - setMinimumScale(minScale); - } - - @Override - public void setMinimumScale(float minimumScale) { - checkZoomLevels(minimumScale, mMidScale, mMaxScale); - mMinScale = minimumScale; - } - - @Override - @Deprecated - public void setMidScale(float midScale) { - setMediumScale(midScale); - } - - @Override - public void setMediumScale(float mediumScale) { - checkZoomLevels(mMinScale, mediumScale, mMaxScale); - mMidScale = mediumScale; - } - - @Override - @Deprecated - public void setMaxScale(float maxScale) { - setMaximumScale(maxScale); - } - - @Override - public void setMaximumScale(float maximumScale) { - checkZoomLevels(mMinScale, mMidScale, maximumScale); - mMaxScale = maximumScale; - } - - @Override - public void setOnLongClickListener(OnLongClickListener listener) { - mLongClickListener = listener; - } - - @Override - public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { - mMatrixChangeListener = listener; - } - - @Override - public void setOnPhotoTapListener(OnPhotoTapListener listener) { - mPhotoTapListener = listener; - } - - @Override - public OnPhotoTapListener getOnPhotoTapListener() { - return mPhotoTapListener; - } - - @Override - public void setOnViewTapListener(OnViewTapListener listener) { - mViewTapListener = listener; - } - - @Override - public OnViewTapListener getOnViewTapListener() { - return mViewTapListener; - } - - @Override - public void setScale(float scale) { - setScale(scale, false); - } - - @Override - public void setScale(float scale, boolean animate) { - ImageView imageView = getImageView(); - - if (null != imageView) { - setScale(scale, - (imageView.getRight()) / 2, - (imageView.getBottom()) / 2, - animate); - } - } - - @Override - public void setScale(float scale, float focalX, float focalY, - boolean animate) { - ImageView imageView = getImageView(); - - if (null != imageView) { - // Check to see if the scale is within bounds - if (scale < mMinScale || scale > mMaxScale) { - QLog - .getLogger() - .i(LOG_TAG, - "Scale must be within the range of minScale and maxScale"); - return; - } - - if (animate) { - imageView.post(new AnimatedZoomRunnable(getScale(), scale, - focalX, focalY)); - } else { - mSuppMatrix.setScale(scale, scale, focalX, focalY); - checkAndDisplayMatrix(); - } - } - } - - @Override - public void setScaleType(ScaleType scaleType) { - if (isSupportedScaleType(scaleType) && scaleType != mScaleType) { - mScaleType = scaleType; - - // Finally update - update(); - } - } - - @Override - public void setZoomable(boolean zoomable) { - mZoomEnabled = zoomable; - update(); - } - - public void update() { - ImageView imageView = getImageView(); - - if (null != imageView) { - if (mZoomEnabled) { - // Make sure we using MATRIX Scale Type - setImageViewScaleTypeMatrix(imageView); - - // Update the base matrix using the current drawable - updateBaseMatrix(imageView.getDrawable()); - } else { - // Reset the Matrix... - resetMatrix(); - } - } - } - - @Override - public Matrix getDisplayMatrix() { - return new Matrix(getDrawMatrix()); - } - - public Matrix getDrawMatrix() { - mDrawMatrix.set(mBaseMatrix); - mDrawMatrix.postConcat(mSuppMatrix); - return mDrawMatrix; - } - - private void cancelFling() { - if (null != mCurrentFlingRunnable) { - mCurrentFlingRunnable.cancelFling(); - mCurrentFlingRunnable = null; - } - } - - /** - * Helper method that simply checks the Matrix, and then displays the result - */ - private void checkAndDisplayMatrix() { - if (checkMatrixBounds()) { - setImageViewMatrix(getDrawMatrix()); - } - } - - private void checkImageViewScaleType() { - ImageView imageView = getImageView(); - - /** - * PhotoView's getScaleType() will just divert to this.getScaleType() so - * only call if we're not attached to a PhotoView. - */ - if (null != imageView && !(imageView instanceof IPhotoView)) { - if (!ScaleType.MATRIX.equals(imageView.getScaleType())) { - throw new IllegalStateException( - "The ImageView's ScaleType has been changed since attaching a PhotoViewAttacher"); - } - } - } - - private boolean checkMatrixBounds() { - final ImageView imageView = getImageView(); - if (null == imageView) { - return false; - } - - final RectF rect = getDisplayRect(getDrawMatrix()); - if (null == rect) { - return false; - } - - final float height = rect.height(), width = rect.width(); - float deltaX = 0, deltaY = 0; - - final int viewHeight = getImageViewHeight(imageView); - if (height <= viewHeight) { - switch (mScaleType) { - case FIT_START: - deltaY = -rect.top; - break; - case FIT_END: - deltaY = viewHeight - height - rect.top; - break; - default: - deltaY = (viewHeight - height) / 2 - rect.top; - break; - } - } else if (rect.top > 0) { - deltaY = -rect.top; - } else if (rect.bottom < viewHeight) { - deltaY = viewHeight - rect.bottom; - } - - final int viewWidth = getImageViewWidth(imageView); - if (width <= viewWidth) { - switch (mScaleType) { - case FIT_START: - deltaX = -rect.left; - break; - case FIT_END: - deltaX = viewWidth - width - rect.left; - break; - default: - deltaX = (viewWidth - width) / 2 - rect.left; - break; - } - mScrollEdge = EDGE_BOTH; - } else if (rect.left > 0) { - mScrollEdge = EDGE_LEFT; - deltaX = -rect.left; - } else if (rect.right < viewWidth) { - deltaX = viewWidth - rect.right; - mScrollEdge = EDGE_RIGHT; - } else { - mScrollEdge = EDGE_NONE; - } - - // Finally actually translate the matrix - mSuppMatrix.postTranslate(deltaX, deltaY); - return true; - } - - /** - * Helper method that maps the supplied Matrix to the current Drawable - * - * @param matrix - Matrix to map Drawable against - * @return RectF - Displayed Rectangle - */ - private RectF getDisplayRect(Matrix matrix) { - ImageView imageView = getImageView(); - - if (null != imageView) { - Drawable d = imageView.getDrawable(); - if (null != d) { - mDisplayRect.set(0, 0, d.getIntrinsicWidth(), - d.getIntrinsicHeight()); - matrix.mapRect(mDisplayRect); - return mDisplayRect; - } - } - return null; - } - - @Override - public Bitmap getVisibleRectangleBitmap() { - ImageView imageView = getImageView(); - return imageView == null ? null : imageView.getDrawingCache(); - } - - @Override - public void setZoomTransitionDuration(int milliseconds) { - if (milliseconds < 0) - milliseconds = DEFAULT_ZOOM_DURATION; - this.ZOOM_DURATION = milliseconds; - } - - /** - * Helper method that 'unpacks' a Matrix and returns the required value - * - * @param matrix - Matrix to unpack - * @param whichValue - Which value from Matrix.M* to return - * @return float - returned value - */ - private float getValue(Matrix matrix, int whichValue) { - matrix.getValues(mMatrixValues); - return mMatrixValues[whichValue]; - } - - /** - * Resets the Matrix back to FIT_CENTER, and then displays it.s - */ - private void resetMatrix() { - mSuppMatrix.reset(); - setImageViewMatrix(getDrawMatrix()); - checkMatrixBounds(); - } - - private void setImageViewMatrix(Matrix matrix) { - ImageView imageView = getImageView(); - if (null != imageView) { - - checkImageViewScaleType(); - imageView.setImageMatrix(matrix); - - // Call MatrixChangedListener if needed - if (null != mMatrixChangeListener) { - RectF displayRect = getDisplayRect(matrix); - if (null != displayRect) { - mMatrixChangeListener.onMatrixChanged(displayRect); - } - } - } - } - - /** - * Calculate Matrix for FIT_CENTER - * - * @param d - Drawable being displayed - */ - private void updateBaseMatrix(Drawable d) { - ImageView imageView = getImageView(); - if (null == imageView || null == d) { - return; - } - - final float viewWidth = getImageViewWidth(imageView); - final float viewHeight = getImageViewHeight(imageView); - final int drawableWidth = d.getIntrinsicWidth(); - final int drawableHeight = d.getIntrinsicHeight(); - - mBaseMatrix.reset(); - - final float widthScale = viewWidth / drawableWidth; - final float heightScale = viewHeight / drawableHeight; - - if (mScaleType == ScaleType.CENTER) { - mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2F, - (viewHeight - drawableHeight) / 2F); - - } else if (mScaleType == ScaleType.CENTER_CROP) { - float scale = Math.max(widthScale, heightScale); - mBaseMatrix.postScale(scale, scale); - mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F, - (viewHeight - drawableHeight * scale) / 2F); - - } else if (mScaleType == ScaleType.CENTER_INSIDE) { - float scale = Math.min(1.0f, Math.min(widthScale, heightScale)); - mBaseMatrix.postScale(scale, scale); - mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F, - (viewHeight - drawableHeight * scale) / 2F); - - } else { - RectF mTempSrc = new RectF(0, 0, drawableWidth, drawableHeight); - RectF mTempDst = new RectF(0, 0, viewWidth, viewHeight); - - switch (mScaleType) { - case FIT_CENTER: - mBaseMatrix - .setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER); - break; - - case FIT_START: - mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START); - break; - - case FIT_END: - mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END); - break; - - case FIT_XY: - mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.FILL); - break; - - default: - break; - } - } - - resetMatrix(); - } - - private int getImageViewWidth(ImageView imageView) { - if (null == imageView) - return 0; - return imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight(); - } - - private int getImageViewHeight(ImageView imageView) { - if (null == imageView) - return 0; - return imageView.getHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom(); - } - - /** - * Interface definition for a callback to be invoked when the internal Matrix has changed for - * this View. - * - * @author Chris Banes - */ - public static interface OnMatrixChangedListener { - /** - * Callback for when the Matrix displaying the Drawable has changed. This could be because - * the View's bounds have changed, or the user has zoomed. - * - * @param rect - Rectangle displaying the Drawable's new bounds. - */ - void onMatrixChanged(RectF rect); - } - - /** - * Interface definition for a callback to be invoked when the Photo is tapped with a single - * tap. - * - * @author Chris Banes - */ - public static interface OnPhotoTapListener { - - /** - * A callback to receive where the user taps on a photo. You will only receive a callback if - * the user taps on the actual photo, tapping on 'whitespace' will be ignored. - * - * @param view - View the user tapped. - * @param x - where the user tapped from the of the Drawable, as percentage of the - * Drawable width. - * @param y - where the user tapped from the top of the Drawable, as percentage of the - * Drawable height. - */ - void onPhotoTap(View view, float x, float y); - } - - /** - * Interface definition for a callback to be invoked when the ImageView is tapped with a single - * tap. - * - * @author Chris Banes - */ - public static interface OnViewTapListener { - - /** - * A callback to receive where the user taps on a ImageView. You will receive a callback if - * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. - * - * @param view - View the user tapped. - * @param x - where the user tapped from the left of the View. - * @param y - where the user tapped from the top of the View. - */ - void onViewTap(View view, float x, float y); - } - - private class AnimatedZoomRunnable implements Runnable { - - private final float mFocalX, mFocalY; - private final long mStartTime; - private final float mZoomStart, mZoomEnd; - - public AnimatedZoomRunnable(final float currentZoom, final float targetZoom, - final float focalX, final float focalY) { - mFocalX = focalX; - mFocalY = focalY; - mStartTime = System.currentTimeMillis(); - mZoomStart = currentZoom; - mZoomEnd = targetZoom; - } - - @Override - public void run() { - ImageView imageView = getImageView(); - if (imageView == null) { - return; - } - - float t = interpolate(); - float scale = mZoomStart + t * (mZoomEnd - mZoomStart); - float deltaScale = scale / getScale(); - - mSuppMatrix.postScale(deltaScale, deltaScale, mFocalX, mFocalY); - checkAndDisplayMatrix(); - - // We haven't hit our target scale yet, so post ourselves again - if (t < 1f) { - Compat.postOnAnimation(imageView, this); - } - } - - private float interpolate() { - float t = 1f * (System.currentTimeMillis() - mStartTime) / ZOOM_DURATION; - t = Math.min(1f, t); - t = sInterpolator.getInterpolation(t); - return t; - } - } - - private class FlingRunnable implements Runnable { - - private final ScrollerProxy mScroller; - private int mCurrentX, mCurrentY; - - public FlingRunnable(Context context) { - mScroller = ScrollerProxy.getScroller(context); - } - - public void cancelFling() { - if (DEBUG) { - QLog.getLogger().d(LOG_TAG, "Cancel Fling"); - } - mScroller.forceFinished(true); - } - - public void fling(int viewWidth, int viewHeight, int velocityX, - int velocityY) { - final RectF rect = getDisplayRect(); - if (null == rect) { - return; - } - - final int startX = Math.round(-rect.left); - final int minX, maxX, minY, maxY; - - if (viewWidth < rect.width()) { - minX = 0; - maxX = Math.round(rect.width() - viewWidth); - } else { - minX = maxX = startX; - } - - final int startY = Math.round(-rect.top); - if (viewHeight < rect.height()) { - minY = 0; - maxY = Math.round(rect.height() - viewHeight); - } else { - minY = maxY = startY; - } - - mCurrentX = startX; - mCurrentY = startY; - - if (DEBUG) { - QLog.getLogger().d( - LOG_TAG, - "fling. StartX:" + startX + " StartY:" + startY - + " MaxX:" + maxX + " MaxY:" + maxY); - } - - // If we actually can move, fling the scroller - if (startX != maxX || startY != maxY) { - mScroller.fling(startX, startY, velocityX, velocityY, minX, - maxX, minY, maxY, 0, 0); - } - } - - @Override - public void run() { - if (mScroller.isFinished()) { - return; // remaining post that should not be handled - } - - ImageView imageView = getImageView(); - if (null != imageView && mScroller.computeScrollOffset()) { - - final int newX = mScroller.getCurrX(); - final int newY = mScroller.getCurrY(); - - if (DEBUG) { - QLog.getLogger().d( - LOG_TAG, - "fling run(). CurrentX:" + mCurrentX + " CurrentY:" - + mCurrentY + " NewX:" + newX + " NewY:" - + newY); - } - - mSuppMatrix.postTranslate(mCurrentX - newX, mCurrentY - newY); - setImageViewMatrix(getDrawMatrix()); - - mCurrentX = newX; - mCurrentY = newY; - - // Post On animation - Compat.postOnAnimation(imageView, this); - } - } - } -} diff --git a/qy/src/main/java/uk/co/senab/photoview/gestures/CupcakeGestureDetector.java b/qy/src/main/java/uk/co/senab/photoview/gestures/CupcakeGestureDetector.java deleted file mode 100644 index eca6964..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/gestures/CupcakeGestureDetector.java +++ /dev/null @@ -1,144 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.gestures; - -import android.content.Context; -import android.util.FloatMath; -import android.util.Log; -import android.view.MotionEvent; -import android.view.VelocityTracker; -import android.view.ViewConfiguration; - -public class CupcakeGestureDetector implements GestureDetector { - - protected OnGestureListener mListener; - private static final String LOG_TAG = "CupcakeGestureDetector"; - float mLastTouchX; - float mLastTouchY; - final float mTouchSlop; - final float mMinimumVelocity; - - @Override - public void setOnGestureListener(OnGestureListener listener) { - this.mListener = listener; - } - - public CupcakeGestureDetector(Context context) { - final ViewConfiguration configuration = ViewConfiguration - .get(context); - mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); - mTouchSlop = configuration.getScaledTouchSlop(); - } - - private VelocityTracker mVelocityTracker; - private boolean mIsDragging; - - float getActiveX(MotionEvent ev) { - return ev.getX(); - } - - float getActiveY(MotionEvent ev) { - return ev.getY(); - } - - @Override - public boolean isScaling() { - return false; - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - switch (ev.getAction()) { - case MotionEvent.ACTION_DOWN: { - mVelocityTracker = VelocityTracker.obtain(); - if (null != mVelocityTracker) { - mVelocityTracker.addMovement(ev); - } else { - Log.i(LOG_TAG, "Velocity tracker is null"); - } - - mLastTouchX = getActiveX(ev); - mLastTouchY = getActiveY(ev); - mIsDragging = false; - break; - } - - case MotionEvent.ACTION_MOVE: { - final float x = getActiveX(ev); - final float y = getActiveY(ev); - final float dx = x - mLastTouchX, dy = y - mLastTouchY; - - if (!mIsDragging) { - // Use Pythagoras to see if drag length is larger than - // touch slop - mIsDragging = (float)Math.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop; - } - - if (mIsDragging) { - mListener.onDrag(dx, dy); - mLastTouchX = x; - mLastTouchY = y; - - if (null != mVelocityTracker) { - mVelocityTracker.addMovement(ev); - } - } - break; - } - - case MotionEvent.ACTION_CANCEL: { - // Recycle Velocity Tracker - if (null != mVelocityTracker) { - mVelocityTracker.recycle(); - mVelocityTracker = null; - } - break; - } - - case MotionEvent.ACTION_UP: { - if (mIsDragging) { - if (null != mVelocityTracker) { - mLastTouchX = getActiveX(ev); - mLastTouchY = getActiveY(ev); - - // Compute velocity within the last 1000ms - mVelocityTracker.addMovement(ev); - mVelocityTracker.computeCurrentVelocity(1000); - - final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker - .getYVelocity(); - - // If the velocity is greater than minVelocity, call - // listener - if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) { - mListener.onFling(mLastTouchX, mLastTouchY, -vX, - -vY); - } - } - } - - // Recycle Velocity Tracker - if (null != mVelocityTracker) { - mVelocityTracker.recycle(); - mVelocityTracker = null; - } - break; - } - } - - return true; - } -} diff --git a/qy/src/main/java/uk/co/senab/photoview/gestures/EclairGestureDetector.java b/qy/src/main/java/uk/co/senab/photoview/gestures/EclairGestureDetector.java deleted file mode 100644 index 2d5215b..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/gestures/EclairGestureDetector.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.gestures; - -import android.annotation.TargetApi; -import android.content.Context; -import android.view.MotionEvent; - -import uk.co.senab.photoview.Compat; - -@TargetApi(5) -public class EclairGestureDetector extends CupcakeGestureDetector { - - private static final int INVALID_POINTER_ID = -1; - private int mActivePointerId = INVALID_POINTER_ID; - private int mActivePointerIndex = 0; - - public EclairGestureDetector(Context context) { - super(context); - } - - @Override - float getActiveX(MotionEvent ev) { - try { - return ev.getX(mActivePointerIndex); - } catch (Exception e) { - return ev.getX(); - } - } - - @Override - float getActiveY(MotionEvent ev) { - try { - return ev.getY(mActivePointerIndex); - } catch (Exception e) { - return ev.getY(); - } - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - final int action = ev.getAction(); - switch (action & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - mActivePointerId = ev.getPointerId(0); - break; - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: - mActivePointerId = INVALID_POINTER_ID; - break; - case MotionEvent.ACTION_POINTER_UP: - // Ignore deprecation, ACTION_POINTER_ID_MASK and - // ACTION_POINTER_ID_SHIFT has same value and are deprecated - // You can have either deprecation or lint target api warning - final int pointerIndex = Compat.getPointerIndex(ev.getAction()); - final int pointerId = ev.getPointerId(pointerIndex); - if (pointerId == mActivePointerId) { - // This was our active pointer going up. Choose a new - // active pointer and adjust accordingly. - final int newPointerIndex = pointerIndex == 0 ? 1 : 0; - mActivePointerId = ev.getPointerId(newPointerIndex); - mLastTouchX = ev.getX(newPointerIndex); - mLastTouchY = ev.getY(newPointerIndex); - } - break; - } - - mActivePointerIndex = ev - .findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId - : 0); - return super.onTouchEvent(ev); - } -} diff --git a/qy/src/main/java/uk/co/senab/photoview/gestures/FroyoGestureDetector.java b/qy/src/main/java/uk/co/senab/photoview/gestures/FroyoGestureDetector.java deleted file mode 100644 index c76c222..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/gestures/FroyoGestureDetector.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.gestures; - -import android.annotation.TargetApi; -import android.content.Context; -import android.view.MotionEvent; -import android.view.ScaleGestureDetector; - -@TargetApi(8) -public class FroyoGestureDetector extends EclairGestureDetector { - - protected final ScaleGestureDetector mDetector; - - public FroyoGestureDetector(Context context) { - super(context); - ScaleGestureDetector.OnScaleGestureListener mScaleListener = new ScaleGestureDetector.OnScaleGestureListener() { - - @Override - public boolean onScale(ScaleGestureDetector detector) { - float scaleFactor = detector.getScaleFactor(); - - if (Float.isNaN(scaleFactor) || Float.isInfinite(scaleFactor)) - return false; - - mListener.onScale(scaleFactor, - detector.getFocusX(), detector.getFocusY()); - return true; - } - - @Override - public boolean onScaleBegin(ScaleGestureDetector detector) { - return true; - } - - @Override - public void onScaleEnd(ScaleGestureDetector detector) { - // NO-OP - } - }; - mDetector = new ScaleGestureDetector(context, mScaleListener); - } - - @Override - public boolean isScaling() { - return mDetector.isInProgress(); - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - mDetector.onTouchEvent(ev); - return super.onTouchEvent(ev); - } - -} diff --git a/qy/src/main/java/uk/co/senab/photoview/gestures/GestureDetector.java b/qy/src/main/java/uk/co/senab/photoview/gestures/GestureDetector.java deleted file mode 100644 index 5433fe6..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/gestures/GestureDetector.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.gestures; - -import android.view.MotionEvent; - -public interface GestureDetector { - - public boolean onTouchEvent(MotionEvent ev); - - public boolean isScaling(); - - public void setOnGestureListener(OnGestureListener listener); - -} diff --git a/qy/src/main/java/uk/co/senab/photoview/gestures/OnGestureListener.java b/qy/src/main/java/uk/co/senab/photoview/gestures/OnGestureListener.java deleted file mode 100644 index d0555ce..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/gestures/OnGestureListener.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.gestures; - -public interface OnGestureListener { - - public void onDrag(float dx, float dy); - - public void onFling(float startX, float startY, float velocityX, - float velocityY); - - public void onScale(float scaleFactor, float focusX, float focusY); - -} \ No newline at end of file diff --git a/qy/src/main/java/uk/co/senab/photoview/gestures/VersionedGestureDetector.java b/qy/src/main/java/uk/co/senab/photoview/gestures/VersionedGestureDetector.java deleted file mode 100644 index c1550ce..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/gestures/VersionedGestureDetector.java +++ /dev/null @@ -1,42 +0,0 @@ -package uk.co.senab.photoview.gestures; - -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import android.content.Context; -import android.os.Build; - -public final class VersionedGestureDetector { - - public static GestureDetector newInstance(Context context, - OnGestureListener listener) { - final int sdkVersion = Build.VERSION.SDK_INT; - GestureDetector detector; - - if (sdkVersion < Build.VERSION_CODES.ECLAIR) { - detector = new CupcakeGestureDetector(context); - } else if (sdkVersion < Build.VERSION_CODES.FROYO) { - detector = new EclairGestureDetector(context); - } else { - detector = new FroyoGestureDetector(context); - } - - detector.setOnGestureListener(listener); - - return detector; - } - -} \ No newline at end of file diff --git a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/GingerScroller.java b/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/GingerScroller.java deleted file mode 100644 index c58cdb9..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/GingerScroller.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.scrollerproxy; - -import android.annotation.TargetApi; -import android.content.Context; -import android.widget.OverScroller; - -@TargetApi(9) -public class GingerScroller extends ScrollerProxy { - - protected final OverScroller mScroller; - private boolean mFirstScroll = false; - - public GingerScroller(Context context) { - mScroller = new OverScroller(context); - } - - @Override - public boolean computeScrollOffset() { - // Workaround for first scroll returning 0 for the direction of the edge it hits. - // Simply recompute values. - if (mFirstScroll) { - mScroller.computeScrollOffset(); - mFirstScroll = false; - } - return mScroller.computeScrollOffset(); - } - - @Override - public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY, - int overX, int overY) { - mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, overX, overY); - } - - @Override - public void forceFinished(boolean finished) { - mScroller.forceFinished(finished); - } - - @Override - public boolean isFinished() { - return mScroller.isFinished(); - } - - @Override - public int getCurrX() { - return mScroller.getCurrX(); - } - - @Override - public int getCurrY() { - return mScroller.getCurrY(); - } -} \ No newline at end of file diff --git a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/IcsScroller.java b/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/IcsScroller.java deleted file mode 100644 index 10f9eab..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/IcsScroller.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.scrollerproxy; - -import android.annotation.TargetApi; -import android.content.Context; - -@TargetApi(14) -public class IcsScroller extends GingerScroller { - - public IcsScroller(Context context) { - super(context); - } - - @Override - public boolean computeScrollOffset() { - return mScroller.computeScrollOffset(); - } - -} diff --git a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/PreGingerScroller.java b/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/PreGingerScroller.java deleted file mode 100644 index 7340696..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/PreGingerScroller.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.scrollerproxy; - -import android.content.Context; -import android.widget.Scroller; - -public class PreGingerScroller extends ScrollerProxy { - - private final Scroller mScroller; - - public PreGingerScroller(Context context) { - mScroller = new Scroller(context); - } - - @Override - public boolean computeScrollOffset() { - return mScroller.computeScrollOffset(); - } - - @Override - public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY, - int overX, int overY) { - mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY); - } - - @Override - public void forceFinished(boolean finished) { - mScroller.forceFinished(finished); - } - - @Override - public boolean isFinished() { - return mScroller.isFinished(); - } - - @Override - public int getCurrX() { - return mScroller.getCurrX(); - } - - @Override - public int getCurrY() { - return mScroller.getCurrY(); - } -} \ No newline at end of file diff --git a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/ScrollerProxy.java b/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/ScrollerProxy.java deleted file mode 100644 index ce39ef1..0000000 --- a/qy/src/main/java/uk/co/senab/photoview/scrollerproxy/ScrollerProxy.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2011, 2012 Chris Banes. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package uk.co.senab.photoview.scrollerproxy; - -import android.content.Context; -import android.os.Build.VERSION; -import android.os.Build.VERSION_CODES; - -public abstract class ScrollerProxy { - - public static ScrollerProxy getScroller(Context context) { - if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) { - return new PreGingerScroller(context); - } else if (VERSION.SDK_INT < VERSION_CODES.ICE_CREAM_SANDWICH) { - return new GingerScroller(context); - } else { - return new IcsScroller(context); - } - } - - public abstract boolean computeScrollOffset(); - - public abstract void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, - int maxY, int overX, int overY); - - public abstract void forceFinished(boolean finished); - - public abstract boolean isFinished(); - - public abstract int getCurrX(); - - public abstract int getCurrY(); - - -} diff --git a/qy/src/main/jniLibs/armeabi-v7a/libBDSpeechDecoder_V1.so b/qy/src/main/jniLibs/armeabi-v7a/libBDSpeechDecoder_V1.so deleted file mode 100644 index 84d731c..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libBDSpeechDecoder_V1.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_base_v4_2_0.so b/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_base_v4_2_0.so deleted file mode 100644 index 04e93a0..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_base_v4_2_0.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_bikenavi_v4_2_0.so b/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_bikenavi_v4_2_0.so deleted file mode 100644 index 08ae842..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_bikenavi_v4_2_0.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_map_for_bikenavi_v4_2_0.so b/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_map_for_bikenavi_v4_2_0.so deleted file mode 100644 index 77cdb59..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libBaiduMapSDK_map_for_bikenavi_v4_2_0.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libbd_etts.so b/qy/src/main/jniLibs/armeabi-v7a/libbd_etts.so deleted file mode 100644 index d2c3907..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libbd_etts.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libbdtts.so b/qy/src/main/jniLibs/armeabi-v7a/libbdtts.so deleted file mode 100644 index 740be2c..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libbdtts.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libbspatch.so b/qy/src/main/jniLibs/armeabi-v7a/libbspatch.so deleted file mode 100644 index c7fbeaf..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libbspatch.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libconceal.so b/qy/src/main/jniLibs/armeabi-v7a/libconceal.so deleted file mode 100644 index 4ffd699..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libconceal.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libgnustl_shared.so b/qy/src/main/jniLibs/armeabi-v7a/libgnustl_shared.so deleted file mode 100644 index 8b6fde1..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libgnustl_shared.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/liblocSDK6a.so b/qy/src/main/jniLibs/armeabi-v7a/liblocSDK6a.so deleted file mode 100644 index 83f7f12..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/liblocSDK6a.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi-v7a/libvi_voslib.so b/qy/src/main/jniLibs/armeabi-v7a/libvi_voslib.so deleted file mode 100644 index f26a517..0000000 Binary files a/qy/src/main/jniLibs/armeabi-v7a/libvi_voslib.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libBDSpeechDecoder_V1.so b/qy/src/main/jniLibs/armeabi/libBDSpeechDecoder_V1.so deleted file mode 100644 index dca98c7..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libBDSpeechDecoder_V1.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v4_2_0.so b/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v4_2_0.so deleted file mode 100644 index 0367aab..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_base_v4_2_0.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_bikenavi_v4_2_0.so b/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_bikenavi_v4_2_0.so deleted file mode 100644 index 94359c0..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_bikenavi_v4_2_0.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_map_for_bikenavi_v4_2_0.so b/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_map_for_bikenavi_v4_2_0.so deleted file mode 100644 index 663ec84..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libBaiduMapSDK_map_for_bikenavi_v4_2_0.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libbd_etts.so b/qy/src/main/jniLibs/armeabi/libbd_etts.so deleted file mode 100644 index 8c1b8dd..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libbd_etts.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libbdtts.so b/qy/src/main/jniLibs/armeabi/libbdtts.so deleted file mode 100644 index 2ddd6c1..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libbdtts.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libbspatch.so b/qy/src/main/jniLibs/armeabi/libbspatch.so deleted file mode 100644 index c7fbeaf..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libbspatch.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libconceal.so b/qy/src/main/jniLibs/armeabi/libconceal.so deleted file mode 100644 index 4ffd699..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libconceal.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libgnustl_shared.so b/qy/src/main/jniLibs/armeabi/libgnustl_shared.so deleted file mode 100644 index bb2c8b6..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libgnustl_shared.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/liblocSDK6a.so b/qy/src/main/jniLibs/armeabi/liblocSDK6a.so deleted file mode 100644 index 83f7f12..0000000 Binary files a/qy/src/main/jniLibs/armeabi/liblocSDK6a.so and /dev/null differ diff --git a/qy/src/main/jniLibs/armeabi/libvi_voslib.so b/qy/src/main/jniLibs/armeabi/libvi_voslib.so deleted file mode 100644 index f26a517..0000000 Binary files a/qy/src/main/jniLibs/armeabi/libvi_voslib.so and /dev/null differ diff --git a/qy/src/main/res/anim/push_left_in.xml b/qy/src/main/res/anim/push_left_in.xml deleted file mode 100644 index 91d2aec..0000000 --- a/qy/src/main/res/anim/push_left_in.xml +++ /dev/null @@ -1,208 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qy/src/main/res/anim/push_left_in_bak.xml b/qy/src/main/res/anim/push_left_in_bak.xml deleted file mode 100644 index 18fe31c..0000000 --- a/qy/src/main/res/anim/push_left_in_bak.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/qy/src/main/res/anim/push_left_out.xml b/qy/src/main/res/anim/push_left_out.xml deleted file mode 100644 index 536b11c..0000000 --- a/qy/src/main/res/anim/push_left_out.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - diff --git a/qy/src/main/res/anim/push_up_in.xml b/qy/src/main/res/anim/push_up_in.xml deleted file mode 100644 index 5168f71..0000000 --- a/qy/src/main/res/anim/push_up_in.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/qy/src/main/res/anim/push_up_out.xml b/qy/src/main/res/anim/push_up_out.xml deleted file mode 100644 index c181266..0000000 --- a/qy/src/main/res/anim/push_up_out.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/qy/src/main/res/anim/umeng_socialize_fade_in.xml b/qy/src/main/res/anim/umeng_socialize_fade_in.xml deleted file mode 100644 index 12262db..0000000 --- a/qy/src/main/res/anim/umeng_socialize_fade_in.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/anim/umeng_socialize_fade_out.xml b/qy/src/main/res/anim/umeng_socialize_fade_out.xml deleted file mode 100644 index d05bb1a..0000000 --- a/qy/src/main/res/anim/umeng_socialize_fade_out.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/anim/umeng_socialize_shareboard_animation_in.xml b/qy/src/main/res/anim/umeng_socialize_shareboard_animation_in.xml deleted file mode 100644 index 669055a..0000000 --- a/qy/src/main/res/anim/umeng_socialize_shareboard_animation_in.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - diff --git a/qy/src/main/res/anim/umeng_socialize_shareboard_animation_out.xml b/qy/src/main/res/anim/umeng_socialize_shareboard_animation_out.xml deleted file mode 100644 index a17c9dd..0000000 --- a/qy/src/main/res/anim/umeng_socialize_shareboard_animation_out.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - diff --git a/qy/src/main/res/anim/umeng_socialize_slide_in_from_bottom.xml b/qy/src/main/res/anim/umeng_socialize_slide_in_from_bottom.xml deleted file mode 100644 index 7820c1c..0000000 --- a/qy/src/main/res/anim/umeng_socialize_slide_in_from_bottom.xml +++ /dev/null @@ -1,7 +0,0 @@ - - diff --git a/qy/src/main/res/anim/umeng_socialize_slide_out_from_bottom.xml b/qy/src/main/res/anim/umeng_socialize_slide_out_from_bottom.xml deleted file mode 100644 index 4d474cd..0000000 --- a/qy/src/main/res/anim/umeng_socialize_slide_out_from_bottom.xml +++ /dev/null @@ -1,7 +0,0 @@ - - \ No newline at end of file diff --git a/qy/src/main/res/anim/welcome_animation.xml b/qy/src/main/res/anim/welcome_animation.xml deleted file mode 100644 index 6c9df31..0000000 --- a/qy/src/main/res/anim/welcome_animation.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/button_color.xml b/qy/src/main/res/drawable-hdpi/button_color.xml deleted file mode 100644 index 14d132d..0000000 --- a/qy/src/main/res/drawable-hdpi/button_color.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/button_down.png b/qy/src/main/res/drawable-hdpi/button_down.png deleted file mode 100644 index e8bd757..0000000 Binary files a/qy/src/main/res/drawable-hdpi/button_down.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/button_on.png b/qy/src/main/res/drawable-hdpi/button_on.png deleted file mode 100644 index 3731bba..0000000 Binary files a/qy/src/main/res/drawable-hdpi/button_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/button_simple_style.xml b/qy/src/main/res/drawable-hdpi/button_simple_style.xml deleted file mode 100644 index ec0b290..0000000 --- a/qy/src/main/res/drawable-hdpi/button_simple_style.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/button_style.xml b/qy/src/main/res/drawable-hdpi/button_style.xml deleted file mode 100644 index d6e0dc8..0000000 --- a/qy/src/main/res/drawable-hdpi/button_style.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/buttonlayout.xml b/qy/src/main/res/drawable-hdpi/buttonlayout.xml deleted file mode 100644 index aed76cc..0000000 --- a/qy/src/main/res/drawable-hdpi/buttonlayout.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/custom_btn_beige.xml b/qy/src/main/res/drawable-hdpi/custom_btn_beige.xml deleted file mode 100644 index 01a54fe..0000000 --- a/qy/src/main/res/drawable-hdpi/custom_btn_beige.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/delete_x.png b/qy/src/main/res/drawable-hdpi/delete_x.png deleted file mode 100644 index 5b4244f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/delete_x.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/drag.9.png b/qy/src/main/res/drawable-hdpi/drag.9.png deleted file mode 100644 index 646c2eb..0000000 Binary files a/qy/src/main/res/drawable-hdpi/drag.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/flatmap.png b/qy/src/main/res/drawable-hdpi/flatmap.png deleted file mode 100644 index e331017..0000000 Binary files a/qy/src/main/res/drawable-hdpi/flatmap.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/head_linearlayout.xml b/qy/src/main/res/drawable-hdpi/head_linearlayout.xml deleted file mode 100644 index b2f52b9..0000000 --- a/qy/src/main/res/drawable-hdpi/head_linearlayout.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/ic_launcher.png b/qy/src/main/res/drawable-hdpi/ic_launcher.png deleted file mode 100644 index 1f405d2..0000000 Binary files a/qy/src/main/res/drawable-hdpi/ic_launcher.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_ablogo.png b/qy/src/main/res/drawable-hdpi/icon_ablogo.png deleted file mode 100644 index bf7fadc..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_ablogo.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_actbanner.jpeg b/qy/src/main/res/drawable-hdpi/icon_actbanner.jpeg deleted file mode 100644 index fd5b8b5..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_actbanner.jpeg and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_archive.png b/qy/src/main/res/drawable-hdpi/icon_archive.png deleted file mode 100644 index 8df8b56..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_archive.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_arrowb.png b/qy/src/main/res/drawable-hdpi/icon_arrowb.png deleted file mode 100644 index 0a9588d..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_arrowb.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_auto_zoom.png b/qy/src/main/res/drawable-hdpi/icon_auto_zoom.png deleted file mode 100644 index befa4c7..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_auto_zoom.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_auto_zoom_inactive.png b/qy/src/main/res/drawable-hdpi/icon_auto_zoom_inactive.png deleted file mode 100644 index de54447..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_auto_zoom_inactive.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_award.png b/qy/src/main/res/drawable-hdpi/icon_award.png deleted file mode 100644 index d181f1d..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_award.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_award_in.png b/qy/src/main/res/drawable-hdpi/icon_award_in.png deleted file mode 100644 index d058f58..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_award_in.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_banner.jpg b/qy/src/main/res/drawable-hdpi/icon_banner.jpg deleted file mode 100644 index c4b8544..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_banner.jpg and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_bend.png b/qy/src/main/res/drawable-hdpi/icon_bend.png deleted file mode 100644 index f221649..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_bend.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_bikebanner.jpg b/qy/src/main/res/drawable-hdpi/icon_bikebanner.jpg deleted file mode 100644 index bde8fa4..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_bikebanner.jpg and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_bstart.png b/qy/src/main/res/drawable-hdpi/icon_bstart.png deleted file mode 100644 index 9dc555f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_bstart.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_busy.png b/qy/src/main/res/drawable-hdpi/icon_busy.png deleted file mode 100644 index ad9971a..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_busy.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_catetop.png b/qy/src/main/res/drawable-hdpi/icon_catetop.png deleted file mode 100644 index 745758a..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_catetop.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_chain2.png b/qy/src/main/res/drawable-hdpi/icon_chain2.png deleted file mode 100644 index d187c22..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_chain2.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_chainbanner.jpg b/qy/src/main/res/drawable-hdpi/icon_chainbanner.jpg deleted file mode 100644 index 2f20f00..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_chainbanner.jpg and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_chart.png b/qy/src/main/res/drawable-hdpi/icon_chart.png deleted file mode 100644 index 042179b..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_chart.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_chart2.png b/qy/src/main/res/drawable-hdpi/icon_chart2.png deleted file mode 100644 index 33b5d22..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_chart2.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_check.png b/qy/src/main/res/drawable-hdpi/icon_check.png deleted file mode 100644 index 571b032..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_check.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_cloud.png b/qy/src/main/res/drawable-hdpi/icon_cloud.png deleted file mode 100644 index 4ace08a..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_cloud.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_clouds.png b/qy/src/main/res/drawable-hdpi/icon_clouds.png deleted file mode 100644 index 472da4a..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_clouds.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_cloudsearch.png b/qy/src/main/res/drawable-hdpi/icon_cloudsearch.png deleted file mode 100644 index e39c598..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_cloudsearch.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_coins.png b/qy/src/main/res/drawable-hdpi/icon_coins.png deleted file mode 100644 index 96818cd..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_coins.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_comment.png b/qy/src/main/res/drawable-hdpi/icon_comment.png deleted file mode 100644 index 755b9fd..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_comment.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_cross.png b/qy/src/main/res/drawable-hdpi/icon_cross.png deleted file mode 100644 index f1c2d68..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_cross.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_databse.png b/qy/src/main/res/drawable-hdpi/icon_databse.png deleted file mode 100644 index ce516dd..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_databse.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_direction.png b/qy/src/main/res/drawable-hdpi/icon_direction.png deleted file mode 100644 index acbb02d..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_direction.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_direction_small.png b/qy/src/main/res/drawable-hdpi/icon_direction_small.png deleted file mode 100644 index 8dc5319..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_direction_small.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_dist.png b/qy/src/main/res/drawable-hdpi/icon_dist.png deleted file mode 100644 index 61b0b24..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_dist.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_dist_in.png b/qy/src/main/res/drawable-hdpi/icon_dist_in.png deleted file mode 100644 index 832bebc..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_dist_in.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_document.png b/qy/src/main/res/drawable-hdpi/icon_document.png deleted file mode 100644 index a1e999e..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_document.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_documents.png b/qy/src/main/res/drawable-hdpi/icon_documents.png deleted file mode 100644 index 441d6c9..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_documents.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_download.png b/qy/src/main/res/drawable-hdpi/icon_download.png deleted file mode 100644 index c2e1dbe..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_download.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_edit.png b/qy/src/main/res/drawable-hdpi/icon_edit.png deleted file mode 100644 index 424a721..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_edit.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_en.png b/qy/src/main/res/drawable-hdpi/icon_en.png deleted file mode 100644 index a040521..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_en.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_footmark.png b/qy/src/main/res/drawable-hdpi/icon_footmark.png deleted file mode 100644 index b63d723..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_footmark.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_fullscreen.png b/qy/src/main/res/drawable-hdpi/icon_fullscreen.png deleted file mode 100644 index b44fc77..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_fullscreen.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_gear.png b/qy/src/main/res/drawable-hdpi/icon_gear.png deleted file mode 100644 index 0f3e1a6..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_gear.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_gears.png b/qy/src/main/res/drawable-hdpi/icon_gears.png deleted file mode 100644 index fe0367c..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_gears.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_geo.png b/qy/src/main/res/drawable-hdpi/icon_geo.png deleted file mode 100644 index f0194a3..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_geo.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_gift.png b/qy/src/main/res/drawable-hdpi/icon_gift.png deleted file mode 100644 index 1c51338..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_gift.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_go.png b/qy/src/main/res/drawable-hdpi/icon_go.png deleted file mode 100644 index 6f5520e..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_go.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_go_in.png b/qy/src/main/res/drawable-hdpi/icon_go_in.png deleted file mode 100644 index 5440da5..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_go_in.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_group.png b/qy/src/main/res/drawable-hdpi/icon_group.png deleted file mode 100644 index 236bfdf..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_group.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_grpbanner.jpg b/qy/src/main/res/drawable-hdpi/icon_grpbanner.jpg deleted file mode 100644 index 8f211e6..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_grpbanner.jpg and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_hearts.png b/qy/src/main/res/drawable-hdpi/icon_hearts.png deleted file mode 100644 index ebaeda1..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_hearts.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_km.png b/qy/src/main/res/drawable-hdpi/icon_km.png deleted file mode 100644 index fcce890..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_km.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_livelist.png b/qy/src/main/res/drawable-hdpi/icon_livelist.png deleted file mode 100644 index fffcfad..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_livelist.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_livelistoff.png b/qy/src/main/res/drawable-hdpi/icon_livelistoff.png deleted file mode 100644 index 354f975..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_livelistoff.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_lock.png b/qy/src/main/res/drawable-hdpi/icon_lock.png deleted file mode 100644 index 93fe7c9..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_lock.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_maintop.png b/qy/src/main/res/drawable-hdpi/icon_maintop.png deleted file mode 100644 index ad5a72d..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_maintop.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_novoice.png b/qy/src/main/res/drawable-hdpi/icon_novoice.png deleted file mode 100644 index 8c236f7..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_novoice.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_pass.png b/qy/src/main/res/drawable-hdpi/icon_pass.png deleted file mode 100644 index 354b031..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_pass.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_play.png b/qy/src/main/res/drawable-hdpi/icon_play.png deleted file mode 100644 index c41a789..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_play.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_plpause.png b/qy/src/main/res/drawable-hdpi/icon_plpause.png deleted file mode 100644 index 14a2ede..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_plpause.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_plresume.png b/qy/src/main/res/drawable-hdpi/icon_plresume.png deleted file mode 100644 index ef82338..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_plresume.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_plstop.png b/qy/src/main/res/drawable-hdpi/icon_plstop.png deleted file mode 100644 index 3b9e6e2..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_plstop.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_plus.png b/qy/src/main/res/drawable-hdpi/icon_plus.png deleted file mode 100644 index 4f1f84b..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_plus.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_puzzle.png b/qy/src/main/res/drawable-hdpi/icon_puzzle.png deleted file mode 100644 index 40dc8eb..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_puzzle.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_radio.png b/qy/src/main/res/drawable-hdpi/icon_radio.png deleted file mode 100644 index 260aca7..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_radio.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_radio_in.png b/qy/src/main/res/drawable-hdpi/icon_radio_in.png deleted file mode 100644 index 4881ec2..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_radio_in.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_rest.png b/qy/src/main/res/drawable-hdpi/icon_rest.png deleted file mode 100644 index 04b4111..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_rest.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_riding64.png b/qy/src/main/res/drawable-hdpi/icon_riding64.png deleted file mode 100644 index f0f23c4..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_riding64.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_roadbook.png b/qy/src/main/res/drawable-hdpi/icon_roadbook.png deleted file mode 100644 index 6b08526..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_roadbook.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_roadbook1.png b/qy/src/main/res/drawable-hdpi/icon_roadbook1.png deleted file mode 100644 index d018c24..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_roadbook1.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_rotation.png b/qy/src/main/res/drawable-hdpi/icon_rotation.png deleted file mode 100644 index efe3399..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_rotation.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_rotation_inactive.png b/qy/src/main/res/drawable-hdpi/icon_rotation_inactive.png deleted file mode 100644 index 512885c..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_rotation_inactive.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_scale.9.png b/qy/src/main/res/drawable-hdpi/icon_scale.9.png deleted file mode 100644 index 4f5b238..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_scale.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_scan.png b/qy/src/main/res/drawable-hdpi/icon_scan.png deleted file mode 100644 index d71fdc0..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_scan.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_score.png b/qy/src/main/res/drawable-hdpi/icon_score.png deleted file mode 100644 index 0ca9074..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_score.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_search.png b/qy/src/main/res/drawable-hdpi/icon_search.png deleted file mode 100644 index 7a8b10f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_search.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_send.png b/qy/src/main/res/drawable-hdpi/icon_send.png deleted file mode 100644 index 07169bd..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_send.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_sstart.png b/qy/src/main/res/drawable-hdpi/icon_sstart.png deleted file mode 100644 index 9d855ca..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_sstart.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_st.png b/qy/src/main/res/drawable-hdpi/icon_st.png deleted file mode 100644 index eafa7ec..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_st.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_star.png b/qy/src/main/res/drawable-hdpi/icon_star.png deleted file mode 100644 index f55c200..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_star.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_statistics.png b/qy/src/main/res/drawable-hdpi/icon_statistics.png deleted file mode 100644 index 31efbf5..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_statistics.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_statistics2.png b/qy/src/main/res/drawable-hdpi/icon_statistics2.png deleted file mode 100644 index 13a8334..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_statistics2.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_stop.png b/qy/src/main/res/drawable-hdpi/icon_stop.png deleted file mode 100644 index c4f1b37..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_stop.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_subcatetop.png b/qy/src/main/res/drawable-hdpi/icon_subcatetop.png deleted file mode 100644 index 00a4344..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_subcatetop.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_tent.png b/qy/src/main/res/drawable-hdpi/icon_tent.png deleted file mode 100644 index 0c34b5b..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_tent.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_track.png b/qy/src/main/res/drawable-hdpi/icon_track.png deleted file mode 100644 index aa5577c..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_track.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_upload.png b/qy/src/main/res/drawable-hdpi/icon_upload.png deleted file mode 100644 index 1c93524..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_upload.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_user.png b/qy/src/main/res/drawable-hdpi/icon_user.png deleted file mode 100644 index 26dc8b1..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_user.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_voice.png b/qy/src/main/res/drawable-hdpi/icon_voice.png deleted file mode 100644 index daafe95..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_voice.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_wall.png b/qy/src/main/res/drawable-hdpi/icon_wall.png deleted file mode 100644 index c2f472f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_wall.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_wall1.png b/qy/src/main/res/drawable-hdpi/icon_wall1.png deleted file mode 100644 index c285b26..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_wall1.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_waypoint.png b/qy/src/main/res/drawable-hdpi/icon_waypoint.png deleted file mode 100644 index f3083a6..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_waypoint.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_web_32.png b/qy/src/main/res/drawable-hdpi/icon_web_32.png deleted file mode 100644 index ae60c92..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_web_32.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_web_32_in.png b/qy/src/main/res/drawable-hdpi/icon_web_32_in.png deleted file mode 100644 index a9c27d0..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_web_32_in.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_welcome.png b/qy/src/main/res/drawable-hdpi/icon_welcome.png deleted file mode 100644 index 5c81e29..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_welcome.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_welcome_48.png b/qy/src/main/res/drawable-hdpi/icon_welcome_48.png deleted file mode 100644 index 790ed44..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_welcome_48.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/icon_wgb.png b/qy/src/main/res/drawable-hdpi/icon_wgb.png deleted file mode 100644 index 32844a5..0000000 Binary files a/qy/src/main/res/drawable-hdpi/icon_wgb.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/item_head.xml b/qy/src/main/res/drawable-hdpi/item_head.xml deleted file mode 100644 index 6707b96..0000000 --- a/qy/src/main/res/drawable-hdpi/item_head.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/linearlayout.xml b/qy/src/main/res/drawable-hdpi/linearlayout.xml deleted file mode 100644 index 42fb5b5..0000000 --- a/qy/src/main/res/drawable-hdpi/linearlayout.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/linearlayout_horizontal.xml b/qy/src/main/res/drawable-hdpi/linearlayout_horizontal.xml deleted file mode 100644 index 2d6ecb7..0000000 --- a/qy/src/main/res/drawable-hdpi/linearlayout_horizontal.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/linearlayoutborder1.xml b/qy/src/main/res/drawable-hdpi/linearlayoutborder1.xml deleted file mode 100644 index c1b5d18..0000000 --- a/qy/src/main/res/drawable-hdpi/linearlayoutborder1.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/location.png b/qy/src/main/res/drawable-hdpi/location.png deleted file mode 100644 index e99621c..0000000 Binary files a/qy/src/main/res/drawable-hdpi/location.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/nolocation.png b/qy/src/main/res/drawable-hdpi/nolocation.png deleted file mode 100644 index e64b5bb..0000000 Binary files a/qy/src/main/res/drawable-hdpi/nolocation.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/note_linearlayout.xml b/qy/src/main/res/drawable-hdpi/note_linearlayout.xml deleted file mode 100644 index 65c8638..0000000 --- a/qy/src/main/res/drawable-hdpi/note_linearlayout.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/notelist_head.xml b/qy/src/main/res/drawable-hdpi/notelist_head.xml deleted file mode 100644 index f3c3556..0000000 --- a/qy/src/main/res/drawable-hdpi/notelist_head.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/picture.png b/qy/src/main/res/drawable-hdpi/picture.png deleted file mode 100644 index 773115c..0000000 Binary files a/qy/src/main/res/drawable-hdpi/picture.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/picture_inactive.png b/qy/src/main/res/drawable-hdpi/picture_inactive.png deleted file mode 100644 index 1d7c70a..0000000 Binary files a/qy/src/main/res/drawable-hdpi/picture_inactive.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/popup_down.png b/qy/src/main/res/drawable-hdpi/popup_down.png deleted file mode 100644 index 8dad382..0000000 Binary files a/qy/src/main/res/drawable-hdpi/popup_down.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/popup_middle.9.png b/qy/src/main/res/drawable-hdpi/popup_middle.9.png deleted file mode 100644 index 07e897a..0000000 Binary files a/qy/src/main/res/drawable-hdpi/popup_middle.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/popup_middlea.png b/qy/src/main/res/drawable-hdpi/popup_middlea.png deleted file mode 100644 index 750b455..0000000 Binary files a/qy/src/main/res/drawable-hdpi/popup_middlea.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/satellite.png b/qy/src/main/res/drawable-hdpi/satellite.png deleted file mode 100644 index f199b9c..0000000 Binary files a/qy/src/main/res/drawable-hdpi/satellite.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/screenshot.png b/qy/src/main/res/drawable-hdpi/screenshot.png deleted file mode 100644 index b6ca84a..0000000 Binary files a/qy/src/main/res/drawable-hdpi/screenshot.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/small_linearlayout.xml b/qy/src/main/res/drawable-hdpi/small_linearlayout.xml deleted file mode 100644 index 533d667..0000000 --- a/qy/src/main/res/drawable-hdpi/small_linearlayout.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable-hdpi/text_color.xml b/qy/src/main/res/drawable-hdpi/text_color.xml deleted file mode 100644 index 6131312..0000000 --- a/qy/src/main/res/drawable-hdpi/text_color.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/qy/src/main/res/drawable-hdpi/umeng_socialize_light_bar_bg_pad.9.png b/qy/src/main/res/drawable-hdpi/umeng_socialize_light_bar_bg_pad.9.png deleted file mode 100644 index b2b4974..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_socialize_light_bar_bg_pad.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_socialize_nav_bar_bg_pad.9.png b/qy/src/main/res/drawable-hdpi/umeng_socialize_nav_bar_bg_pad.9.png deleted file mode 100644 index 10651c5..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_socialize_nav_bar_bg_pad.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_socialize_oauth_check_off.png b/qy/src/main/res/drawable-hdpi/umeng_socialize_oauth_check_off.png deleted file mode 100644 index cc32791..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_socialize_oauth_check_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_socialize_oauth_check_on.png b/qy/src/main/res/drawable-hdpi/umeng_socialize_oauth_check_on.png deleted file mode 100644 index acb7ba7..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_socialize_oauth_check_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_socialize_share_music.png b/qy/src/main/res/drawable-hdpi/umeng_socialize_share_music.png deleted file mode 100644 index ad07270..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_socialize_share_music.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_socialize_share_pic.png b/qy/src/main/res/drawable-hdpi/umeng_socialize_share_pic.png deleted file mode 100644 index 09ef645..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_socialize_share_pic.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_socialize_share_video.png b/qy/src/main/res/drawable-hdpi/umeng_socialize_share_video.png deleted file mode 100644 index c4087d6..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_socialize_share_video.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_focused_holo_light.png b/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_focused_holo_light.png deleted file mode 100644 index adedc85..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_focused_holo_light.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_holo_light.png b/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_holo_light.png deleted file mode 100644 index b1b52b2..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_holo_light.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_pressed_holo_light.png b/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_pressed_holo_light.png deleted file mode 100644 index 338f73f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_off_pressed_holo_light.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_focused_holo_light.png b/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_focused_holo_light.png deleted file mode 100644 index dc53ecd..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_focused_holo_light.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_holo_light.png b/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_holo_light.png deleted file mode 100644 index ceb5acf..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_holo_light.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_pressed_holo_light.png b/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_pressed_holo_light.png deleted file mode 100644 index 3c7bc1f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_btn_check_on_pressed_holo_light.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_close_bg_normal.png b/qy/src/main/res/drawable-hdpi/umeng_update_close_bg_normal.png deleted file mode 100644 index ca2d1d8..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_close_bg_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/umeng_update_close_bg_tap.png b/qy/src/main/res/drawable-hdpi/umeng_update_close_bg_tap.png deleted file mode 100644 index 6089f72..0000000 Binary files a/qy/src/main/res/drawable-hdpi/umeng_update_close_bg_tap.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/wayinstructions4.png b/qy/src/main/res/drawable-hdpi/wayinstructions4.png deleted file mode 100644 index 450a1c3..0000000 Binary files a/qy/src/main/res/drawable-hdpi/wayinstructions4.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/wayinstructions_inactive.png b/qy/src/main/res/drawable-hdpi/wayinstructions_inactive.png deleted file mode 100644 index 2fb0ec7..0000000 Binary files a/qy/src/main/res/drawable-hdpi/wayinstructions_inactive.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/zoomin_disable.png b/qy/src/main/res/drawable-hdpi/zoomin_disable.png deleted file mode 100644 index 2a44238..0000000 Binary files a/qy/src/main/res/drawable-hdpi/zoomin_disable.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/zoomin_normal.png b/qy/src/main/res/drawable-hdpi/zoomin_normal.png deleted file mode 100644 index 604e8af..0000000 Binary files a/qy/src/main/res/drawable-hdpi/zoomin_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/zoomin_press.png b/qy/src/main/res/drawable-hdpi/zoomin_press.png deleted file mode 100644 index 1401b60..0000000 Binary files a/qy/src/main/res/drawable-hdpi/zoomin_press.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/zoomout_disable.png b/qy/src/main/res/drawable-hdpi/zoomout_disable.png deleted file mode 100644 index 232ad1d..0000000 Binary files a/qy/src/main/res/drawable-hdpi/zoomout_disable.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/zoomout_normal.png b/qy/src/main/res/drawable-hdpi/zoomout_normal.png deleted file mode 100644 index 21c8c1f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/zoomout_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable-hdpi/zoomout_press.png b/qy/src/main/res/drawable-hdpi/zoomout_press.png deleted file mode 100644 index cf5569f..0000000 Binary files a/qy/src/main/res/drawable-hdpi/zoomout_press.png and /dev/null differ diff --git a/qy/src/main/res/drawable-nodpi/empty_photo.png b/qy/src/main/res/drawable-nodpi/empty_photo.png deleted file mode 100644 index da1478a..0000000 Binary files a/qy/src/main/res/drawable-nodpi/empty_photo.png and /dev/null differ diff --git a/qy/src/main/res/drawable/background_view_rounded_single.xml b/qy/src/main/res/drawable/background_view_rounded_single.xml deleted file mode 100644 index b2fdfb7..0000000 --- a/qy/src/main/res/drawable/background_view_rounded_single.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/button_shape.xml b/qy/src/main/res/drawable/button_shape.xml deleted file mode 100644 index d7fcfd3..0000000 --- a/qy/src/main/res/drawable/button_shape.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/icon_direction.png b/qy/src/main/res/drawable/icon_direction.png deleted file mode 100644 index 8dc5319..0000000 Binary files a/qy/src/main/res/drawable/icon_direction.png and /dev/null differ diff --git a/qy/src/main/res/drawable/progressbar.xml b/qy/src/main/res/drawable/progressbar.xml deleted file mode 100644 index 07bbe7f..0000000 --- a/qy/src/main/res/drawable/progressbar.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/tab_camera_focus.9.png b/qy/src/main/res/drawable/tab_camera_focus.9.png deleted file mode 100644 index 5c7fad3..0000000 Binary files a/qy/src/main/res/drawable/tab_camera_focus.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_camera_indicator.xml b/qy/src/main/res/drawable/tab_camera_indicator.xml deleted file mode 100644 index e984e3c..0000000 --- a/qy/src/main/res/drawable/tab_camera_indicator.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/tab_camera_indicatoraaa.xml b/qy/src/main/res/drawable/tab_camera_indicatoraaa.xml deleted file mode 100644 index 6d7498d..0000000 --- a/qy/src/main/res/drawable/tab_camera_indicatoraaa.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/tab_camera_press.9.png b/qy/src/main/res/drawable/tab_camera_press.9.png deleted file mode 100644 index 5c7fad3..0000000 Binary files a/qy/src/main/res/drawable/tab_camera_press.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_camera_selected.9.png b/qy/src/main/res/drawable/tab_camera_selected.9.png deleted file mode 100644 index 41ca661..0000000 Binary files a/qy/src/main/res/drawable/tab_camera_selected.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_camera_unselected.9.png b/qy/src/main/res/drawable/tab_camera_unselected.9.png deleted file mode 100644 index 41ca661..0000000 Binary files a/qy/src/main/res/drawable/tab_camera_unselected.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_camera_unselectedbk.9.png b/qy/src/main/res/drawable/tab_camera_unselectedbk.9.png deleted file mode 100644 index 2e0a7df..0000000 Binary files a/qy/src/main/res/drawable/tab_camera_unselectedbk.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_focus.9.png b/qy/src/main/res/drawable/tab_focus.9.png deleted file mode 100644 index f2ef8e3..0000000 Binary files a/qy/src/main/res/drawable/tab_focus.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_indicator.xml b/qy/src/main/res/drawable/tab_indicator.xml deleted file mode 100644 index 5febf7c..0000000 --- a/qy/src/main/res/drawable/tab_indicator.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/tab_indicatorbka.xml b/qy/src/main/res/drawable/tab_indicatorbka.xml deleted file mode 100644 index 5e25e40..0000000 --- a/qy/src/main/res/drawable/tab_indicatorbka.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/tab_press.9.png b/qy/src/main/res/drawable/tab_press.9.png deleted file mode 100644 index f2ef8e3..0000000 Binary files a/qy/src/main/res/drawable/tab_press.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_selected.9.png b/qy/src/main/res/drawable/tab_selected.9.png deleted file mode 100644 index f2ef8e3..0000000 Binary files a/qy/src/main/res/drawable/tab_selected.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tab_unselected.9.png b/qy/src/main/res/drawable/tab_unselected.9.png deleted file mode 100644 index be42046..0000000 Binary files a/qy/src/main/res/drawable/tab_unselected.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/tb_munion_icon.xml b/qy/src/main/res/drawable/tb_munion_icon.xml deleted file mode 100644 index dbe28a7..0000000 --- a/qy/src/main/res/drawable/tb_munion_icon.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/tb_munion_item_selector.xml b/qy/src/main/res/drawable/tb_munion_item_selector.xml deleted file mode 100644 index d7c1201..0000000 --- a/qy/src/main/res/drawable/tb_munion_item_selector.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/qy/src/main/res/drawable/umeng_common_gradient_green.xml b/qy/src/main/res/drawable/umeng_common_gradient_green.xml deleted file mode 100644 index fc4f510..0000000 --- a/qy/src/main/res/drawable/umeng_common_gradient_green.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_common_gradient_orange.xml b/qy/src/main/res/drawable/umeng_common_gradient_orange.xml deleted file mode 100644 index 7db81ab..0000000 --- a/qy/src/main/res/drawable/umeng_common_gradient_orange.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_common_gradient_red.xml b/qy/src/main/res/drawable/umeng_common_gradient_red.xml deleted file mode 100644 index f38c8a1..0000000 --- a/qy/src/main/res/drawable/umeng_common_gradient_red.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_action_back.xml b/qy/src/main/res/drawable/umeng_socialize_action_back.xml deleted file mode 100644 index 4ff7296..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_action_back.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_action_back_normal.png b/qy/src/main/res/drawable/umeng_socialize_action_back_normal.png deleted file mode 100644 index e5245a6..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_action_back_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_action_back_selected.png b/qy/src/main/res/drawable/umeng_socialize_action_back_selected.png deleted file mode 100644 index 9d77a65..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_action_back_selected.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_at_button.xml b/qy/src/main/res/drawable/umeng_socialize_at_button.xml deleted file mode 100644 index 5f5fb4c..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_at_button.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_at_normal.png b/qy/src/main/res/drawable/umeng_socialize_at_normal.png deleted file mode 100644 index e2eee43..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_at_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_at_selected.png b/qy/src/main/res/drawable/umeng_socialize_at_selected.png deleted file mode 100644 index 838ebf9..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_at_selected.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_bind_bg.9.png b/qy/src/main/res/drawable/umeng_socialize_bind_bg.9.png deleted file mode 100644 index 5c92d0c..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_bind_bg.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_button_blue.9.png b/qy/src/main/res/drawable/umeng_socialize_button_blue.9.png deleted file mode 100644 index 2603820..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_button_blue.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_button_grey.9.png b/qy/src/main/res/drawable/umeng_socialize_button_grey.9.png deleted file mode 100644 index bfafad9..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_button_grey.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_button_grey_blue.xml b/qy/src/main/res/drawable/umeng_socialize_button_grey_blue.xml deleted file mode 100644 index 830bc80..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_button_grey_blue.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_button_login.xml b/qy/src/main/res/drawable/umeng_socialize_button_login.xml deleted file mode 100644 index 88ca29c..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_button_login.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_button_login_normal.png b/qy/src/main/res/drawable/umeng_socialize_button_login_normal.png deleted file mode 100644 index f3e7327..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_button_login_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_button_login_pressed.png b/qy/src/main/res/drawable/umeng_socialize_button_login_pressed.png deleted file mode 100644 index f3e7327..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_button_login_pressed.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_button_red.9.png b/qy/src/main/res/drawable/umeng_socialize_button_red.9.png deleted file mode 100644 index dff8b18..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_button_red.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_button_red_blue.xml b/qy/src/main/res/drawable/umeng_socialize_button_red_blue.xml deleted file mode 100644 index 035ecf2..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_button_red_blue.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_button_white.9.png b/qy/src/main/res/drawable/umeng_socialize_button_white.9.png deleted file mode 100644 index a8977b1..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_button_white.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_button_white_blue.xml b/qy/src/main/res/drawable/umeng_socialize_button_white_blue.xml deleted file mode 100644 index 8a45951..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_button_white_blue.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_default_avatar.png b/qy/src/main/res/drawable/umeng_socialize_default_avatar.png deleted file mode 100644 index 1a92a8b..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_default_avatar.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_douban_off.png b/qy/src/main/res/drawable/umeng_socialize_douban_off.png deleted file mode 100644 index 6ceaa39..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_douban_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_douban_on.png b/qy/src/main/res/drawable/umeng_socialize_douban_on.png deleted file mode 100644 index 75aebea..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_douban_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_facebook.png b/qy/src/main/res/drawable/umeng_socialize_facebook.png deleted file mode 100644 index 7d7b4dc..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_facebook.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_fetch_image.png b/qy/src/main/res/drawable/umeng_socialize_fetch_image.png deleted file mode 100644 index 64ee845..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_fetch_image.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_follow_check.xml b/qy/src/main/res/drawable/umeng_socialize_follow_check.xml deleted file mode 100644 index e35f11b..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_follow_check.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_follow_off.png b/qy/src/main/res/drawable/umeng_socialize_follow_off.png deleted file mode 100644 index e41fc24..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_follow_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_follow_on.png b/qy/src/main/res/drawable/umeng_socialize_follow_on.png deleted file mode 100644 index adb3015..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_follow_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_google.png b/qy/src/main/res/drawable/umeng_socialize_google.png deleted file mode 100644 index ac3c9fc..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_google.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_light_bar_bg.9.png b/qy/src/main/res/drawable/umeng_socialize_light_bar_bg.9.png deleted file mode 100644 index fd93932..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_light_bar_bg.9.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_location_ic.png b/qy/src/main/res/drawable/umeng_socialize_location_ic.png deleted file mode 100644 index 8f86b48..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_location_ic.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_location_off.png b/qy/src/main/res/drawable/umeng_socialize_location_off.png deleted file mode 100644 index e3c7710..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_location_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_location_on.png b/qy/src/main/res/drawable/umeng_socialize_location_on.png deleted file mode 100644 index f7ed6cb..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_location_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_nav_bar_bg.png b/qy/src/main/res/drawable/umeng_socialize_nav_bar_bg.png deleted file mode 100644 index 94c09ce..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_nav_bar_bg.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_oauth_check.xml b/qy/src/main/res/drawable/umeng_socialize_oauth_check.xml deleted file mode 100644 index 5599be6..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_oauth_check.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_oauth_check_off.png b/qy/src/main/res/drawable/umeng_socialize_oauth_check_off.png deleted file mode 100644 index 11b4664..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_oauth_check_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_oauth_check_on.png b/qy/src/main/res/drawable/umeng_socialize_oauth_check_on.png deleted file mode 100644 index 1cc697f..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_oauth_check_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_qq_off.png b/qy/src/main/res/drawable/umeng_socialize_qq_off.png deleted file mode 100644 index 3126365..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_qq_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_qq_on.png b/qy/src/main/res/drawable/umeng_socialize_qq_on.png deleted file mode 100644 index 8f8e912..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_qq_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_qzone_off.png b/qy/src/main/res/drawable/umeng_socialize_qzone_off.png deleted file mode 100644 index 25ad620..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_qzone_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_qzone_on.png b/qy/src/main/res/drawable/umeng_socialize_qzone_on.png deleted file mode 100644 index c8d87c6..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_qzone_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_refersh.png b/qy/src/main/res/drawable/umeng_socialize_refersh.png deleted file mode 100644 index af6f7e8..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_refersh.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_renren_off.png b/qy/src/main/res/drawable/umeng_socialize_renren_off.png deleted file mode 100644 index cf42b6f..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_renren_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_renren_on.png b/qy/src/main/res/drawable/umeng_socialize_renren_on.png deleted file mode 100644 index e8f3b96..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_renren_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_search_icon.png b/qy/src/main/res/drawable/umeng_socialize_search_icon.png deleted file mode 100644 index f4f1a6f..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_search_icon.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_shape_solid_black.xml b/qy/src/main/res/drawable/umeng_socialize_shape_solid_black.xml deleted file mode 100644 index 14fe6cb..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_shape_solid_black.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_shape_solid_grey.xml b/qy/src/main/res/drawable/umeng_socialize_shape_solid_grey.xml deleted file mode 100644 index 4cbea62..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_shape_solid_grey.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_share_to_button.xml b/qy/src/main/res/drawable/umeng_socialize_share_to_button.xml deleted file mode 100644 index b7c8f11..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_share_to_button.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_share_transparent_corner.xml b/qy/src/main/res/drawable/umeng_socialize_share_transparent_corner.xml deleted file mode 100644 index b0548f3..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_share_transparent_corner.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_shareboard_item_background.xml b/qy/src/main/res/drawable/umeng_socialize_shareboard_item_background.xml deleted file mode 100644 index aa935dc..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_shareboard_item_background.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_sidebar_normal.xml b/qy/src/main/res/drawable/umeng_socialize_sidebar_normal.xml deleted file mode 100644 index 4049845..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_sidebar_normal.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_sidebar_selected.xml b/qy/src/main/res/drawable/umeng_socialize_sidebar_selected.xml deleted file mode 100644 index 18c69b1..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_sidebar_selected.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_sidebar_selector.xml b/qy/src/main/res/drawable/umeng_socialize_sidebar_selector.xml deleted file mode 100644 index 54db8d6..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_sidebar_selector.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_sina_off.png b/qy/src/main/res/drawable/umeng_socialize_sina_off.png deleted file mode 100644 index 1bbef53..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_sina_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_sina_on.png b/qy/src/main/res/drawable/umeng_socialize_sina_on.png deleted file mode 100644 index 37f4563..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_sina_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_back_bt.xml b/qy/src/main/res/drawable/umeng_socialize_title_back_bt.xml deleted file mode 100644 index d8904a0..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_title_back_bt.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_title_back_bt_normal.png b/qy/src/main/res/drawable/umeng_socialize_title_back_bt_normal.png deleted file mode 100644 index 96a89e5..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_back_bt_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_back_bt_selected.png b/qy/src/main/res/drawable/umeng_socialize_title_back_bt_selected.png deleted file mode 100644 index c7732fb..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_back_bt_selected.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_right_bt.xml b/qy/src/main/res/drawable/umeng_socialize_title_right_bt.xml deleted file mode 100644 index 0b072a6..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_title_right_bt.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_title_right_bt_normal.png b/qy/src/main/res/drawable/umeng_socialize_title_right_bt_normal.png deleted file mode 100644 index 02c673e..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_right_bt_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_right_bt_selected.png b/qy/src/main/res/drawable/umeng_socialize_title_right_bt_selected.png deleted file mode 100644 index d2fdab0..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_right_bt_selected.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_tab_button_left.xml b/qy/src/main/res/drawable/umeng_socialize_title_tab_button_left.xml deleted file mode 100644 index 798e986..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_title_tab_button_left.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_title_tab_button_right.xml b/qy/src/main/res/drawable/umeng_socialize_title_tab_button_right.xml deleted file mode 100644 index e366d5c..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_title_tab_button_right.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_title_tab_left_normal.png b/qy/src/main/res/drawable/umeng_socialize_title_tab_left_normal.png deleted file mode 100644 index ba78baf..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_tab_left_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_tab_left_pressed.png b/qy/src/main/res/drawable/umeng_socialize_title_tab_left_pressed.png deleted file mode 100644 index 92653e8..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_tab_left_pressed.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_tab_right_normal.png b/qy/src/main/res/drawable/umeng_socialize_title_tab_right_normal.png deleted file mode 100644 index a1f6e75..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_tab_right_normal.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_title_tab_right_pressed.png b/qy/src/main/res/drawable/umeng_socialize_title_tab_right_pressed.png deleted file mode 100644 index 026f7f7..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_title_tab_right_pressed.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_twitter.png b/qy/src/main/res/drawable/umeng_socialize_twitter.png deleted file mode 100644 index 70484f5..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_twitter.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_tx_off.png b/qy/src/main/res/drawable/umeng_socialize_tx_off.png deleted file mode 100644 index 9e45118..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_tx_off.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_tx_on.png b/qy/src/main/res/drawable/umeng_socialize_tx_on.png deleted file mode 100644 index e844269..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_tx_on.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_wechat.png b/qy/src/main/res/drawable/umeng_socialize_wechat.png deleted file mode 100644 index 72d6e00..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_wechat.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_wechat_gray.png b/qy/src/main/res/drawable/umeng_socialize_wechat_gray.png deleted file mode 100644 index 24851eb..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_wechat_gray.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_window_shadow_pad.xml b/qy/src/main/res/drawable/umeng_socialize_window_shadow_pad.xml deleted file mode 100644 index 83b6326..0000000 --- a/qy/src/main/res/drawable/umeng_socialize_window_shadow_pad.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_socialize_wxcircle.png b/qy/src/main/res/drawable/umeng_socialize_wxcircle.png deleted file mode 100644 index da94344..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_wxcircle.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_wxcircle_gray.png b/qy/src/main/res/drawable/umeng_socialize_wxcircle_gray.png deleted file mode 100644 index 9483f8f..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_wxcircle_gray.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_socialize_x_button.png b/qy/src/main/res/drawable/umeng_socialize_x_button.png deleted file mode 100644 index 2f2c9fc..0000000 Binary files a/qy/src/main/res/drawable/umeng_socialize_x_button.png and /dev/null differ diff --git a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_focused.xml b/qy/src/main/res/drawable/umeng_update_button_cancel_bg_focused.xml deleted file mode 100644 index 98af568..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_focused.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_normal.xml b/qy/src/main/res/drawable/umeng_update_button_cancel_bg_normal.xml deleted file mode 100644 index 5040f92..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_normal.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_selector.xml b/qy/src/main/res/drawable/umeng_update_button_cancel_bg_selector.xml deleted file mode 100644 index 1180fc9..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_selector.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - diff --git a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_tap.xml b/qy/src/main/res/drawable/umeng_update_button_cancel_bg_tap.xml deleted file mode 100644 index 909e341..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_cancel_bg_tap.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_update_button_check_selector.xml b/qy/src/main/res/drawable/umeng_update_button_check_selector.xml deleted file mode 100644 index 03445de..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_check_selector.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - diff --git a/qy/src/main/res/drawable/umeng_update_button_close_bg_selector.xml b/qy/src/main/res/drawable/umeng_update_button_close_bg_selector.xml deleted file mode 100644 index 61cfd6b..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_close_bg_selector.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - diff --git a/qy/src/main/res/drawable/umeng_update_button_ok_bg_focused.xml b/qy/src/main/res/drawable/umeng_update_button_ok_bg_focused.xml deleted file mode 100644 index 8145038..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_ok_bg_focused.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/qy/src/main/res/drawable/umeng_update_button_ok_bg_normal.xml b/qy/src/main/res/drawable/umeng_update_button_ok_bg_normal.xml deleted file mode 100644 index b132b72..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_ok_bg_normal.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_update_button_ok_bg_selector.xml b/qy/src/main/res/drawable/umeng_update_button_ok_bg_selector.xml deleted file mode 100644 index 9816ea3..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_ok_bg_selector.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - diff --git a/qy/src/main/res/drawable/umeng_update_button_ok_bg_tap.xml b/qy/src/main/res/drawable/umeng_update_button_ok_bg_tap.xml deleted file mode 100644 index bcae1a8..0000000 --- a/qy/src/main/res/drawable/umeng_update_button_ok_bg_tap.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_update_dialog_bg.xml b/qy/src/main/res/drawable/umeng_update_dialog_bg.xml deleted file mode 100644 index 3f79dfb..0000000 --- a/qy/src/main/res/drawable/umeng_update_dialog_bg.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_update_title_bg.xml b/qy/src/main/res/drawable/umeng_update_title_bg.xml deleted file mode 100644 index c9f5f77..0000000 --- a/qy/src/main/res/drawable/umeng_update_title_bg.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/umeng_update_wifi_disable.png b/qy/src/main/res/drawable/umeng_update_wifi_disable.png deleted file mode 100644 index c2b739a..0000000 Binary files a/qy/src/main/res/drawable/umeng_update_wifi_disable.png and /dev/null differ diff --git a/qy/src/main/res/drawable/zoomin_seletor.xml b/qy/src/main/res/drawable/zoomin_seletor.xml deleted file mode 100644 index 356dc80..0000000 --- a/qy/src/main/res/drawable/zoomin_seletor.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/drawable/zoomout_seletor.xml b/qy/src/main/res/drawable/zoomout_seletor.xml deleted file mode 100644 index 50467bc..0000000 --- a/qy/src/main/res/drawable/zoomout_seletor.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_full_alert_dialog.xml b/qy/src/main/res/layout-sw550dp-large/umeng_socialize_full_alert_dialog.xml deleted file mode 100644 index 237f694..0000000 --- a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_full_alert_dialog.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_oauth_dialog.xml b/qy/src/main/res/layout-sw550dp-large/umeng_socialize_oauth_dialog.xml deleted file mode 100644 index 9138ef2..0000000 --- a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_oauth_dialog.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_post_share.xml b/qy/src/main/res/layout-sw550dp-large/umeng_socialize_post_share.xml deleted file mode 100644 index 2a222ce..0000000 --- a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_post_share.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_titile_bar.xml b/qy/src/main/res/layout-sw550dp-large/umeng_socialize_titile_bar.xml deleted file mode 100644 index 520122b..0000000 --- a/qy/src/main/res/layout-sw550dp-large/umeng_socialize_titile_bar.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - -