Compare commits

...

77 Commits

Author SHA1 Message Date
Dennis Guse a42bdf32e1 Release: v3.11.1 2020-10-06 08:16:58 +02:00
Dennis Guse c29d69b44d Cleanup. 2020-10-05 22:59:21 +02:00
Román 547b1d07bd Bugfix: interval stats announced incorrectly because an error in last interval computing. Fixes #443. 2020-10-05 20:08:07 +02:00
Dennis Guse 22a1dfd354 README: removed link to Maps.ME due to the amount of embedded trackers. 2020-10-04 12:51:14 +02:00
Dennis Guse be81e758c6 License: use non-Markdown, so Github-API identifies it. 2020-09-26 23:16:19 +02:00
Dennis Guse b3117e6410 Release: v3.11.0 2020-09-26 20:23:32 +02:00
Dennis Guse 47ab109c2b F-Droid now signs APKs with v2, so installing on Android 11 works.
More info: #421
This reverts commit ee22fd8e
2020-09-26 19:56:22 +02:00
Dennis Guse bc04efbaac Bugfix: for export all write permissions are required.
Android 11 enforces this (and it is good practice).
Fixes #439.
2020-09-26 19:52:48 +02:00
Román fbb9d21e73 TrackRecordingActivity keeps Track.Id value instead of track object. Every time the track is needed it gets it. Fixes #435. 2020-09-26 16:47:51 +02:00
dependabot[bot] f5308e4287 Bump mockito-android from 3.5.11 to 3.5.13
Bumps [mockito-android](https://github.com/mockito/mockito) from 3.5.11 to 3.5.13.
- [Release notes](https://github.com/mockito/mockito/releases)
- [Commits](https://github.com/mockito/mockito/compare/v3.5.11...v3.5.13)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-25 18:20:32 +02:00
Dennis Guse 15b5920e3b README: add F-Droid version shield 2020-09-25 12:37:58 +02:00
Dennis Guse d09aaab398 Theming: import/export finished dialog needs to be AndroidX. 2020-09-24 22:45:20 +02:00
pappapisshu f7008e2362 Update strings.xml
Fixed italian translation.
2020-09-24 17:16:54 +02:00
Dennis Guse e939778beb Refactor: use marker instead of waypoint.
Fixes #389.
2020-09-23 17:16:34 +02:00
Dennis Guse 8643b50bd1 Bugfix: application context does not provide access to theme attributes. 2020-09-23 12:12:34 +02:00
Dennis Guse 74e42525d4 Cleanup. 2020-09-23 08:11:10 +02:00
Dennis Guse 833a387574 Theming: splashscreen uses dark background color. 2020-09-23 08:05:40 +02:00
Dennis Guse e574c67ad6 Theming: activity icons are now in textColorPrimary.
And replaced spinner in StatisticsRecordedFragment.
2020-09-23 07:36:15 +02:00
Dennis Guse ce38d5e891 Theming: define colorAccent. 2020-09-23 07:36:15 +02:00
Dennis Guse 3a44da4a9d Theming: stats labels use color accent. 2020-09-23 07:36:15 +02:00
Dennis Guse eba9106db5 Theming: delete dialog needs to be Androidx for proper theming. 2020-09-23 07:36:15 +02:00
Dennis Guse 4501226562 Theming: reduce font size of lists first line. 2020-09-23 07:36:15 +02:00
Dennis Guse b974193564 Theming: delete dialog uses delete icon. 2020-09-23 07:36:15 +02:00
Dennis Guse 0b3e447258 Theming: charts use theme text colors. 2020-09-23 07:36:15 +02:00
Dennis Guse 9908cc02a2 Theming: added color.xml for night styling. 2020-09-23 07:36:15 +02:00
Dennis Guse 4e67011d7c Theming: style selected list items with transparent color. 2020-09-23 07:36:15 +02:00
Dennis Guse 5f93c0bab3 Theming: tabs use default indicator color. 2020-09-23 07:36:15 +02:00
Dennis Guse caec5e7c45 Theming: chart use default design background color. 2020-09-23 07:36:15 +02:00
Dennis Guse 240cb4b363 Theming: chart colors extracted. 2020-09-23 07:36:15 +02:00
Dennis Guse 91e8eb66b1 Theming: chart text is now rendered as FILL_AND_STROKE. 2020-09-23 07:36:15 +02:00
Dennis Guse 27bd69ec62 Code cleanup. 2020-09-23 07:36:15 +02:00
Dennis Guse 553fd39e21 Theming: make SplashScreen fullscreen. 2020-09-23 07:36:15 +02:00
Dennis Guse 733ee1c6e6 Theming: move TrackEdit to material design text fields. 2020-09-23 07:36:15 +02:00
Dennis Guse ef61c9597d Theming: activity chooser matches parent height. 2020-09-23 07:36:15 +02:00
Dennis Guse e874af791e Theming: removed all custom modifications to Holo theme. 2020-09-23 07:36:15 +02:00
Dennis Guse a4b2bb1aa0 Theming: tint all icons with colorControlNormal. 2020-09-23 07:36:15 +02:00
Dennis Guse bc9b20ffc8 Theming: marker detail uses default background. 2020-09-23 07:36:15 +02:00
Dennis Guse 6f212328a1 Theming: merged edit buttons into layout. 2020-09-23 07:36:15 +02:00
Dennis Guse a68cde7ac9 Theming: listView main item is now TextLarge. 2020-09-23 07:36:15 +02:00
Dennis Guse 5cab331058 Theming: removed custom spinner style. 2020-09-23 07:36:15 +02:00
Dennis Guse 6d25a10abd Theming: use default text color. 2020-09-23 07:36:15 +02:00
Dennis Guse d2516947f2 Theming: removed custom radio button style - use Material design. 2020-09-23 07:36:15 +02:00
Dennis Guse 4150d060ee Theming: enable day/night mode incl. app-wide setting. 2020-09-23 07:36:15 +02:00
Dennis Guse 1688076457 Theming: use AppCompat themes instead of Holo. 2020-09-23 07:36:15 +02:00
Román 5c1f669b2b Bugfix: spinner adapter needed notifyDataSetChanged to reload intervals with unit when user change from km to mi and the other way around. 2020-09-21 19:12:57 +02:00
Dennis Guse cc1e080ce1 Interval statistics: show unit in dropdown. 2020-09-20 19:05:32 +02:00
Dennis Guse 0dfd31a308 Code cleanup via Android Studio analyze.
Notably change: TrackPoint's copy constructor missed to copy the elevationGain.
2020-09-20 18:46:05 +02:00
dependabot[bot] bd13535d3c Bump mockito-android from 3.5.10 to 3.5.11
Bumps [mockito-android](https://github.com/mockito/mockito) from 3.5.10 to 3.5.11.
- [Release notes](https://github.com/mockito/mockito/releases)
- [Commits](https://github.com/mockito/mockito/compare/v3.5.10...v3.5.11)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-18 08:07:00 +02:00
Dennis Guse 27386bb4f0 Localization: update via Transifex CLI. 2020-09-17 23:44:37 +02:00
Dennis Guse c6c07f03bf Localization: add configuration for Transifex CLI. 2020-09-17 23:43:28 +02:00
Dennis Guse b0ad08f7c5 Release: v3.10.0 2020-09-14 18:38:48 +02:00
Román d1957331b8 Intervals refactoring: added stack mode to the intervals adapter with two possibilities: stack from top and stack from bottom.
Stack from top for recorded intervals (the first lap in the top).
Stack from bottom for recording intervals (the last lap in the top).
2020-09-14 18:31:12 +02:00
Román ffedc04777 Intervals refactoring: avoid duplication code: IntervalsRecordingFragment is a version of IntervalsFragment. 2020-09-14 18:31:12 +02:00
Román 684762db58 Intervals refactoring: ListView instead of LinearLayout with a list of views. 2020-09-14 18:31:12 +02:00
thrillfall 5a44da3fb0 extract logic for creating DocumentFile for export to align naming 2020-09-14 17:25:29 +02:00
Dennis Guse 88cf46d999 Bugfix: another missed toString() in the id-refactoring. 2020-09-14 12:29:31 +02:00
Román 906b9413d1 Improved and simplified lap time/speed announcement message. 2020-09-13 19:30:17 +02:00
Dennis Guse 060c4f1529 Theming: add a SplashScreen for TrackListActivity. 2020-09-12 00:03:42 +02:00
Dennis Guse 7902aea849 Disable flacky test. 2020-09-12 00:01:56 +02:00
Sudeep Duggal ee22fd8ee8 Added workaround for allowing Android 11 install with only apk v1 signature 2020-09-10 08:28:55 +02:00
Román a6e275f8aa Several hidden bugfixes around Track.Id 2020-09-09 17:53:07 +02:00
Román a61468d600 Bugfix: String.valueOf doesn't work with Track.Id. Fixes #422. 2020-09-09 17:53:07 +02:00
thrillfall 78c26cb669 unify export filename logic 2020-09-09 17:50:00 +02:00
Dennis Guse 0d493c410e Merge branch 'barometer#10' into main 2020-09-06 22:34:54 +02:00
Román 6e1aba6fa0 Added barriers in stats recorded layout and stats recording layout. 2020-09-06 18:17:46 +02:00
Dennis Guse 5099118dd7 Elevation gain: make it optional as Float - and if null, then the UI just shows "-".
In TrackStatistics the elevation gain is now nullable.
2020-09-05 12:39:23 +02:00
Dennis Guse 6845ce4984 Elevation gain: make it optional as Float.
So if no sensor data is provided, it is not stored in the database and not exported.
2020-09-05 12:39:23 +02:00
Dennis Guse e0d1ad4b52 Squash: fixed tests. 2020-09-05 12:39:23 +02:00
Dennis Guse 04b8d0f4a8 Import/Export: elevation gain per TrackPoint. 2020-09-05 12:39:23 +02:00
Román fe3bf61acb Squash: load TrackPoint elevationGain. 2020-09-05 12:39:23 +02:00
Román 577b9b4635 Alter table trackpoints: added elevation gain to the trackpoints table. 2020-09-05 12:39:23 +02:00
Dennis Guse 4b7de188fd Elevation gain adheres to visibility setting. 2020-09-05 12:39:23 +02:00
Román 3bfb212dc9 Bugfix: reset elevation every time track point is inserted. 2020-09-05 12:39:22 +02:00
Dennis Guse be7eb41cf3 Bugfix: previous total elevation gain was added twice. 2020-09-05 12:39:22 +02:00
Dennis Guse c7db4f528e Elevation gain: apply exponential smoothing and limit changes (defined change diff per sensor value). 2020-09-05 12:39:22 +02:00
Dennis Guse 8a14bc46f6 Implement elevation gain via barometer. 2020-09-05 12:39:22 +02:00
Dennis Guse 01ee1a1e49 Renamed DoubleBuffer to DoubleRingBuffer. 2020-09-05 12:39:22 +02:00
307 changed files with 3698 additions and 1887 deletions
+10
View File
@@ -0,0 +1,10 @@
[main]
host = https://www.transifex.com
[opentracks.src-main-res-values-strings-xml--main]
file_filter = src/main/res/values-<lang>/strings.xml
minimum_perc = 0
source_file = src/main/res/values/strings.xml
source_lang = en
type = ANDROID
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
-194
View File
@@ -1,194 +0,0 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
+3 -1
View File
@@ -13,6 +13,8 @@ _OpenTracks_ is a sport tracking application that completely respects your priva
<td>
<a href="https://f-droid.org/packages/de.dennisguse.opentracks">
<img alt="Get it on F-Droid" src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" height="60" align="middle">
<br />
<img alt="OpenTracks version published on F-Droid" src="https://img.shields.io/f-droid/v/de.dennisguse.opentracks.svg" align="middle" >
</a>
</td>
<td>
@@ -61,7 +63,7 @@ As of v3.3.1 OpenTracks enables to use custom dashboards.
The reference implementation is [OSMDashboard](https://github.com/OpenTracksApp/OSMDashboard), which presents an OpenStreetMap map (showing the current track, incl. updates).
The developer documentation is in [README_API.md](README_API.md).
Alternatively, recorded tracks can be shared as KMZ/GPX to installed applications (e.g., [OsmAnd](https://play.google.com/store/apps/details?id=net.osmand) or [MAPS.ME](https://play.google.com/store/apps/details?id=com.mapswithme.maps.pro)).
Alternatively, recorded tracks can be shared as KMZ/GPX to installed applications (e.g., [OsmAnd](https://play.google.com/store/apps/details?id=net.osmand)).
However, this is rather slow and does not provide updates while recording.
+3 -3
View File
@@ -47,8 +47,8 @@ android {
defaultConfig {
applicationId "de.dennisguse.opentracks"
versionCode 3584
versionName "v3.9.5"
versionCode 3661
versionName "v3.11.1"
buildConfigField "String", "VERSION_NAME_FULL", "\"${getVersionName()}\""
@@ -94,5 +94,5 @@ dependencies {
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test:rules:1.3.0'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'org.mockito:mockito-android:3.5.10'
androidTestImplementation 'org.mockito:mockito-android:3.5.13'
}
@@ -0,0 +1,10 @@
v3.10.0: OpenTracks
Changes:
- Elevation gain via barometer
- Add splash screen
- Android 11/F-Droid: downgrade to targetSDK 29 (v1 signature)
see https://gitlab.com/fdroid/fdroidserver/-/issues/827
Bugfix:
- Several fixes due to trackId refactoring
@@ -0,0 +1,10 @@
v3.11.0: OpenTracks
Changes:
- Theming: day/night mode (default: night)
- Theming: use Material Design instead of custom element theming
- Use targetSDK 30 again (F-Droid signs now with V2)
Bugfix:
- Android 11: export all crashed
- TrackDetail not updated in UI after data was changed by user
@@ -0,0 +1,4 @@
v3.11.1: OpenTracks
Bugfix:
- Voice announcements reported wrong statistics
@@ -68,9 +68,9 @@ public class TestDataUtil {
trackPoint.setSpeed(5f + (i / 10));
trackPoint.setHeartRate_bpm(100f + i);
trackPoint.setCyclingCadence_rpm(200f + i);
trackPoint.setCyclingCadence_rpm(300f + i);
trackPoint.setPower(400f + i);
trackPoint.setElevationGain(500f + i);
return trackPoint;
}
@@ -455,7 +455,7 @@ public class CustomContentProviderUtilsTest {
statistics.setTotalTime(1500L);
statistics.setMovingTime(700L);
statistics.setTotalDistance(750.0);
statistics.setTotalElevationGain(50.0);
statistics.setTotalElevationGain(50.0f);
statistics.setMaxSpeed(60.0);
statistics.setMaxElevation(1250.0);
statistics.setMinElevation(1200.0);
@@ -76,7 +76,7 @@ public class ExportImportTest {
marker.setName("the marker " + i);
marker.setDescription("the marker description " + i);
marker.setCategory("the marker category" + i);
marker.setIcon("the waypoing icon" + i);
marker.setIcon("the marker icon" + i);
marker.setPhotoUrl("the photo url" + i);
marker.setTrackId(trackId);
contentProviderUtils.insertMarker(marker);
@@ -133,7 +133,7 @@ public class ExportImportTest {
assertMarkers();
// 3. trackpoints
assertTrackpoints(false, false, false);
assertTrackpoints(false, false, false, false);
}
@LargeTest
@@ -168,7 +168,7 @@ public class ExportImportTest {
assertMarkers();
// 3. trackpoints
assertTrackpoints(true, true, true);
assertTrackpoints(true, true, true, true);
}
@LargeTest
@@ -257,7 +257,7 @@ public class ExportImportTest {
assertMarkers();
// 3. trackpoints
assertTrackpoints(false, true, true);
assertTrackpoints(false, true, true, false);
}
@LargeTest
@@ -304,7 +304,7 @@ public class ExportImportTest {
}
}
private void assertTrackpoints(boolean verifyPower, boolean verifyHeartrate, boolean verifyCadence) {
private void assertTrackpoints(boolean verifyPower, boolean verifyHeartrate, boolean verifyCadence, boolean verifyElevationGain) {
List<TrackPoint> importedTrackPoints = contentProviderUtils.getTrackPoints(importTrackId);
assertEquals(trackPoints.size(), importedTrackPoints.size());
@@ -330,6 +330,9 @@ public class ExportImportTest {
if (verifyPower) {
assertEquals(trackPoint.getPower(), importedTrackPoint.getPower(), 0.01);
}
if (verifyElevationGain) {
assertEquals(trackPoint.getElevationGain(), importedTrackPoint.getElevationGain(), 0.01);
}
}
}
}
@@ -25,7 +25,6 @@ import android.os.Looper;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.FlakyTest;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import androidx.test.rule.GrantPermissionRule;
@@ -34,6 +33,7 @@ import androidx.test.rule.ServiceTestRule;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -235,7 +235,7 @@ public class TrackRecordingServiceTest {
assertEquals(TrackPointsColumns.RESUME_LATITUDE, trackPoints.get(2).getLatitude(), 0.01);
}
@FlakyTest(detail = "Sometimes fails on CI.")
@Ignore("Sometimes fails on CI.")
@MediumTest
@Test
public void testRecording_orphanedRecordingTrack() throws Exception {
@@ -318,7 +318,7 @@ public class TrackRecordingServiceTest {
// then
assertNotEquals(-1L, waypointId);
Marker wpt = contentProviderUtils.getMarker(waypointId);
assertEquals(context.getString(R.string.marker_waypoint_icon_url), wpt.getIcon());
assertEquals(context.getString(R.string.marker_icon_url), wpt.getIcon());
assertEquals(context.getString(R.string.marker_name_format, 1), wpt.getName());
assertEquals(trackId, wpt.getTrackId());
assertEquals(0.0, wpt.getLength(), 0.01);
@@ -0,0 +1,50 @@
package de.dennisguse.opentracks.services.sensors;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* NOTE: Test data is completely artificial.
*/
public class ElevationSumManagerTest {
private ElevationSumManager elevationSumManager = new ElevationSumManager();
private static void addSensorValue(ElevationSumManager elevationSumManager, float[] values) {
for (float f : values) {
elevationSumManager.onSensorValueChanged(f);
}
}
@Before
public void setUp() {
elevationSumManager.reset();
}
@Test
public void getElevationGainLoss_downhill() {
// given
elevationSumManager.setConnected(true);
// then
addSensorValue(elevationSumManager, new float[]{1015f, 1015.01f, 1015.02f, 1015.03f, 1015.04f, 1015.05f, 1015.06f, 1015.07f, 1015.08f, 1015.09f, 1015.10f, 1015.11f, 1015.12f, 1015.13f, 1015.14f, 1015.15f});
// then
Assert.assertEquals(0f, elevationSumManager.getElevationGain_m(), 0.01);
Assert.assertEquals(-48.0, elevationSumManager.getElevationLoss_m(), 0.01);
}
@Test
public void sensorUnavailable() {
// given
elevationSumManager.setConnected(false);
// then
elevationSumManager.onSensorValueChanged(999f);
// then
Assert.assertNull(elevationSumManager.getElevationGain_m());
Assert.assertNull(elevationSumManager.getElevationLoss_m());
}
}
@@ -51,8 +51,8 @@ public class TrackStatisticsTest {
statistics2.setMovingTime(600L); // Result: 700+600
statistics.setTotalDistance(750.0);
statistics2.setTotalDistance(350.0); // Result: 750+350
statistics.setTotalElevationGain(50.0);
statistics2.setTotalElevationGain(850.0); // Result: 850+50
statistics.setTotalElevationGain(50.0f);
statistics2.setTotalElevationGain(850.0f); // Result: 850+50
statistics.setMaxSpeed(60.0); // Resulting max speed
statistics2.setMaxSpeed(30.0);
statistics.setMaxElevation(1250.0);
@@ -59,7 +59,7 @@ public class AnnouncementUtilsTest {
double kmPerHour = lastInterval.getSpeed_ms() * UnitConversions.MPS_TO_KMH;
String firstPartMsg = "OpenTracks total distance 20.00 kilometers in 5 minutes 0 seconds at 240.0 kilometers per hour";
String rateMsg = " With a current kilometer speed of " + context.getResources().getQuantityString(speedId, getQuantityCount(kmPerHour), kmPerHour);
String rateMsg = " Lap speed of " + context.getResources().getQuantityString(speedId, getQuantityCount(kmPerHour), kmPerHour);
String msg = firstPartMsg + rateMsg;
// when
@@ -0,0 +1,49 @@
package de.dennisguse.opentracks.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class PressureSensorUtilsTest {
// real data at 500Hz stationary
@Test
public void elevationChanges_none() {
// given
float[] sensorValues_hPa = new float[]{1015.6876f, 1015.699f, 1015.70905f, 1015.71075f, 1015.7224f, 1015.72f, 1015.7373f, 1015.7481f, 1015.74133f, 1015.73553f, 1015.7462f, 1015.74896f, 1015.752f, 1015.754f, 1015.7456f, 1015.73303f, 1015.7288f, 1015.7239f, 1015.7298f, 1015.7387f, 1015.72534f, 1015.72577f, 1015.72797f, 1015.71796f, 1015.7113f, 1015.7097f, 1015.7096f, 1015.7013f, 1015.7072f, 1015.71063f, 1015.7088f, 1015.7115f, 1015.713f, 1015.7121f, 1015.7062f, 1015.7062f, 1015.6994f, 1015.69617f, 1015.68945f, 1015.698f, 1015.6913f, 1015.69696f, 1015.69293f, 1015.6955f, 1015.6928f, 1015.6939f, 1015.68787f, 1015.6881f, 1015.68536f, 1015.68726f, 1015.6879f, 1015.6904f, 1015.6937f, 1015.69476f, 1015.7046f, 1015.7019f, 1015.7079f, 1015.71124f, 1015.71216f, 1015.71436f, 1015.7171f, 1015.7186f, 1015.7186f, 1015.7246f, 1015.72046f, 1015.7211f, 1015.72375f, 1015.7194f, 1015.72125f, 1015.7161f, 1015.71185f, 1015.7188f, 1015.721f, 1015.7252f, 1015.72266f, 1015.7236f, 1015.72614f, 1015.7266f, 1015.7344f, 1015.7376f, 1015.7337f, 1015.7253f, 1015.71875f, 1015.7219f, 1015.7219f, 1015.7317f, 1015.7284f, 1015.73444f, 1015.73584f, 1015.7369f, 1015.73254f, 1015.7369f, 1015.7336f, 1015.73254f, 1015.73676f, 1015.74176f, 1015.74506f, 1015.7478f, 1015.755f, 1015.7515f, 1015.7543f, 1015.7459f, 1015.7468f, 1015.7492f, 1015.74585f, 1015.74756f, 1015.74756f, 1015.75085f, 1015.754f, 1015.75336f, 1015.7568f, 1015.75165f, 1015.761f, 1015.7527f, 1015.75684f, 1015.7635f, 1015.7585f, 1015.7552f, 1015.7475f, 1015.74506f, 1015.7542f, 1015.75586f, 1015.74176f, 1015.74414f, 1015.7501f, 1015.751f, 1015.7478f, 1015.755f, 1015.75836f, 1015.7592f, 1015.75256f, 1015.7559f, 1015.76654f, 1015.76154f, 1015.766f, 1015.77014f, 1015.76904f, 1015.76013f, 1015.7674f, 1015.76514f, 1015.7674f, 1015.7635f, 1015.76404f, 1015.7607f, 1015.754f, 1015.7574f, 1015.7607f, 1015.7607f, 1015.7607f, 1015.754f, 1015.7567f, 1015.7616f, 1015.7643f, 1015.7666f, 1015.7609f, 1015.766f, 1015.76764f, 1015.755f, 1015.75757f, 1015.74927f, 1015.74927f, 1015.7426f, 1015.745f, 1015.745f, 1015.7409f, 1015.7376f, 1015.7326f, 1015.74164f, 1015.74664f, 1015.745f, 1015.7459f, 1015.7502f, 1015.7493f, 1015.7476f, 1015.7493f, 1015.751f, 1015.7601f, 1015.76434f, 1015.766f, 1015.756f, 1015.7617f, 1015.7623f, 1015.76404f, 1015.76733f, 1015.7607f, 1015.7623f, 1015.76337f, 1015.7584f, 1015.7573f, 1015.7502f, 1015.7534f, 1015.7534f, 1015.7601f, 1015.75684f, 1015.7518f, 1015.75574f, 1015.7524f, 1015.7507f, 1015.7484f, 1015.7502f, 1015.7534f, 1015.7623f, 1015.75903f, 1015.75574f, 1015.75574f, 1015.7573f, 1015.7524f, 1015.75574f, 1015.75574f, 1015.7607f, 1015.7573f, 1015.754f, 1015.74677f, 1015.754f, 1015.75574f, 1015.75903f, 1015.7573f, 1015.7551f, 1015.7573f, 1015.754f, 1015.7507f, 1015.7374f, 1015.739f, 1015.73566f, 1015.73566f, 1015.7367f, 1015.7417f, 1015.7417f, 1015.739f, 1015.74835f, 1015.74567f, 1015.7517f, 1015.74066f, 1015.7374f, 1015.739f, 1015.7417f, 1015.73065f, 1015.72894f, 1015.73505f, 1015.73334f, 1015.74005f, 1015.74005f, 1015.7367f, 1015.7434f, 1015.744f, 1015.7423f, 1015.7384f, 1015.739f, 1015.7374f, 1015.7374f, 1015.7374f, 1015.7341f, 1015.73505f, 1015.7341f, 1015.7267f, 1015.72833f, 1015.7234f, 1015.7167f, 1015.725f, 1015.7217f, 1015.7234f, 1015.73004f, 1015.7324f, 1015.7423f, 1015.74005f, 1015.73505f, 1015.73004f, 1015.739f, 1015.7417f, 1015.74567f, 1015.74066f, 1015.74146f, 1015.74146f, 1015.73816f, 1015.7274f, 1015.72906f, 1015.7274f, 1015.7341f, 1015.739f, 1015.744f, 1015.7417f, 1015.7374f, 1015.7324f, 1015.73816f, 1015.74146f, 1015.7374f, 1015.7341f, 1015.7365f, 1015.7365f, 1015.74146f, 1015.74414f, 1015.7475f, 1015.7448f, 1015.74146f, 1015.74585f, 1015.7475f, 1015.75146f, 1015.75146f, 1015.7591f, 1015.75476f, 1015.7614f, 1015.75476f, 1015.7492f, 1015.74817f, 1015.7498f, 1015.7515f, 1015.75586f, 1015.7509f, 1015.7448f, 1015.7525f, 1015.7581f, 1015.7592f};
float firstSensorValue = sensorValues_hPa[0];
// when // then
for (float v : sensorValues_hPa) {
assertNull(PressureSensorUtils.computeChanges_m(firstSensorValue, v));
}
}
// Simulate a sudden drop of elevation.
// test data
@Test
public void computeChanges_downhill() {
float[] sensorValues_hPa = new float[]{1015f, 1015.01f, 1015.02f, 1015.03f, 1015.04f, 1015.05f, 1015.06f, 1015.07f, 1015.08f, 1015.09f, 1015.10f, 1015.11f, 1015.12f, 1015.13f, 1018f, 1018.1f, 1018.1f, 1018.1f, 1018.1f};
float firstSensorValue = sensorValues_hPa[0];
// when
float elevationGain_m = 0;
float elevationLoss_m = 0;
float lastUsedPressureValue_hPa = firstSensorValue;
for (float v : sensorValues_hPa) {
PressureSensorUtils.ElevationChange elevationChange = PressureSensorUtils.computeChanges_m(lastUsedPressureValue_hPa, v);
if (elevationChange != null) {
elevationGain_m += elevationChange.getElevationGain_m();
elevationLoss_m += elevationChange.getElevationLoss_m();
lastUsedPressureValue_hPa = elevationChange.getCurrentSensorValue_hPa();
}
}
// then
assertEquals(0f, elevationGain_m, 0.01);
assertEquals(-15.0f, elevationLoss_m, 0.01);
assertEquals(1016.80f, lastUsedPressureValue_hPa, 0.01); //Expect exponential smoothing
}
}
@@ -35,7 +35,7 @@ public class AggregatedStatisticsTest {
statistics.setTotalTime(totalTime);
statistics.setMovingTime(totalTime);
statistics.setTotalDistance(totalDistance);
statistics.setTotalElevationGain(50.0);
statistics.setTotalElevationGain(50.0f);
statistics.setMaxSpeed(50.0); // Resulting max speed
statistics.setMaxElevation(1250.0);
statistics.setMinElevation(1200.0); // Resulting min elevation
+3 -2
View File
@@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="de.dennisguse.opentracks"
android:installLocation="auto">
@@ -138,7 +137,9 @@ limitations under the License.
<activity android:name=".TrackEditActivity" />
<activity android:name=".TrackListActivity">
<activity
android:name=".TrackListActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -23,7 +23,7 @@ public class AggregatedStatisticsActivity extends AbstractActivity {
final AggregatedStatisticsModel viewModel = new ViewModelProvider(this).get(AggregatedStatisticsModel.class);
viewModel.getAggregatedStats().observe(this, aggregatedStatistics -> {
if (aggregatedStatistics != null) {
adapter = new AggregatedStatisticsAdapter(getApplicationContext(), aggregatedStatistics);
adapter = new AggregatedStatisticsAdapter(this, aggregatedStatistics);
listView.setAdapter(adapter);
}
adapter.notifyDataSetChanged();
@@ -48,33 +48,33 @@ public class MarkerDetailActivity extends AbstractActivity implements DeleteMark
private static final String TAG = MarkerDetailActivity.class.getSimpleName();
private List<Marker.Id> waypointIds;
private List<Marker.Id> markerIds;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
Marker.Id waypointId = getIntent().getParcelableExtra(EXTRA_MARKER_ID);
if (waypointId == null) {
Marker.Id markerId = getIntent().getParcelableExtra(EXTRA_MARKER_ID);
if (markerId == null) {
Log.d(TAG, "invalid marker id");
finish();
return;
}
ContentProviderUtils contentProviderUtils = new ContentProviderUtils(this);
Marker waypoint = contentProviderUtils.getMarker(waypointId);
Marker marker = contentProviderUtils.getMarker(markerId);
waypointIds = new ArrayList<>();
markerIds = new ArrayList<>();
int markerIndex = -1;
//TODO Load only waypointIds, not the whole waypoint
try (Cursor cursor = contentProviderUtils.getMarkerCursor(waypoint.getTrackId(), null, -1)) {
//TODO Load only markerIds, not the whole marker
try (Cursor cursor = contentProviderUtils.getMarkerCursor(marker.getTrackId(), null, -1)) {
if (cursor != null && cursor.moveToFirst()) {
for (int i = 0; i < cursor.getCount(); i++) {
Marker currentMarker = contentProviderUtils.createMarker(cursor);
waypointIds.add(currentMarker.getId());
if (waypointId.equals(currentMarker.getId())) {
markerIndex = waypointIds.size() - 1;
markerIds.add(currentMarker.getId());
if (markerId.equals(currentMarker.getId())) {
markerIndex = markerIds.size() - 1;
}
cursor.moveToNext();
@@ -127,7 +127,7 @@ public class MarkerDetailActivity extends AbstractActivity implements DeleteMark
@Override
@NonNull
public Fragment getItem(int position) {
return MarkerDetailFragment.newInstance(waypointIds.get(position));
return MarkerDetailFragment.newInstance(markerIds.get(position));
}
@Nullable
@@ -138,7 +138,7 @@ public class MarkerDetailActivity extends AbstractActivity implements DeleteMark
@Override
public int getCount() {
return waypointIds.size();
return markerIds.size();
}
}
}
@@ -32,12 +32,13 @@ import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.material.textfield.TextInputEditText;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
@@ -67,7 +68,7 @@ public class MarkerEditActivity extends AbstractActivity {
private static final String TAG = MarkerEditActivity.class.getSimpleName();
private Track.Id trackId;
private TrackRecordingServiceConnection trackRecordingServiceConnection = new TrackRecordingServiceConnection();
private Marker waypoint;
private Marker marker;
private MenuItem insertPhotoMenuItem;
private MenuItem insertGalleryImgMenuItem;
@@ -76,35 +77,35 @@ public class MarkerEditActivity extends AbstractActivity {
private boolean hasCamera;
// UI elements
private EditText waypointName;
private AutoCompleteTextView waypointMarkerType;
private EditText waypointDescription;
private ImageView waypointPhoto;
private ImageView waypointDeletePhotoBtn;
private TextInputEditText markerName;
private AutoCompleteTextView markerType;
private TextInputEditText markerDescription;
private ImageView markerPhoto;
private ImageView markerDeletePhotoBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
trackId = getIntent().getParcelableExtra(EXTRA_TRACK_ID);
Marker.Id waypointId = getIntent().getParcelableExtra(EXTRA_MARKER_ID);
Marker.Id markerId = getIntent().getParcelableExtra(EXTRA_MARKER_ID);
hasCamera = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
// Setup UI elements
waypointName = findViewById(R.id.marker_edit_waypoint_name);
waypointMarkerType = findViewById(R.id.marker_edit_waypoint_marker_type);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.waypoint_types, android.R.layout.simple_dropdown_item_1line);
waypointMarkerType.setAdapter(adapter);
waypointDescription = findViewById(R.id.marker_edit_waypoint_description);
waypointPhoto = findViewById(R.id.marker_edit_waypoint_photo);
markerName = findViewById(R.id.marker_edit_name);
markerType = findViewById(R.id.marker_edit_marker_type);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.marker_types, android.R.layout.simple_dropdown_item_1line);
markerType.setAdapter(adapter);
markerDescription = findViewById(R.id.marker_edit_description);
markerPhoto = findViewById(R.id.marker_edit_photo);
waypointDeletePhotoBtn = findViewById(R.id.marker_edit_waypoint_photo_delete);
waypointDeletePhotoBtn.setOnClickListener(v -> {
if (waypoint != null && waypoint.hasPhoto()) {
waypoint.setPhotoUrl(null);
markerDeletePhotoBtn = findViewById(R.id.marker_edit_photo_delete);
markerDeletePhotoBtn.setOnClickListener(v -> {
if (marker != null && marker.hasPhoto()) {
marker.setPhotoUrl(null);
}
waypointPhoto.setImageBitmap(null);
markerPhoto.setImageBitmap(null);
photoUri = null;
hideAndShowOptions();
});
@@ -112,7 +113,7 @@ public class MarkerEditActivity extends AbstractActivity {
Button cancel = findViewById(R.id.marker_edit_cancel);
cancel.setOnClickListener(v -> finish());
final boolean isNewMarker = waypointId == null;
final boolean isNewMarker = markerId == null;
setTitle(isNewMarker ? R.string.menu_insert_marker : R.string.menu_edit);
Button done = findViewById(R.id.marker_edit_done);
@@ -127,37 +128,37 @@ public class MarkerEditActivity extends AbstractActivity {
});
if (isNewMarker) {
int nextWaypointNumber = trackId == null ? -1 : new ContentProviderUtils(this).getNextMarkerNumber(trackId);
if (nextWaypointNumber == -1) {
nextWaypointNumber = 0;
int nextMarkerNumber = trackId == null ? -1 : new ContentProviderUtils(this).getNextMarkerNumber(trackId);
if (nextMarkerNumber == -1) {
nextMarkerNumber = 0;
}
waypointName.setText(getString(R.string.marker_name_format, nextWaypointNumber));
waypointName.selectAll();
waypointMarkerType.setText("");
waypointDescription.setText("");
markerName.setText(getString(R.string.marker_name_format, nextMarkerNumber));
markerName.selectAll();
markerType.setText("");
markerDescription.setText("");
} else {
waypoint = new ContentProviderUtils(this).getMarker(waypointId);
if (waypoint == null) {
Log.d(TAG, "waypoint is null");
marker = new ContentProviderUtils(this).getMarker(markerId);
if (marker == null) {
Log.d(TAG, "marker is null");
finish();
return;
}
waypointName.setText(waypoint.getName());
waypointMarkerType.setText(waypoint.getCategory());
waypointDescription.setText(waypoint.getDescription());
if (waypoint.hasPhoto()) {
photoUri = waypoint.getPhotoURI();
markerName.setText(marker.getName());
markerType.setText(marker.getCategory());
markerDescription.setText(marker.getDescription());
if (marker.hasPhoto()) {
photoUri = marker.getPhotoURI();
}
}
if (savedInstanceState != null) {
photoUri = savedInstanceState.getParcelable(BUNDLE_PHOTO_URI);
if (waypoint != null) {
waypoint.setPhotoUrl(photoUri != null ? photoUri.toString() : null);
if (marker != null) {
marker.setPhotoUrl(photoUri != null ? photoUri.toString() : null);
}
}
if (photoUri != null) {
setWaypointImageView(photoUri);
setMarkerImageView(photoUri);
}
hideAndShowOptions();
@@ -202,10 +203,10 @@ public class MarkerEditActivity extends AbstractActivity {
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.marker_edit_insert_photo:
createWaypointWithPicture();
createMarkerWithPicture();
return true;
case R.id.marker_edit_insert_gallery_img:
createWaypointWithGalleryImage();
createMarkerWithGalleryImage();
return true;
default:
return super.onOptionsItemSelected(item);
@@ -219,7 +220,7 @@ public class MarkerEditActivity extends AbstractActivity {
Toast.makeText(this, R.string.marker_add_photo_canceled, Toast.LENGTH_LONG).show();
return;
} else if (resultCode == RESULT_OK) {
setWaypointImageView(photoUri);
setMarkerImageView(photoUri);
}
} else if (requestCode == GALLERY_IMG_REQUEST_CODE) {
if (resultCode == RESULT_CANCELED) {
@@ -233,7 +234,7 @@ public class MarkerEditActivity extends AbstractActivity {
FileUtils.copy(srcFd, dstFile);
photoUri = FileUtils.getUriForFile(this, dstFile);
setWaypointImageView(photoUri);
setMarkerImageView(photoUri);
} catch(Exception e) {
Log.e(TAG, e.getMessage());
Toast.makeText(this, R.string.marker_add_canceled, Toast.LENGTH_LONG).show();
@@ -250,31 +251,26 @@ public class MarkerEditActivity extends AbstractActivity {
* If a photo is set then one's options are shown, otherwise another ones are shown.
*/
private void hideAndShowOptions() {
boolean isPhotoSet = (waypoint != null && waypoint.hasPhoto()) || photoUri != null;
boolean isPhotoSet = (marker != null && marker.hasPhoto()) || photoUri != null;
if (insertPhotoMenuItem != null && insertGalleryImgMenuItem != null) {
insertPhotoMenuItem.setVisible(!isPhotoSet);
insertGalleryImgMenuItem.setVisible(!isPhotoSet);
}
waypointDeletePhotoBtn.setVisibility(isPhotoSet ? View.VISIBLE : View.GONE);
markerDeletePhotoBtn.setVisibility(isPhotoSet ? View.VISIBLE : View.GONE);
}
/**
* Returns the trackId. If trackId == -1 then get it from waypoint object.
* Returns the trackId; either from track or marker.
*/
private Track.Id getTrackId() {
return trackId == null ? waypoint.getTrackId() : trackId;
return trackId == null ? marker.getTrackId() : trackId;
}
/**
* Sets the ImageView waypointPhoto with the uri photo.
*
* @param uri the uri photo.
*/
private void setWaypointImageView(@NonNull Uri uri) {
private void setMarkerImageView(@NonNull Uri uri) {
try (ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "r")) {
FileDescriptor fd = pfd.getFileDescriptor();
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fd);
waypointPhoto.setImageBitmap(bitmap);
markerPhoto.setImageBitmap(bitmap);
hideAndShowOptions();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
@@ -282,31 +278,31 @@ public class MarkerEditActivity extends AbstractActivity {
}
}
private void createWaypointWithPicture() {
private void createMarkerWithPicture() {
Pair<Intent, Uri> intentAndPhotoUri = IntentUtils.createTakePictureIntent(this, getTrackId());
photoUri = intentAndPhotoUri.second;
startActivityForResult(intentAndPhotoUri.first, CAMERA_REQUEST_CODE);
}
private void createWaypointWithGalleryImage() {
private void createMarkerWithGalleryImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_IMG_REQUEST_CODE);
}
private void addMarker() {
trackRecordingServiceConnection.addMarker(this,
waypointName.getText().toString(),
waypointMarkerType.getText().toString(),
waypointDescription.getText().toString(),
markerName.getText().toString(),
markerType.getText().toString(),
markerDescription.getText().toString(),
photoUri != null ? photoUri.toString() : null);
}
private void saveMarker() {
waypoint.setName(waypointName.getText().toString());
waypoint.setCategory(waypointMarkerType.getText().toString());
waypoint.setDescription(waypointDescription.getText().toString());
waypoint.setPhotoUrl(photoUri != null ? photoUri.toString() : null);
marker.setName(markerName.getText().toString());
marker.setCategory(markerType.getText().toString());
marker.setDescription(markerDescription.getText().toString());
marker.setPhotoUrl(photoUri != null ? photoUri.toString() : null);
new ContentProviderUtils(this).updateMarker(this, waypoint);
new ContentProviderUtils(this).updateMarker(this, marker);
}
}
@@ -229,35 +229,35 @@ public class MarkerListActivity extends AbstractActivity implements DeleteMarker
/**
* Handles a context item selection.
*
* @param itemId the menu item id
* @param longWaypointIds the marker ids
* @param itemId the menu item id
* @param longMarkerds the marker ids
* @return true if handled.
*/
private boolean handleContextItem(int itemId, long... longWaypointIds) {
Marker.Id[] waypointIds = new Marker.Id[longWaypointIds.length];
for (int i = 0; i < longWaypointIds.length; i++) {
waypointIds[i] = new Marker.Id(longWaypointIds[i]);
private boolean handleContextItem(int itemId, long... longMarkerds) {
Marker.Id[] markerIds = new Marker.Id[longMarkerds.length];
for (int i = 0; i < longMarkerds.length; i++) {
markerIds[i] = new Marker.Id(longMarkerds[i]);
}
Intent intent;
switch (itemId) {
case R.id.list_context_menu_show_on_map:
if (waypointIds.length == 1) {
IntentUtils.showCoordinateOnMap(this, contentProviderUtils.getMarker(waypointIds[0]));
if (markerIds.length == 1) {
IntentUtils.showCoordinateOnMap(this, contentProviderUtils.getMarker(markerIds[0]));
}
return true;
case R.id.list_context_menu_edit:
if (waypointIds.length == 1) {
if (markerIds.length == 1) {
intent = IntentUtils.newIntent(this, MarkerEditActivity.class)
.putExtra(MarkerEditActivity.EXTRA_MARKER_ID, waypointIds[0]);
.putExtra(MarkerEditActivity.EXTRA_MARKER_ID, markerIds[0]);
startActivity(intent);
}
return true;
case R.id.list_context_menu_delete:
if (waypointIds.length > 1 && waypointIds.length == listView.getCount()) {
waypointIds = null;
if (markerIds.length > 1 && markerIds.length == listView.getCount()) {
markerIds = null;
}
DeleteMarkerDialogFragment.showDialog(getSupportFragmentManager(), waypointIds);
DeleteMarkerDialogFragment.showDialog(getSupportFragmentManager(), markerIds);
return true;
case R.id.list_context_menu_select_all:
for (int i = 0; i < listView.getCount(); i++) {
@@ -271,7 +271,7 @@ public class SearchListActivity extends AbstractListActivity implements DeleteMa
}
Map<String, Object> item = arrayAdapter.getItem(positions[0]);
Track.Id trackId = (Track.Id) item.get(TRACK_ID_FIELD);
Marker.Id waypointId = (Marker.Id) item.get(MARKER_ID_FIELD);
Marker.Id markerId = (Marker.Id) item.get(MARKER_ID_FIELD);
Intent intent;
switch (itemId) {
case R.id.list_context_menu_show_on_map:
@@ -283,9 +283,9 @@ public class SearchListActivity extends AbstractListActivity implements DeleteMa
startActivity(intent);
return true;
case R.id.list_context_menu_edit:
if (waypointId != null) {
if (markerId != null) {
intent = IntentUtils.newIntent(this, MarkerEditActivity.class)
.putExtra(MarkerEditActivity.EXTRA_MARKER_ID, waypointId);
.putExtra(MarkerEditActivity.EXTRA_MARKER_ID, markerId);
} else {
intent = IntentUtils.newIntent(this, TrackEditActivity.class)
.putExtra(TrackEditActivity.EXTRA_TRACK_ID, trackId);
@@ -296,8 +296,8 @@ public class SearchListActivity extends AbstractListActivity implements DeleteMa
finish();
return true;
case R.id.list_context_menu_delete:
if (waypointId != null) {
DeleteMarkerDialogFragment.showDialog(getSupportFragmentManager(), waypointId);
if (markerId != null) {
DeleteMarkerDialogFragment.showDialog(getSupportFragmentManager(), markerId);
} else {
deleteTracks(trackId);
}
@@ -349,7 +349,7 @@ public class SearchListActivity extends AbstractListActivity implements DeleteMa
* @return a list of result maps
*/
private List<Map<String, Object>> prepareResultsforDisplay(Collection<ScoredResult> scoredResults) {
//TODO Replace use of map<string, object>, but rather provide Track or Waypoint directly.
//TODO Replace use of map<string, object>, but rather provide Track or Marker directly.
ArrayList<Map<String, Object>> output = new ArrayList<>(scoredResults.size());
for (ScoredResult result : scoredResults) {
if (result.track != null) {
@@ -361,18 +361,12 @@ public class SearchListActivity extends AbstractListActivity implements DeleteMa
return output;
}
/**
* Prepares a marker for display by filling in a result map.
*
* @param waypoint the marker
* @return the result map
*/
private Map<String, Object> prepareMarkerForDisplay(Marker waypoint) {
private Map<String, Object> prepareMarkerForDisplay(Marker marker) {
Map<String, Object> resultMap = new HashMap<>();
//TODO: It may be more appropriate to obtain the track name as a join in the retrieval phase of the searchable.
String trackName = null;
Track.Id trackId = waypoint.getTrackId();
Track.Id trackId = marker.getTrackId();
if (!trackId.isValid()) {
Track track = contentProviderUtils.getTrack(trackId);
if (track != null) {
@@ -384,20 +378,20 @@ public class SearchListActivity extends AbstractListActivity implements DeleteMa
resultMap.put(IS_PAUSED_FIELD, true);
resultMap.put(ICON_ID_FIELD, MarkerUtils.ICON_ID);
resultMap.put(ICON_CONTENT_DESCRIPTION_ID_FIELD, R.string.image_marker);
resultMap.put(NAME_FIELD, waypoint.getName());
resultMap.put(NAME_FIELD, marker.getName());
// Display the marker's track name in the total time field
resultMap.put(TOTAL_TIME_FIELD, trackName == null ? null : getString(R.string.search_list_marker_track_location, trackName));
resultMap.put(TOTAL_DISTANCE_FIELD, null);
resultMap.put(MARKER_COUNT_FIELD, 0);
resultMap.put(START_TIME_FIELD, waypoint.getLocation().getTime());
resultMap.put(CATEGORY_FIELD, waypoint.getCategory());
resultMap.put(DESCRIPTION_FIELD, waypoint.getDescription());
resultMap.put(PHOTO_URL_FIELD, waypoint.getPhotoUrl());
resultMap.put(TRACK_ID_FIELD, waypoint.getTrackId());
resultMap.put(MARKER_ID_FIELD, waypoint.getId());
resultMap.put(START_TIME_FIELD, marker.getLocation().getTime());
resultMap.put(CATEGORY_FIELD, marker.getCategory());
resultMap.put(DESCRIPTION_FIELD, marker.getDescription());
resultMap.put(PHOTO_URL_FIELD, marker.getPhotoUrl());
resultMap.put(TRACK_ID_FIELD, marker.getTrackId());
resultMap.put(MARKER_ID_FIELD, marker.getId());
resultMap.put(MARKER_LATITUDE_FIELD, waypoint.getLocation().getLatitude());
resultMap.put(MARKER_LONGITUDE_FIELD, waypoint.getLocation().getLongitude());
resultMap.put(MARKER_LATITUDE_FIELD, marker.getLocation().getLatitude());
resultMap.put(MARKER_LONGITUDE_FIELD, marker.getLocation().getLongitude());
return resultMap;
}
@@ -415,7 +409,7 @@ public class SearchListActivity extends AbstractListActivity implements DeleteMa
String icon = track.getIcon();
String category = icon != null && !icon.equals("") ? null : track.getCategory();
resultMap.put(IS_RECORDING_FIELD, track.getId() == recordingTrackId);
resultMap.put(IS_RECORDING_FIELD, track.getId().equals(recordingTrackId));
resultMap.put(IS_PAUSED_FIELD, recordingTrackPaused);
resultMap.put(ICON_ID_FIELD, TrackIconUtils.getIconDrawable(icon));
resultMap.put(ICON_CONTENT_DESCRIPTION_ID_FIELD, R.string.image_track);
@@ -6,6 +6,7 @@ import android.util.Log;
import java.util.Locale;
import de.dennisguse.opentracks.util.ActivityUtils;
import de.dennisguse.opentracks.util.PreferencesUtils;
/**
@@ -32,6 +33,8 @@ public class Startup extends Application {
PreferencesUtils.setString(this, R.string.stats_units_key, statsUnits);
}
ActivityUtils.applyNightMode(this);
//TODO Workaround to reset recordingTrackId on app startup as the TrackRecordingService (likely) crashed.
if (PreferencesUtils.isRecording(this)) {
Log.e(TAG, "Reset recordingTrackId; likely the TrackRecordingService crashed.");
@@ -24,11 +24,12 @@ import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.annotation.NonNull;
import com.google.android.material.textfield.TextInputEditText;
import de.dennisguse.opentracks.content.data.Track;
import de.dennisguse.opentracks.content.provider.ContentProviderUtils;
import de.dennisguse.opentracks.fragments.ChooseActivityTypeDialogFragment;
@@ -55,10 +56,10 @@ public class TrackEditActivity extends AbstractActivity implements ChooseActivit
private Track track;
private String iconValue;
private EditText nameEditText;
private TextInputEditText nameEditText;
private AutoCompleteTextView activityType;
private Spinner activityTypeIcon;
private EditText description;
private TextInputEditText description;
@Override
protected void onCreate(Bundle bundle) {
@@ -75,7 +76,7 @@ public class TrackEditActivity extends AbstractActivity implements ChooseActivit
contentProviderUtils = new ContentProviderUtils(this);
track = contentProviderUtils.getTrack(trackId);
if (track == null) {
Log.e(TAG, "No track for " + trackId);
Log.e(TAG, "No track for " + trackId.getId());
finish();
return;
}
@@ -214,6 +214,9 @@ public class TrackListActivity extends AbstractListActivity implements ConfirmDe
@Override
protected void onCreate(Bundle savedInstanceState) {
// Reset theme after splash
setTheme(R.style.ThemeCustom);
super.onCreate(savedInstanceState);
gpsStatusValue = GpsStatusValue.GPS_NONE;
@@ -37,7 +37,7 @@ import de.dennisguse.opentracks.content.provider.ContentProviderUtils;
import de.dennisguse.opentracks.fragments.ChartFragment;
import de.dennisguse.opentracks.fragments.ChooseActivityTypeDialogFragment;
import de.dennisguse.opentracks.fragments.ConfirmDeleteDialogFragment;
import de.dennisguse.opentracks.fragments.IntervalsRecordedFragment;
import de.dennisguse.opentracks.fragments.IntervalsFragment;
import de.dennisguse.opentracks.fragments.StatisticsRecordedFragment;
import de.dennisguse.opentracks.services.TrackRecordingServiceConnection;
import de.dennisguse.opentracks.settings.SettingsActivity;
@@ -55,11 +55,11 @@ import de.dennisguse.opentracks.util.TrackUtils;
*/
public class TrackRecordedActivity extends AbstractListActivity implements ChooseActivityTypeDialogFragment.ChooseActivityTypeCaller, ConfirmDeleteDialogFragment.ConfirmDeleteCaller, TrackActivityDataHubInterface {
private static final String TAG = TrackRecordedActivity.class.getSimpleName();
public static final String EXTRA_TRACK_ID = "track_id";
public static final String EXTRA_MARKER_ID = "marker_id";
private static final String TAG = TrackRecordedActivity.class.getSimpleName();
private static final String CURRENT_TAB_TAG_KEY = "current_tab_tag_key";
// The following are set in onCreate.
@@ -67,7 +67,7 @@ public class TrackRecordedActivity extends AbstractListActivity implements Choos
private TrackDataHub trackDataHub;
private ViewPager pager;
private Track track;
private Track.Id trackId;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -100,8 +100,8 @@ public class TrackRecordedActivity extends AbstractListActivity implements Choos
// Update UI
this.invalidateOptionsMenu();
if (track != null) {
trackDataHub.loadTrack(track.getId());
if (trackId != null) {
trackDataHub.loadTrack(trackId);
}
}
@@ -139,6 +139,7 @@ public class TrackRecordedActivity extends AbstractListActivity implements Choos
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.track_detail_markers).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.findItem(R.id.track_detail_resume_track).setVisible(!PreferencesUtils.isRecording(this));
Track track = contentProviderUtils.getTrack(trackId);
setTitle(track != null ? track.getName() : "");
return super.onPrepareOptionsMenu(menu);
}
@@ -148,29 +149,29 @@ public class TrackRecordedActivity extends AbstractListActivity implements Choos
Intent intent;
switch (item.getItemId()) {
case R.id.track_detail_share:
intent = IntentUtils.newShareFileIntent(this, track.getId());
intent = IntentUtils.newShareFileIntent(this, trackId);
intent = Intent.createChooser(intent, null);
startActivity(intent);
return true;
case R.id.track_detail_menu_show_on_map:
IntentDashboardUtils.startDashboard(this, false, track.getId());
IntentDashboardUtils.startDashboard(this, false, trackId);
return true;
case R.id.track_detail_markers:
intent = IntentUtils.newIntent(this, MarkerListActivity.class)
.putExtra(MarkerListActivity.EXTRA_TRACK_ID, track.getId());
.putExtra(MarkerListActivity.EXTRA_TRACK_ID, trackId);
startActivity(intent);
return true;
case R.id.track_detail_edit:
intent = IntentUtils.newIntent(this, TrackEditActivity.class)
.putExtra(TrackEditActivity.EXTRA_TRACK_ID, track.getId());
.putExtra(TrackEditActivity.EXTRA_TRACK_ID, trackId);
startActivity(intent);
return true;
case R.id.track_detail_delete:
deleteTracks(track.getId());
deleteTracks(trackId);
return true;
case R.id.track_detail_resume_track:
Intent newIntent = IntentUtils.newIntent(TrackRecordedActivity.this, TrackRecordingActivity.class)
.putExtra(TrackRecordingActivity.EXTRA_TRACK_ID, track.getId());
.putExtra(TrackRecordingActivity.EXTRA_TRACK_ID, trackId);
startActivity(newIntent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
@@ -204,25 +205,23 @@ public class TrackRecordedActivity extends AbstractListActivity implements Choos
}
private void handleIntent(Intent intent) {
Track.Id trackId = intent.getParcelableExtra(EXTRA_TRACK_ID);
trackId = intent.getParcelableExtra(EXTRA_TRACK_ID);
Marker.Id waypointId = intent.getParcelableExtra(EXTRA_MARKER_ID);
if (waypointId != null) {
Marker.Id markerId = intent.getParcelableExtra(EXTRA_MARKER_ID);
if (markerId != null) {
// Use the trackId from the marker
Marker waypoint = contentProviderUtils.getMarker(waypointId);
if (waypoint == null) {
Marker marker = contentProviderUtils.getMarker(markerId);
if (marker == null) {
finish();
return;
}
trackId = waypoint.getTrackId();
trackId = marker.getTrackId();
}
if (trackId == null) {
Log.e(TAG, "TrackDetailActivity needs EXTRA_TRACK_ID.");
finish();
}
track = contentProviderUtils.getTrack(trackId);
}
public void chooseActivityType(String category) {
@@ -232,6 +231,7 @@ public class TrackRecordedActivity extends AbstractListActivity implements Choos
@Override
public void onChooseActivityTypeDone(String iconValue) {
String category = getString(TrackIconUtils.getIconActivityType(iconValue));
Track track = contentProviderUtils.getTrack(trackId);
TrackUtils.updateTrack(this, track, null, category, null, contentProviderUtils);
}
@@ -251,9 +251,9 @@ public class TrackRecordedActivity extends AbstractListActivity implements Choos
public Fragment getItem(int position) {
switch (position) {
case 0:
return StatisticsRecordedFragment.newInstance(track.getId());
return StatisticsRecordedFragment.newInstance(trackId);
case 1:
return IntervalsRecordedFragment.newInstance(track.getId());
return IntervalsFragment.newInstance(trackId);
case 2:
return ChartFragment.newInstance(false);
case 3:
@@ -25,7 +25,7 @@ import de.dennisguse.opentracks.content.data.Track;
import de.dennisguse.opentracks.content.provider.ContentProviderUtils;
import de.dennisguse.opentracks.fragments.ChartFragment;
import de.dennisguse.opentracks.fragments.ChooseActivityTypeDialogFragment;
import de.dennisguse.opentracks.fragments.IntervalsRecordingFragment;
import de.dennisguse.opentracks.fragments.IntervalsFragment;
import de.dennisguse.opentracks.fragments.StatisticsRecordingFragment;
import de.dennisguse.opentracks.services.TrackRecordingServiceConnection;
import de.dennisguse.opentracks.services.TrackRecordingServiceInterface;
@@ -390,7 +390,7 @@ public class TrackRecordingActivity extends AbstractActivity implements ChooseAc
case 0:
return StatisticsRecordingFragment.newInstance();
case 1:
return IntervalsRecordingFragment.newInstance(trackId);
return IntervalsFragment.IntervalsRecordingFragment.newInstance(trackId);
case 2:
return ChartFragment.newInstance(false);
case 3:
@@ -423,5 +423,8 @@ public class TrackRecordingActivity extends AbstractActivity implements ChooseAc
public void setTrackIdListener(OnTrackIdListener listener) {
this.intervalsListener = listener;
if (trackId != null) {
listener.onTrackId(trackId);
}
}
}
@@ -20,18 +20,21 @@ import de.dennisguse.opentracks.viewmodels.IntervalStatistics;
public class IntervalStatisticsAdapter extends ArrayAdapter<IntervalStatistics.Interval> {
private StackMode stackMode;
private boolean metricUnits;
private float sumDistance_m = 0f;
private float sumDistance_m;
public IntervalStatisticsAdapter(Context context, List<IntervalStatistics.Interval> intervalList) {
public IntervalStatisticsAdapter(Context context, List<IntervalStatistics.Interval> intervalList, StackMode stackMode) {
super(context, R.layout.interval_stats_list_item, intervalList);
metricUnits = PreferencesUtils.isMetricUnits(context);
this.stackMode = stackMode;
}
@NonNull
@Override
public View getView(int position, @Nullable View intervalView, @NonNull ViewGroup parent) {
IntervalStatistics.Interval interval = getItem(position);
int actualPosition = stackMode == StackMode.STACK_FROM_TOP ? position : getCount() - 1 - position;
IntervalStatistics.Interval interval = getItem(actualPosition);
ViewHolder viewHolder;
if (intervalView == null) {
@@ -48,7 +51,11 @@ public class IntervalStatisticsAdapter extends ArrayAdapter<IntervalStatistics.I
viewHolder = (ViewHolder) intervalView.getTag();
}
sumDistance_m += interval.getDistance_m();
if (actualPosition + 1 == getCount() && actualPosition > 0) {
sumDistance_m = actualPosition * getItem(actualPosition - 1).getDistance_m() + interval.getDistance_m();
} else {
sumDistance_m = (actualPosition + 1) * interval.getDistance_m();
}
viewHolder.distance.setText(StringUtils.formatDistance(getContext(), sumDistance_m, metricUnits));
Pair<String, String> speedParts = StringUtils.getSpeedParts(getContext(), interval.getSpeed_ms(), metricUnits, true);
@@ -60,6 +67,14 @@ public class IntervalStatisticsAdapter extends ArrayAdapter<IntervalStatistics.I
return intervalView;
}
/**
* Defines the two modes of list items stacking: from top or from bottom.
*/
public enum StackMode {
STACK_FROM_BOTTOM,
STACK_FROM_TOP
}
private static class ViewHolder {
private TextView distance;
private TextView speed;
@@ -47,9 +47,9 @@ abstract class ChartValueSeries {
private final Paint strokePaint;
private final Paint titlePaint;
private final Paint markerPaint;
private final ExtremityMonitor extremityMonitor;
private final NumberFormat numberFormat;
private final Path path;
private final ExtremityMonitor extremityMonitor = new ExtremityMonitor();
private final NumberFormat numberFormat = NumberFormat.getIntegerInstance();
private final Path path = new Path();
private int interval = 1;
private int minMarkerValue = 0;
@@ -91,17 +91,15 @@ abstract class ChartValueSeries {
titlePaint = new Paint(strokePaint);
titlePaint.setTextSize(ChartView.MEDIUM_TEXT_SIZE * scale);
titlePaint.setTextAlign(Align.CENTER);
titlePaint.setStyle(Style.FILL_AND_STROKE);
markerPaint = new Paint(strokePaint);
markerPaint.setTextSize(ChartView.SMALL_TEXT_SIZE * scale);
markerPaint.setTextAlign(Align.RIGHT);
markerPaint.setStyle(Style.FILL_AND_STROKE);
// Set stroke paint thickness
strokePaint.setStrokeWidth(STROKE_WIDTH);
extremityMonitor = new ExtremityMonitor();
numberFormat = NumberFormat.getIntegerInstance();
path = new Path();
}
/**
@@ -19,7 +19,6 @@ package de.dennisguse.opentracks.chart;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Align;
@@ -47,6 +46,7 @@ import de.dennisguse.opentracks.stats.ExtremityMonitor;
import de.dennisguse.opentracks.util.IntentUtils;
import de.dennisguse.opentracks.util.MarkerUtils;
import de.dennisguse.opentracks.util.StringUtils;
import de.dennisguse.opentracks.util.ThemeUtils;
import de.dennisguse.opentracks.util.UnitConversions;
/**
@@ -75,7 +75,7 @@ public class ChartView extends View {
private static final int Y_AXIS_OFFSET = 16;
//TODO Determine from actual size of the used drawable
private static final float WAYPOINT_X_ANCHOR = 13f / 48f;
private static final float MARKER_X_ANCHOR = 13f / 48f;
static {
X_FRACTION_FORMAT.setMaximumFractionDigits(1);
@@ -87,14 +87,15 @@ public class ChartView extends View {
private final ChartValueSeries paceSeries;
private final List<ChartPoint> chartPoints = new ArrayList<>();
private final List<Marker> waypoints = new ArrayList<>();
private final List<Marker> markers = new ArrayList<>();
private final ExtremityMonitor xExtremityMonitor = new ExtremityMonitor();
private final int backgroundColor;
private final Paint axisPaint;
private final Paint xAxisMarkerPaint;
private final Paint gridPaint;
private final Paint markerPaint;
private final Drawable pointer;
private final Drawable waypointMarker;
private final Drawable markerPin;
private final int markerWidth;
private final int markerHeight;
private final Scroller scroller;
@@ -150,19 +151,19 @@ public class ChartView extends View {
// Check if the y event is within markerHeight of the marker center
if (Math.abs(event.getY() - topBorder - spacer - markerHeight / 2f) < markerHeight) {
int minDistance = Integer.MAX_VALUE;
Marker nearestWaypoint = null;
synchronized (waypoints) {
for (Marker waypoint : waypoints) {
int distance = Math.abs(getX(getWaypointXValue(waypoint)) - (int) event.getX() - getScrollX());
Marker nearestMarker = null;
synchronized (markers) {
for (Marker marker : markers) {
int distance = Math.abs(getX(getMarkerXValue(marker)) - (int) event.getX() - getScrollX());
if (distance < minDistance) {
minDistance = distance;
nearestWaypoint = waypoint;
nearestMarker = marker;
}
}
}
if (nearestWaypoint != null && minDistance < markerWidth) {
if (nearestMarker != null && minDistance < markerWidth) {
Intent intent = IntentUtils.newIntent(getContext(), MarkerDetailActivity.class)
.putExtra(MarkerDetailActivity.EXTRA_MARKER_ID, nearestWaypoint.getId());
.putExtra(MarkerDetailActivity.EXTRA_MARKER_ID, nearestMarker.getId());
getContext().startActivity(intent);
return true;
}
@@ -191,7 +192,6 @@ public class ChartView extends View {
public ChartView(Context context, final boolean chartByDistance) {
super(context);
this.chartByDistance = chartByDistance;
seriesList.add(new ChartValueSeries(context,
Integer.MIN_VALUE,
Integer.MAX_VALUE,
@@ -307,11 +307,13 @@ public class ChartView extends View {
}
});
backgroundColor = ThemeUtils.getBackgroundColor(context);
float scale = context.getResources().getDisplayMetrics().density;
axisPaint = new Paint();
axisPaint.setStyle(Style.STROKE);
axisPaint.setColor(context.getResources().getColor(android.R.color.black));
axisPaint.setStyle(Style.FILL_AND_STROKE);
axisPaint.setColor(ThemeUtils.getTextColorPrimary(context));
axisPaint.setAntiAlias(true);
axisPaint.setTextSize(SMALL_TEXT_SIZE * scale);
@@ -320,22 +322,21 @@ public class ChartView extends View {
gridPaint = new Paint();
gridPaint.setStyle(Style.STROKE);
gridPaint.setColor(context.getResources().getColor(android.R.color.darker_gray));
gridPaint.setColor(ThemeUtils.getTextColorSecondary(context));
gridPaint.setAntiAlias(false);
gridPaint.setPathEffect(new DashPathEffect(new float[]{3, 2}, 0));
markerPaint = new Paint();
markerPaint.setStyle(Style.STROKE);
markerPaint.setColor(context.getResources().getColor(android.R.color.darker_gray));
markerPaint.setAntiAlias(false);
pointer = context.getResources().getDrawable(R.drawable.ic_logo_color_24dp);
pointer.setBounds(0, 0, pointer.getIntrinsicWidth(), pointer.getIntrinsicHeight());
waypointMarker = MarkerUtils.getDefaultPhoto(context);
markerWidth = waypointMarker.getIntrinsicWidth();
markerHeight = waypointMarker.getIntrinsicHeight();
waypointMarker.setBounds(0, 0, markerWidth, markerHeight);
markerPin = MarkerUtils.getDefaultPhoto(context);
markerWidth = markerPin.getIntrinsicWidth();
markerHeight = markerPin.getIntrinsicHeight();
markerPin.setBounds(0, 0, markerWidth, markerHeight);
scroller = new Scroller(context);
setFocusable(true);
@@ -434,15 +435,15 @@ public class ChartView extends View {
scrollTo(0, 0);
}
public void addWaypoint(Marker waypoint) {
synchronized (waypoints) {
waypoints.add(waypoint);
public void addMarker(Marker marker) {
synchronized (markers) {
markers.add(marker);
}
}
public void clearWaypoints() {
synchronized (waypoints) {
waypoints.clear();
public void clearMarker() {
synchronized (markers) {
markers.clear();
}
}
@@ -540,13 +541,13 @@ public class ChartView extends View {
synchronized (chartPoints) {
canvas.save();
canvas.drawColor(Color.WHITE);
canvas.drawColor(backgroundColor);
canvas.save();
clipToGraphArea(canvas);
drawDataSeries(canvas);
drawWaypoints(canvas);
drawMarker(canvas);
drawGrid(canvas);
canvas.restore();
@@ -587,24 +588,19 @@ public class ChartView extends View {
}
}
/**
* Draws the waypoints.
*
* @param canvas the canvas
*/
private void drawWaypoints(Canvas canvas) {
synchronized (waypoints) {
for (Marker waypoint : waypoints) {
double xValue = getWaypointXValue(waypoint);
private void drawMarker(Canvas canvas) {
synchronized (markers) {
for (Marker marker : markers) {
double xValue = getMarkerXValue(marker);
if (xValue > maxX) {
continue;
}
canvas.save();
float x = getX(getWaypointXValue(waypoint));
float x = getX(getMarkerXValue(marker));
canvas.drawLine(x, topBorder + spacer + markerHeight / 2, x, topBorder + effectiveHeight, markerPaint);
canvas.translate(x - (markerWidth * WAYPOINT_X_ANCHOR), topBorder + spacer);
canvas.translate(x - (markerWidth * MARKER_X_ANCHOR), topBorder + spacer);
waypointMarker.draw(canvas);
markerPin.draw(canvas);
canvas.restore();
}
}
@@ -904,7 +900,7 @@ public class ChartView extends View {
for (ChartValueSeries chartValueSeries : seriesList) {
chartValueSeries.updateDimension();
}
float density = getContext().getResources().getDisplayMetrics().density;
float density = getResources().getDisplayMetrics().density;
spacer = (int) (density * SPACER);
yAxisOffset = (int) (density * Y_AXIS_OFFSET);
@@ -975,17 +971,12 @@ public class ChartView extends View {
return topBorder + yAxisOffset + (int) ((1 - percentage) * rangeHeight);
}
/**
* Gets a waypoint's x value.
*
* @param waypoint the waypoint
*/
private double getWaypointXValue(Marker waypoint) {
private double getMarkerXValue(Marker marker) {
if (chartByDistance) {
double lenghtInKm = waypoint.getLength() * UnitConversions.M_TO_KM;
return metricUnits ? lenghtInKm : lenghtInKm * UnitConversions.KM_TO_MI;
double length_km = marker.getLength() * UnitConversions.M_TO_KM;
return metricUnits ? length_km : length_km * UnitConversions.KM_TO_MI;
} else {
return waypoint.getDuration();
return marker.getDuration();
}
}
@@ -136,7 +136,9 @@ public class DescriptionGenerator {
}
// Elevation gain
writeElevation(stats.getTotalElevationGain(), builder, R.string.description_elevation_gain, lineBreak);
if (stats.hasTotalElevationGain()) {
writeElevation(stats.getTotalElevationGain(), builder, R.string.description_elevation_gain, lineBreak);
}
// Recorded time
builder.append(context.getString(R.string.description_recorded_time, StringUtils.formatDateTime(context, stats.getStartTime_ms())));
@@ -250,7 +250,7 @@ public class SearchEngine {
score *= getTimeBoost(query, meanTimestamp);
// Score the currently-selected track lower (user is already there, wouldn't be searching for it).
if (track.getId() == query.currentTrackId) {
if (track.getId().equals(query.currentTrackId)) {
score *= CURRENT_TRACK_DEMOTION;
}
@@ -69,7 +69,7 @@ public final class Marker {
}
/**
* May be null if the waypoint was not loaded from the database.
* May be null if the it was not loaded from the database.
*/
public @Nullable
Id getId() {
@@ -165,16 +165,12 @@ public final class Marker {
this.id = id;
}
public Id(@NonNull String id) {
this(Long.parseLong(id));
}
//TOOD Limit visibility to TrackRecordingService / ContentProvider
public long getId() {
return id;
}
@Deprecated //TODO Use a Waypoint.Id of null instead
@Deprecated //TODO Use a Id of null instead
public boolean isValid() {
return id != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT;
}
@@ -22,7 +22,7 @@ import android.provider.BaseColumns;
import de.dennisguse.opentracks.content.provider.ContentProviderUtils;
/**
* Constants for waypoints table.
* Constants for markers table.
*
* @author Leif Hendrik Wilden
*/
@@ -36,10 +36,10 @@ public interface MarkerColumns extends BaseColumns {
String DEFAULT_SORT_ORDER = _ID;
// Columns
String NAME = "name"; // waypoint name
String DESCRIPTION = "description"; // waypoint description
String CATEGORY = "category"; // waypoint category
String ICON = "icon"; // waypoint icon
String NAME = "name"; // marker name
String DESCRIPTION = "description"; // marker description
String CATEGORY = "category"; // marker category
String ICON = "icon"; // marker icon
String TRACKID = "trackid"; // track id
String LENGTH = "length"; // length of the track (without smoothing)
@@ -118,10 +118,6 @@ public class Track {
this.id = id;
}
public Id(@NonNull String id) {
this(Long.parseLong(id));
}
//TOOD Limit visibility to TrackRecordingService / ContentProvider
public long getId() {
return id;
@@ -32,6 +32,7 @@ public class TrackPoint {
private Float heartRate_bpm = null;
private Float cyclingCadence_rpm = null;
private Float power = null;
private Float elevationGain = null;
public TrackPoint() {
this.location = new Location("");
@@ -47,6 +48,8 @@ public class TrackPoint {
this.heartRate_bpm = trackPoint.getHeartRate_bpm();
this.cyclingCadence_rpm = trackPoint.getCyclingCadence_rpm();
this.power = trackPoint.getPower();
this.elevationGain = trackPoint.getElevationGain();
}
public TrackPoint(double latitude, double longitude, Double altitude, long time) {
@@ -92,6 +95,18 @@ public class TrackPoint {
return location;
}
public boolean hasElevationGain() {
return elevationGain != null;
}
public float getElevationGain() {
return elevationGain;
}
public void setElevationGain(Float elevationGain) {
this.elevationGain = elevationGain;
}
public double getLatitude() {
return location.getLatitude();
}
@@ -51,6 +51,7 @@ public interface TrackPointsColumns extends BaseColumns {
String SENSOR_HEARTRATE = "sensor_heartrate";
String SENSOR_CADENCE = "sensor_cadence";
String SENSOR_POWER = "sensor_power";
String ELEVATION_GAIN = "elevation_gain";
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
@@ -64,7 +65,8 @@ public interface TrackPointsColumns extends BaseColumns {
+ BEARING + " FLOAT, "
+ SENSOR_HEARTRATE + " FLOAT, "
+ SENSOR_CADENCE + " FLOAT, "
+ SENSOR_POWER + " FLOAT)";
+ SENSOR_POWER + " FLOAT, "
+ ELEVATION_GAIN + " FLOAT)";
String CREATE_TABLE_INDEX = "CREATE INDEX " + TABLE_NAME + "_" + TRACKID + "_index ON " + TABLE_NAME + "(" + TRACKID + ")";
}
@@ -19,6 +19,7 @@ class CachedTrackPointsIndexes {
final int sensorHeartRateIndex;
final int sensorCadenceIndex;
final int sensorPowerIndex;
final int elevationGainIndex;
CachedTrackPointsIndexes(Cursor cursor) {
idIndex = cursor.getColumnIndex(TrackPointsColumns._ID);
@@ -32,5 +33,6 @@ class CachedTrackPointsIndexes {
sensorHeartRateIndex = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR_HEARTRATE);
sensorCadenceIndex = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR_CADENCE);
sensorPowerIndex = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR_POWER);
elevationGainIndex = cursor.getColumnIndexOrThrow(TrackPointsColumns.ELEVATION_GAIN);
}
}
@@ -648,6 +648,10 @@ public class ContentProviderUtils {
trackPoint.setPower(cursor.getFloat(indexes.sensorPowerIndex));
}
if (!cursor.isNull(indexes.elevationGainIndex)) {
trackPoint.setElevationGain(cursor.getFloat(indexes.elevationGainIndex));
}
return trackPoint;
}
@@ -836,6 +840,11 @@ public class ContentProviderUtils {
if (trackPoint.hasPower()) {
values.put(TrackPointsColumns.SENSOR_POWER, trackPoint.getPower());
}
if (trackPoint.hasElevationGain()) {
values.put(TrackPointsColumns.ELEVATION_GAIN, trackPoint.getElevationGain());
}
return values;
}
@@ -38,7 +38,7 @@ import de.dennisguse.opentracks.content.data.TrackPointsColumns;
import de.dennisguse.opentracks.content.data.TracksColumns;
/**
* A {@link ContentProvider} that handles access to track points, tracks, and waypoints tables.
* A {@link ContentProvider} that handles access to track points, tracks, and markers tables.
*
* @author Leif Hendrik Wilden
*/
@@ -61,9 +61,9 @@ public class CustomContentProvider extends ContentProvider {
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, TracksColumns.CONTENT_URI.getPath(), UrlType.TRACKS.ordinal());
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, TracksColumns.CONTENT_URI.getPath() + "/*", UrlType.TRACKS_BY_ID.ordinal());
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, MarkerColumns.CONTENT_URI.getPath(), UrlType.WAYPOINTS.ordinal());
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, MarkerColumns.CONTENT_URI.getPath() + "/#", UrlType.WAYPOINTS_BY_ID.ordinal());
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, MarkerColumns.CONTENT_URI_BY_TRACKID.getPath() + "/*", UrlType.WAYPOINTS_BY_TRACKID.ordinal());
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, MarkerColumns.CONTENT_URI.getPath(), UrlType.MARKERS.ordinal());
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, MarkerColumns.CONTENT_URI.getPath() + "/#", UrlType.MARKERS_BY_ID.ordinal());
uriMatcher.addURI(ContentProviderUtils.AUTHORITY_PACKAGE, MarkerColumns.CONTENT_URI_BY_TRACKID.getPath() + "/*", UrlType.MARKERS_BY_TRACKID.ordinal());
}
@Override
@@ -100,7 +100,7 @@ public class CustomContentProvider extends ContentProvider {
table = TracksColumns.TABLE_NAME;
shouldVacuum = true;
break;
case WAYPOINTS:
case MARKERS:
table = MarkerColumns.TABLE_NAME;
break;
default:
@@ -138,10 +138,10 @@ public class CustomContentProvider extends ContentProvider {
return TracksColumns.CONTENT_TYPE;
case TRACKS_BY_ID:
return TracksColumns.CONTENT_ITEMTYPE;
case WAYPOINTS:
case MARKERS:
return MarkerColumns.CONTENT_TYPE;
case WAYPOINTS_BY_ID:
case WAYPOINTS_BY_TRACKID:
case MARKERS_BY_ID:
case MARKERS_BY_TRACKID:
return MarkerColumns.CONTENT_ITEMTYPE;
default:
throw new IllegalArgumentException("Unknown URL " + url);
@@ -213,15 +213,15 @@ public class CustomContentProvider extends ContentProvider {
queryBuilder.setTables(TracksColumns.TABLE_NAME);
queryBuilder.appendWhere(TracksColumns._ID + " IN (" + TextUtils.join(SQL_LIST_DELIMITER, ContentProviderUtils.parseTrackIdsFromUri(url)) + ")");
break;
case WAYPOINTS:
case MARKERS:
queryBuilder.setTables(MarkerColumns.TABLE_NAME);
sortOrder = sort != null ? sort : MarkerColumns.DEFAULT_SORT_ORDER;
break;
case WAYPOINTS_BY_ID:
case MARKERS_BY_ID:
queryBuilder.setTables(MarkerColumns.TABLE_NAME);
queryBuilder.appendWhere(MarkerColumns._ID + "=" + ContentUris.parseId(url));
break;
case WAYPOINTS_BY_TRACKID:
case MARKERS_BY_TRACKID:
queryBuilder.setTables(MarkerColumns.TABLE_NAME);
queryBuilder.appendWhere(MarkerColumns.TRACKID + " IN (" + TextUtils.join(SQL_LIST_DELIMITER, ContentProviderUtils.parseTrackIdsFromUri(url)) + ")");
break;
@@ -261,11 +261,11 @@ public class CustomContentProvider extends ContentProvider {
whereClause += " AND (" + where + ")";
}
break;
case WAYPOINTS:
case MARKERS:
table = MarkerColumns.TABLE_NAME;
whereClause = where;
break;
case WAYPOINTS_BY_ID:
case MARKERS_BY_ID:
table = MarkerColumns.TABLE_NAME;
whereClause = MarkerColumns._ID + "=" + ContentUris.parseId(url);
if (!TextUtils.isEmpty(where)) {
@@ -316,8 +316,8 @@ public class CustomContentProvider extends ContentProvider {
return insertTrackPoint(url, contentValues);
case TRACKS:
return insertTrack(url, contentValues);
case WAYPOINTS:
return insertWaypoint(url, contentValues);
case MARKERS:
return insertMarker(url, contentValues);
default:
throw new IllegalArgumentException("Unknown url " + url);
}
@@ -361,25 +361,14 @@ public class CustomContentProvider extends ContentProvider {
throw new SQLException("Failed to insert a track " + url);
}
/**
* Inserts a waypoint.
*
* @param url the content url
* @param contentValues the content values
*/
private Uri insertWaypoint(Uri url, ContentValues contentValues) {
private Uri insertMarker(Uri url, ContentValues contentValues) {
long rowId = db.insert(MarkerColumns.TABLE_NAME, MarkerColumns._ID, contentValues);
if (rowId >= 0) {
return ContentUris.appendId(MarkerColumns.CONTENT_URI.buildUpon(), rowId).build();
}
throw new SQLException("Failed to insert a waypoint " + url);
throw new SQLException("Failed to insert a marker " + url);
}
/**
* Types of url.
*
* @author Jimmy Shih
*/
@VisibleForTesting
enum UrlType {
TRACKPOINTS,
@@ -387,8 +376,8 @@ public class CustomContentProvider extends ContentProvider {
TRACKPOINTS_BY_TRACKID,
TRACKS,
TRACKS_BY_ID,
WAYPOINTS,
WAYPOINTS_BY_ID,
WAYPOINTS_BY_TRACKID
MARKERS,
MARKERS_BY_ID,
MARKERS_BY_TRACKID
}
}
@@ -25,7 +25,7 @@ public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {
private static final String TAG = CustomSQLiteOpenHelper.class.getSimpleName();
private static final int DATABASE_VERSION = 26;
private static final int DATABASE_VERSION = 27;
@VisibleForTesting
public static final String DATABASE_NAME = "database.db";
@@ -70,6 +70,10 @@ public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {
case 26:
upgradeFrom25to26(db);
break;
case 27:
upgradeFrom26to27(db);
break;
default:
throw new RuntimeException("Not implemented: upgrade to " + toVersion);
@@ -91,6 +95,9 @@ public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {
case 25:
downgradeFrom26to25(db);
break;
case 26:
downgradeFrom27to26(db);
break;
default:
throw new RuntimeException("Not implemented: downgrade to " + toVersion);
@@ -166,7 +173,7 @@ public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {
Track.Id trackId = new Track.Id(cursor.getLong(trackIdIndex));
ContentValues cv = new ContentValues();
cv.put("uuid", UUIDUtils.toBytes(UUID.randomUUID()));
db.update("tracks", cv, "_id = ?", new String[]{String.valueOf(trackId)});
db.update("tracks", cv, "_id = ?", new String[]{String.valueOf(trackId.getId())});
} while (cursor.moveToNext());
}
}
@@ -190,4 +197,27 @@ public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {
db.setTransactionSuccessful();
db.endTransaction();
}
private void upgradeFrom26to27(SQLiteDatabase db) {
db.beginTransaction();
db.execSQL("ALTER TABLE trackpoints ADD COLUMN elevation_gain FLOAT");
db.setTransactionSuccessful();
db.endTransaction();
}
private void downgradeFrom27to26(SQLiteDatabase db) {
db.beginTransaction();
db.execSQL("ALTER TABLE trackpoints RENAME TO trackpoints_old");
db.execSQL("CREATE TABLE trackpoints (_id INTEGER PRIMARY KEY AUTOINCREMENT, trackid INTEGER, longitude INTEGER, latitude INTEGER, time INTEGER, elevation FLOAT, accuracy FLOAT, speed FLOAT, bearing FLOAT, sensor_heartrate FLOAT, sensor_cadence FLOAT, sensor_power FLOAT)");
db.execSQL("INSERT INTO trackpoints SELECT _id, trackid, longitude, latitude, time, elevation, accuracy, speed, bearing, sensor_heartrate, sensor_cadence, sensor_power FROM trackpoints_old");
db.execSQL("DROP TABLE trackpoints_old");
db.execSQL("CREATE INDEX trackpoints_trackid_index ON trackpoints(trackid)");
db.setTransactionSuccessful();
db.endTransaction();
}
}
@@ -244,14 +244,14 @@ public class ChartFragment extends Fragment implements TrackDataListener {
@Override
public void clearMarkers() {
if (isResumed()) {
chartView.clearWaypoints();
chartView.clearMarker();
}
}
@Override
public void onNewMarker(Marker marker) {
if (isResumed() && marker != null && LocationUtils.isValidLocation(marker.getLocation())) {
chartView.addWaypoint(marker);
chartView.addMarker(marker);
}
}
@@ -22,6 +22,8 @@ import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import androidx.core.content.ContextCompat;
import java.util.List;
import de.dennisguse.opentracks.R;
@@ -76,7 +78,7 @@ class ChooseActivityTypeImageAdapter extends BaseAdapter {
}
if (position == selected) {
imageView.setBackgroundResource(R.drawable.list_selector_background_transition_holo_dark);
imageView.setBackgroundColor(ContextCompat.getColor(parent.getContext(), R.color.colorAccent));
} else {
imageView.setBackgroundColor(Color.TRANSPARENT);
}
@@ -42,9 +42,9 @@ public class DeleteMarkerDialogFragment extends DialogFragment {
private DeleteMarkerCaller caller;
public static void showDialog(FragmentManager fragmentManager, Marker.Id... waypointIds) {
public static void showDialog(FragmentManager fragmentManager, Marker.Id... markerIds) {
Bundle bundle = new Bundle();
bundle.putParcelableArray(KEY_MARKER_IDS, waypointIds);
bundle.putParcelableArray(KEY_MARKER_IDS, markerIds);
DeleteMarkerDialogFragment deleteMarkerDialogFragment = new DeleteMarkerDialogFragment();
deleteMarkerDialogFragment.setArguments(bundle);
@@ -16,12 +16,12 @@
package de.dennisguse.opentracks.fragments;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
@@ -38,6 +38,7 @@ import de.dennisguse.opentracks.R;
import de.dennisguse.opentracks.content.data.Track;
import de.dennisguse.opentracks.content.data.TracksColumns;
import de.dennisguse.opentracks.content.provider.ContentProviderUtils;
import de.dennisguse.opentracks.io.file.ExportFile;
import de.dennisguse.opentracks.io.file.TrackFileFormat;
import de.dennisguse.opentracks.io.file.exporter.TrackExporter;
import de.dennisguse.opentracks.util.DialogUtils;
@@ -208,33 +209,32 @@ public class ExportProgressDialogFragment extends DialogFragment {
private Boolean exportTrack(Context context, Track track) {
TrackExporter trackExporter = trackFileFormat.newTrackExporter(context);
//TODO Move to helper function
String fileName = track.getId().getId() + "." + trackFileFormat.getExtension();
DocumentFile exportDocumentFile = ExportFile.getExportDocumentFile(
track.getId(),
trackFileFormat.getExtension(),
directory,
trackFileFormat.getMimeType()
);
// Overwrite a file if it exists; DocumentFile.createFile() creates a new file appending a suffix if the displayname already exists.
DocumentFile file = directory.findFile(fileName);
if (file == null) {
file = directory.createFile(trackFileFormat.getMimeType(), fileName);
}
try (OutputStream outputStream = context.getContentResolver().openOutputStream(file.getUri())) {
try (OutputStream outputStream = context.getContentResolver().openOutputStream(exportDocumentFile.getUri())) {
if (trackExporter.writeTrack(track, outputStream)) {
return true;
} else {
if (!file.delete()) {
Log.e(TAG, "Unable to delete file");
if (!exportDocumentFile.delete()) {
Log.e(TAG, "Unable to delete exportDocumentFile");
}
Log.e(TAG, "Unable to export track");
return false;
}
} catch (FileNotFoundException e) {
Log.e(TAG, "Unable to open file " + file.getName(), e);
Log.e(TAG, "Unable to open exportDocumentFile " + exportDocumentFile.getName(), e);
return false;
} catch (IOException e) {
Log.e(TAG, "Unable to close file output stream", e);
Log.e(TAG, "Unable to close exportDocumentFile output stream", e);
return false;
}
}
}
public interface DismissCallback {
@@ -16,12 +16,12 @@
package de.dennisguse.opentracks.fragments;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
@@ -0,0 +1,225 @@
package de.dennisguse.opentracks.fragments;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import de.dennisguse.opentracks.R;
import de.dennisguse.opentracks.TrackRecordingActivity;
import de.dennisguse.opentracks.adapters.IntervalStatisticsAdapter;
import de.dennisguse.opentracks.content.data.Track;
import de.dennisguse.opentracks.util.PreferencesUtils;
import de.dennisguse.opentracks.util.UnitConversions;
import de.dennisguse.opentracks.viewmodels.IntervalStatistics;
import de.dennisguse.opentracks.viewmodels.IntervalStatisticsModel;
/**
* A fragment to display the intervals from recorded track.
*/
public class IntervalsFragment extends Fragment {
private static final String TAG = IntervalsFragment.class.getSimpleName();
private static final String TRACK_ID_KEY = "trackId";
private IntervalStatisticsModel viewModel;
private ListView intervalListView;
protected IntervalStatisticsAdapter.StackMode stackModeListView;
private IntervalStatisticsModel.IntervalOption selectedInterval;
private String intervalUnit;
private IntervalStatisticsAdapter adapter;
protected Spinner spinnerIntervals;
private ArrayAdapter<IntervalStatisticsModel.IntervalOption> spinnerAdapter;
private Track.Id trackId;
protected final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = (preferences, key) -> {
if (PreferencesUtils.isKey(getContext(), R.string.stats_units_key, key) || PreferencesUtils.isKey(getContext(), R.string.stats_rate_key, key)) {
intervalUnit = PreferencesUtils.isMetricUnits(getContext()) ? getContext().getString(R.string.unit_kilometer) : getContext().getString(R.string.unit_mile);
if (adapter != null) {
adapter.notifyDataSetChanged();
spinnerAdapter.notifyDataSetChanged();
intervalChanged();
}
}
};
public static Fragment newInstance(Track.Id trackId) {
Bundle bundle = new Bundle();
bundle.putParcelable(TRACK_ID_KEY, trackId);
Fragment fragment = new IntervalsFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.interval_list_view, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PreferencesUtils.register(getContext(), sharedPreferenceChangeListener);
intervalUnit = PreferencesUtils.isMetricUnits(getContext()) ? getContext().getString(R.string.unit_kilometer) : getContext().getString(R.string.unit_mile);
if (savedInstanceState != null) {
trackId = savedInstanceState.getParcelable(TRACK_ID_KEY);
} else {
trackId = getArguments().getParcelable(TRACK_ID_KEY);
}
intervalListView = view.findViewById(R.id.interval_list);
intervalListView.setEmptyView(view.findViewById(R.id.interval_list_empty_view));
stackModeListView = IntervalStatisticsAdapter.StackMode.STACK_FROM_TOP;
viewModel = new ViewModelProvider(this).get(IntervalStatisticsModel.class);
spinnerIntervals = view.findViewById(R.id.spinner_intervals);
spinnerAdapter = new ArrayAdapter<IntervalStatisticsModel.IntervalOption>(getContext(), android.R.layout.simple_spinner_dropdown_item, IntervalStatisticsModel.IntervalOption.values()) {
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
TextView v = (TextView) super.getView(position, convertView, parent);
v.setText(v.getText() + " " + intervalUnit);
return v;
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
TextView v = (TextView) super.getDropDownView(position, convertView, parent);
v.setText(v.getText() + " " + intervalUnit);
return v;
}
};
spinnerIntervals.setAdapter(spinnerAdapter);
spinnerIntervals.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedInterval = IntervalStatisticsModel.IntervalOption.values()[i];
intervalChanged();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
intervalChanged();
}
@Override
public void onDestroy() {
super.onDestroy();
PreferencesUtils.unregister(getContext(), sharedPreferenceChangeListener);
intervalListView = null;
adapter = null;
spinnerIntervals = null;
viewModel = null;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(TRACK_ID_KEY, trackId);
}
/**
* Update intervals through {@link IntervalStatisticsModel} view model.
*/
public void intervalChanged() {
if (viewModel == null || intervalListView == null) {
return;
}
LiveData<IntervalStatistics> liveData = viewModel.getIntervalStats(trackId, selectedInterval);
liveData.observe(getActivity(), intervalStatistics -> {
if (intervalStatistics != null) {
adapter = new IntervalStatisticsAdapter(getContext(), intervalStatistics.getIntervalList(), stackModeListView);
intervalListView.setAdapter(adapter);
}
});
}
public void setTrackId(Track.Id trackId) {
this.trackId = trackId;
}
public static class IntervalsRecordingFragment extends IntervalsFragment implements TrackRecordingActivity.OnTrackIdListener {
// Refreshing intervals stats it's not so demanding so 5 seconds is enough to balance performance and user experience.
private static final long UI_UPDATE_INTERVAL = 5 * UnitConversions.ONE_SECOND_MS;
private Handler intervalHandler;
private final Runnable intervalRunner = new Runnable() {
@Override
public void run() {
if (isResumed()) {
updateIntervals();
intervalHandler.postDelayed(intervalRunner, UI_UPDATE_INTERVAL);
}
}
};
public static Fragment newInstance(Track.Id trackId) {
Bundle bundle = new Bundle();
bundle.putParcelable(TRACK_ID_KEY, trackId);
Fragment fragment = new IntervalsRecordingFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((TrackRecordingActivity) getActivity()).setTrackIdListener(this);
intervalHandler = new Handler();
stackModeListView = IntervalStatisticsAdapter.StackMode.STACK_FROM_BOTTOM;
}
@Override
public void onResume() {
super.onResume();
intervalHandler.post(intervalRunner);
}
@Override
public void onPause() {
super.onPause();
intervalHandler.removeCallbacks(intervalRunner);
}
private void updateIntervals() {
intervalChanged();
}
@Override
public void onTrackId(Track.Id trackId) {
setTrackId(trackId);
}
}
}
@@ -1,105 +0,0 @@
package de.dennisguse.opentracks.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import de.dennisguse.opentracks.R;
import de.dennisguse.opentracks.content.data.Track;
import de.dennisguse.opentracks.viewmodels.IntervalStatistics;
import de.dennisguse.opentracks.viewmodels.IntervalStatisticsModel;
import de.dennisguse.opentracks.views.IntervalListView;
/**
* A fragment to display the intervals from recorded track.
*/
public class IntervalsRecordedFragment extends Fragment implements IntervalListView.IntervalListListener {
private static final String TAG = IntervalsRecordedFragment.class.getSimpleName();
private static final String TRACK_ID_KEY = "trackId";
private IntervalStatisticsModel viewModel;
private IntervalListView intervalListView;
private Track.Id trackId;
public static Fragment newInstance(Track.Id trackId) {
Bundle bundle = new Bundle();
bundle.putParcelable(TRACK_ID_KEY, trackId);
Fragment fragment = new IntervalsRecordedFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.intervals_recording, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
trackId = getArguments().getParcelable(TRACK_ID_KEY);
intervalListView = new IntervalListView(getActivity(), this);
intervalListView.setId(View.generateViewId());
LinearLayout linearLayout = view.findViewById(R.id.root_view);
linearLayout.removeAllViews();
linearLayout.addView(intervalListView);
viewModel = new ViewModelProvider(this).get(IntervalStatisticsModel.class);
intervalChanged(null);
}
@Override
public void onDestroy() {
super.onDestroy();
intervalListView.destroy();
intervalListView = null;
viewModel = null;
}
/**
* Update intervals through {@link IntervalStatisticsModel} view model.
*
* @param interval intervals will split in this interval if not null. If it's null then view model will use the default one.
*/
@Override
public void intervalChanged(@Nullable IntervalStatisticsModel.IntervalOption interval) {
if (viewModel == null || intervalListView == null) {
return;
}
LiveData<IntervalStatistics> liveData = viewModel.getIntervalStats(trackId, interval);
liveData.observe(getActivity(), intervalStatistics -> {
if (intervalStatistics != null) {
intervalListView.display(intervalStatistics.getIntervalList());
}
});
}
@Override
public void unitChanged() {
if (viewModel != null) {
LiveData<IntervalStatistics> liveData = viewModel.getIntervalStats(trackId, null);
liveData.observe(getActivity(), intervalStatistics -> {
if (intervalStatistics != null) {
intervalListView.display(intervalStatistics.getIntervalList());
}
});
}
}
}
@@ -1,147 +0,0 @@
package de.dennisguse.opentracks.fragments;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import de.dennisguse.opentracks.R;
import de.dennisguse.opentracks.TrackRecordingActivity;
import de.dennisguse.opentracks.content.data.Track;
import de.dennisguse.opentracks.util.UnitConversions;
import de.dennisguse.opentracks.viewmodels.IntervalStatistics;
import de.dennisguse.opentracks.viewmodels.IntervalStatisticsModel;
import de.dennisguse.opentracks.views.IntervalListView;
/**
* A fragment to display the intervals from recording track.
*/
public class IntervalsRecordingFragment extends Fragment implements IntervalListView.IntervalListListener, TrackRecordingActivity.OnTrackIdListener {
private static final String TAG = IntervalsRecordingFragment.class.getSimpleName();
private static final String TRACK_ID_KEY = "trackId";
// Refreshing intervals stats it's not so demanding so 5 seconds is enough to balance performance and user experience.
private static final long UI_UPDATE_INTERVAL = 5 * UnitConversions.ONE_SECOND_MS;
private IntervalStatisticsModel viewModel;
private IntervalListView.IntervalReverseListView intervalListView;
private IntervalStatisticsModel.IntervalOption selectedInterval;
private Track.Id trackId;
public static Fragment newInstance(Track.Id trackId) {
Bundle bundle = new Bundle();
bundle.putParcelable(TRACK_ID_KEY, trackId);
Fragment fragment = new IntervalsRecordingFragment();
fragment.setArguments(bundle);
return fragment;
}
private final Runnable intervalRunner = new Runnable() {
@Override
public void run() {
if (isResumed()) {
updateIntervals();
intervalHandler.postDelayed(intervalRunner, UI_UPDATE_INTERVAL);
}
}
};
private Handler intervalHandler;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.intervals_recording, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
trackId = getArguments().getParcelable(TRACK_ID_KEY);
((TrackRecordingActivity) getActivity()).setTrackIdListener(this);
intervalHandler = new Handler();
intervalListView = new IntervalListView.IntervalReverseListView(getActivity(), this);
intervalListView.setId(View.generateViewId());
LinearLayout linearLayout = view.findViewById(R.id.root_view);
linearLayout.removeAllViews();
linearLayout.addView(intervalListView);
viewModel = new ViewModelProvider(this).get(IntervalStatisticsModel.class);
}
@Override
public void onResume() {
super.onResume();
intervalHandler.post(intervalRunner);
}
@Override
public void onPause() {
super.onPause();
intervalHandler.removeCallbacks(intervalRunner);
}
@Override
public void onDestroy() {
super.onDestroy();
intervalListView.destroy();
intervalListView = null;
viewModel = null;
}
/**
* Update intervals through {@link IntervalStatisticsModel} view model.
*
* @param interval intervals will split in this interval if not null. If it's null then view model will use the default one.
*/
@Override
public void intervalChanged(@Nullable IntervalStatisticsModel.IntervalOption interval) {
if (viewModel == null || intervalListView == null) {
return;
}
selectedInterval = interval;
LiveData<IntervalStatistics> liveData = viewModel.getIntervalStats(trackId, interval);
liveData.observe(getActivity(), intervalStatistics -> {
if (intervalStatistics != null) {
intervalListView.display(intervalStatistics.getIntervalList());
}
});
}
private void updateIntervals() {
intervalChanged(selectedInterval);
}
@Override
public void unitChanged() {
if (viewModel != null) {
LiveData<IntervalStatistics> liveData = viewModel.getIntervalStats(trackId, selectedInterval);
liveData.observe(getActivity(), intervalStatistics -> {
if (intervalStatistics != null) {
intervalListView.display(intervalStatistics.getIntervalList());
}
});
}
}
@Override
public void onTrackId(Track.Id trackId) {
this.trackId = trackId;
}
}
@@ -66,8 +66,8 @@ public class MarkerDetailFragment extends Fragment {
private Handler handler;
private ImageView photoView;
private ImageView textGradient;
private LinearLayout waypointInfo;
private Marker waypoint;
private LinearLayout markerInfo;
private Marker marker;
private final Runnable hideText = new Runnable() {
@Override
public void run() {
@@ -85,17 +85,17 @@ public class MarkerDetailFragment extends Fragment {
@Override
public void onAnimationEnd(Animation anim) {
textGradient.setVisibility(View.GONE);
waypointInfo.setVisibility(View.GONE);
markerInfo.setVisibility(View.GONE);
}
});
textGradient.startAnimation(animation);
waypointInfo.startAnimation(animation);
markerInfo.startAnimation(animation);
}
};
public static MarkerDetailFragment newInstance(Marker.Id waypointId) {
public static MarkerDetailFragment newInstance(Marker.Id markerId) {
Bundle bundle = new Bundle();
bundle.putParcelable(KEY_MARKER_ID, waypointId);
bundle.putParcelable(KEY_MARKER_ID, markerId);
MarkerDetailFragment fragment = new MarkerDetailFragment();
fragment.setArguments(bundle);
@@ -106,8 +106,8 @@ public class MarkerDetailFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Marker.Id waypointId = getArguments().getParcelable(KEY_MARKER_ID);
if (waypointId == null) {
Marker.Id markerId = getArguments().getParcelable(KEY_MARKER_ID);
if (markerId == null) {
Log.d(TAG, "invalid marker id");
getParentFragmentManager().popBackStack();
return;
@@ -121,15 +121,15 @@ public class MarkerDetailFragment extends Fragment {
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.marker_detail_fragment, container, false);
photoView = view.findViewById(R.id.marker_detail_waypoint_photo);
textGradient = view.findViewById(R.id.marker_detail_waypoint_text_gradient);
waypointInfo = view.findViewById(R.id.marker_detail_waypoint_info);
photoView = view.findViewById(R.id.marker_detail_marker_photo);
textGradient = view.findViewById(R.id.marker_detail_marker_text_gradient);
markerInfo = view.findViewById(R.id.marker_detail_marker_info);
photoView.setOnClickListener(v -> {
handler.removeCallbacks(hideText);
int visibility = waypointInfo.getVisibility() == View.GONE ? View.VISIBLE : View.GONE;
int visibility = markerInfo.getVisibility() == View.GONE ? View.VISIBLE : View.GONE;
textGradient.setVisibility(visibility);
waypointInfo.setVisibility(visibility);
markerInfo.setVisibility(visibility);
if (visibility == View.VISIBLE) {
handler.postDelayed(hideText, HIDE_TEXT_DELAY);
}
@@ -141,8 +141,8 @@ public class MarkerDetailFragment extends Fragment {
public void onResume() {
super.onResume();
// Need to update the waypoint in case returning after an edit
updateWaypoint(true);
// Need to update the marker in case returning after an edit
updateMarker(true);
updateUi();
updateMenuItems();
}
@@ -171,64 +171,59 @@ public class MarkerDetailFragment extends Fragment {
public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.marker_detail, menu);
shareMarkerImageMenuItem = menu.findItem(R.id.marker_detail_share);
updateWaypoint(false);
updateMarker(false);
updateMenuItems();
}
private void updateMenuItems() {
if (shareMarkerImageMenuItem != null)
shareMarkerImageMenuItem.setVisible(waypoint.hasPhoto());
shareMarkerImageMenuItem.setVisible(marker.hasPhoto());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Marker.Id waypointId = getArguments().getParcelable(KEY_MARKER_ID); //TODO Should only happen in onCreate?
Marker.Id markerId = getArguments().getParcelable(KEY_MARKER_ID); //TODO Should only happen in onCreate?
FragmentActivity fragmentActivity = getActivity();
Intent intent;
switch (item.getItemId()) {
case R.id.marker_detail_show_on_map:
IntentUtils.showCoordinateOnMap(getContext(), waypoint);
IntentUtils.showCoordinateOnMap(getContext(), marker);
return true;
case R.id.marker_detail_edit:
intent = IntentUtils.newIntent(fragmentActivity, MarkerEditActivity.class)
.putExtra(MarkerEditActivity.EXTRA_MARKER_ID, waypointId);
.putExtra(MarkerEditActivity.EXTRA_MARKER_ID, markerId);
startActivity(intent);
return true;
case R.id.marker_detail_share:
if (waypoint.hasPhoto()) {
intent = IntentUtils.newShareImageIntent(getContext(), waypoint.getPhotoURI());
if (marker.hasPhoto()) {
intent = IntentUtils.newShareImageIntent(getContext(), marker.getPhotoURI());
intent = Intent.createChooser(intent, null);
startActivity(intent);
}
return true;
case R.id.marker_detail_delete:
DeleteMarkerDialogFragment.showDialog(getChildFragmentManager(), waypointId);
DeleteMarkerDialogFragment.showDialog(getChildFragmentManager(), markerId);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Updates the waypoint.
*
* @param refresh true to always update
*/
private void updateWaypoint(boolean refresh) {
if (refresh || waypoint == null) {
waypoint = contentProviderUtils.getMarker(getArguments().getParcelable(KEY_MARKER_ID)); //TODO Should only happen in onCreate?
if (waypoint == null) {
Log.d(TAG, "waypoint is null");
private void updateMarker(boolean refresh) {
if (refresh || marker == null) {
marker = contentProviderUtils.getMarker(getArguments().getParcelable(KEY_MARKER_ID)); //TODO Should only happen in onCreate?
if (marker == null) {
Log.d(TAG, "marker is null");
getParentFragmentManager().popBackStack();
}
}
}
private void updateUi() {
boolean hasPhoto = waypoint.hasPhoto();
boolean hasPhoto = marker.hasPhoto();
if (hasPhoto) {
handler.removeCallbacks(hideText);
photoView.setImageURI(waypoint.getPhotoURI());
photoView.setImageURI(marker.getPhotoURI());
handler.postDelayed(hideText, HIDE_TEXT_DELAY);
} else {
photoView.setImageResource(MarkerUtils.ICON_ID);
@@ -236,23 +231,23 @@ public class MarkerDetailFragment extends Fragment {
setName(hasPhoto);
TextView category = getView().findViewById(R.id.marker_detail_waypoint_category);
ListItemUtils.setTextView(getActivity(), category, StringUtils.getCategory(waypoint.getCategory()), hasPhoto);
TextView category = getView().findViewById(R.id.marker_detail_marker_category);
ListItemUtils.setTextView(getActivity(), category, StringUtils.getCategory(marker.getCategory()), hasPhoto);
TextView description = getView().findViewById(R.id.marker_detail_waypoint_description);
ListItemUtils.setTextView(getActivity(), description, waypoint.getDescription(), hasPhoto);
TextView description = getView().findViewById(R.id.marker_detail_marker_description);
ListItemUtils.setTextView(getActivity(), description, marker.getDescription(), hasPhoto);
setLocation(hasPhoto);
}
private void setName(boolean addShadow) {
TextView textView = getView().findViewById(R.id.marker_detail_waypoint_name);
ListItemUtils.setTextView(getActivity(), textView, waypoint.getName(), addShadow);
TextView textView = getView().findViewById(R.id.marker_detail_marker_name);
ListItemUtils.setTextView(getActivity(), textView, marker.getName(), addShadow);
}
private void setLocation(boolean addShadow) {
TextView textView = getView().findViewById(R.id.marker_detail_waypoint_location);
Location location = waypoint.getLocation();
TextView textView = getView().findViewById(R.id.marker_detail_marker_location);
Location location = marker.getLocation();
String value;
if (location == null) {
value = null;
@@ -19,20 +19,19 @@ package de.dennisguse.opentracks.fragments;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.Group;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import de.dennisguse.opentracks.R;
import de.dennisguse.opentracks.TrackRecordedActivity;
import de.dennisguse.opentracks.content.data.Track;
import de.dennisguse.opentracks.content.provider.ContentProviderUtils;
import de.dennisguse.opentracks.stats.TrackStatistics;
@@ -52,7 +51,8 @@ public class StatisticsRecordedFragment extends Fragment {
private TrackStatistics trackStatistics;
private String category = "";
private Track track;
private Track.Id trackId;
private ContentProviderUtils contentProviderUtils;
private final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = (preferences, key) -> {
if (PreferencesUtils.isKey(getContext(), R.string.stats_units_key, key) || PreferencesUtils.isKey(getContext(), R.string.stats_rate_key, key)) {
@@ -75,7 +75,7 @@ public class StatisticsRecordedFragment extends Fragment {
private TextView distanceValue;
private TextView distanceUnit;
private View activityLabel;
private Spinner activitySpinner;
private ImageView activitySpinner;
private TextView movingTimeValue;
private TextView speedAvgLabel;
private TextView speedAvgValue;
@@ -87,6 +87,10 @@ public class StatisticsRecordedFragment extends Fragment {
private TextView speedMovingValue;
private TextView speedMovingUnit;
private Group elevationGroup;
private TextView elevationTotalGainValue;
private TextView elevationTotalGainUnit;
public static StatisticsRecordedFragment newInstance(Track.Id trackId) {
Bundle bundle = new Bundle();
bundle.putParcelable(TRACK_ID_KEY, trackId);
@@ -100,9 +104,8 @@ public class StatisticsRecordedFragment extends Fragment {
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Track.Id trackId = getArguments().getParcelable(TRACK_ID_KEY);
ContentProviderUtils contentProviderUtils = new ContentProviderUtils(getContext());
track = contentProviderUtils.getTrack(trackId);
trackId = getArguments().getParcelable(TRACK_ID_KEY);
contentProviderUtils = new ContentProviderUtils(getContext());
}
@Override
@@ -130,26 +133,10 @@ public class StatisticsRecordedFragment extends Fragment {
speedMovingLabel = view.findViewById(R.id.stats_moving_speed_label);
speedMovingValue = view.findViewById(R.id.stats_moving_speed_value);
speedMovingUnit = view.findViewById(R.id.stats_moving_speed_unit);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Spinner activityTypeIcon = getView().findViewById(R.id.stats_activity_type_icon);
activityTypeIcon.setAdapter(TrackIconUtils.getIconSpinnerAdapter(getActivity(), ""));
activityTypeIcon.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
((TrackRecordedActivity) getActivity()).chooseActivityType(category);
}
return true;
});
activityTypeIcon.setOnKeyListener((v, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
((TrackRecordedActivity) getActivity()).chooseActivityType(category);
}
return true;
});
elevationGroup = view.findViewById(R.id.stats_elevation_group);
elevationTotalGainValue = view.findViewById(R.id.stats_elevation_gain_value);
elevationTotalGainUnit = view.findViewById(R.id.stats_elevation_gain_unit);
}
@Override
@@ -187,12 +174,17 @@ public class StatisticsRecordedFragment extends Fragment {
speedMovingLabel = null;
speedMovingValue = null;
speedMovingUnit = null;
elevationGroup = null;
elevationTotalGainValue = null;
elevationTotalGainUnit = null;
}
public void loadStatistics() {
if (isResumed()) {
getActivity().runOnUiThread(() -> {
if (isResumed()) {
Track track = contentProviderUtils.getTrack(trackId);
trackStatistics = track != null ? track.getTrackStatistics() : null;
category = track != null ? track.getCategory() : "";
updateUI();
@@ -202,8 +194,6 @@ public class StatisticsRecordedFragment extends Fragment {
}
private void updateUI() {
String trackIconValue = TrackIconUtils.getIconValue(getContext(), category);
boolean metricUnits = PreferencesUtils.isMetricUnits(getContext());
boolean reportSpeed = PreferencesUtils.isReportSpeed(getContext(), category);
@@ -218,12 +208,14 @@ public class StatisticsRecordedFragment extends Fragment {
// Set activity type
{
String trackIconValue = TrackIconUtils.getIconValue(getContext(), category);
activityLabel.setVisibility(trackIconValue != null ? View.VISIBLE : View.GONE);
activitySpinner.setVisibility(trackIconValue != null ? View.VISIBLE : View.GONE);
activitySpinner.setEnabled(false);
if (trackIconValue != null) {
TrackIconUtils.setIconSpinner(activitySpinner, trackIconValue);
activitySpinner.setImageDrawable(ContextCompat.getDrawable(getContext(), TrackIconUtils.getIconDrawable(trackIconValue)));
}
}
@@ -264,5 +256,18 @@ public class StatisticsRecordedFragment extends Fragment {
speedMovingValue.setText(parts.first);
speedMovingUnit.setText(parts.second);
}
// Set elevation gain
{
// Make elevation visible?
boolean showElevation = PreferencesUtils.isShowStatsElevation(getContext());
elevationGroup.setVisibility(showElevation ? View.VISIBLE : View.GONE);
Float elevationGain_m = trackStatistics != null ? trackStatistics.getTotalElevationGain() : null;
Pair<String, String> parts = StringUtils.formatElevation(getContext(), elevationGain_m, metricUnits);
elevationTotalGainValue.setText(parts.first);
elevationTotalGainUnit.setText(parts.second);
}
}
}
@@ -132,12 +132,14 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
private TextView speedMovingLabel;
private TextView speedMovingValue;
private TextView speedMovingUnit;
private Group elevationGroup;
private TextView speedLabel;
private TextView speedValue;
private TextView speedUnit;
private TextView elevationValue;
private TextView elevationUnit;
private Group elevationGroup;
private TextView elevationCurrentValue;
private TextView elevationCurrentUnit;
private TextView elevationTotalGainValue;
private TextView elevationTotalGainUnit;
private Group coordinateGroup;
private TextView latitudeValue;
private TextView longitudeValue;
@@ -178,14 +180,16 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
speedMovingValue = view.findViewById(R.id.stats_moving_speed_value);
speedMovingUnit = view.findViewById(R.id.stats_moving_speed_unit);
elevationGroup = view.findViewById(R.id.stats_elevation_current_group);
speedLabel = view.findViewById(R.id.stats_speed_label);
speedValue = view.findViewById(R.id.stats_speed_value);
speedUnit = view.findViewById(R.id.stats_speed_unit);
elevationValue = view.findViewById(R.id.stats_elevation_current_value);
elevationUnit = view.findViewById(R.id.stats_elevation_current_unit);
elevationGroup = view.findViewById(R.id.stats_elevation_group);
elevationCurrentValue = view.findViewById(R.id.stats_elevation_current_value);
elevationCurrentUnit = view.findViewById(R.id.stats_elevation_current_unit);
elevationTotalGainValue = view.findViewById(R.id.stats_elevation_gain_value);
elevationTotalGainUnit = view.findViewById(R.id.stats_elevation_gain_unit);
coordinateGroup = view.findViewById(R.id.stats_coordinate_group);
@@ -197,7 +201,7 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recordingGpsAccuracy = Integer.parseInt(getContext().getResources().getString(R.string.recording_gps_accuracy_default));
recordingGpsAccuracy = Integer.parseInt(getResources().getString(R.string.recording_gps_accuracy_default));
handlerUpdateUI = new Handler();
@@ -276,14 +280,16 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
speedMovingValue = null;
speedMovingUnit = null;
elevationGroup = null;
speedLabel = null;
speedValue = null;
speedUnit = null;
elevationValue = null;
elevationUnit = null;
elevationGroup = null;
elevationCurrentValue = null;
elevationCurrentUnit = null;
elevationTotalGainValue = null;
elevationTotalGainUnit = null;
coordinateGroup = null;
@@ -406,20 +412,25 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
/**
* Tries to fetch most recent {@link SensorDataSet} from {@link de.dennisguse.opentracks.services.TrackRecordingService}.
* Also sets elevation gain.
*/
private void updateSensorDataUI() {
TrackRecordingServiceInterface trackRecordingService = trackRecordingServiceConnection.getServiceIfBound();
SensorDataSet sensorDataSet = null;
Float elevationGain_m = null;
if (trackRecordingService == null) {
Log.d(TAG, "Cannot get the track recording service.");
} else {
sensorDataSet = trackRecordingService.getSensorData();
elevationGain_m = trackRecordingService.getElevationGain_m();
}
setHeartRateSensorData(sensorDataSet);
setCadenceSensorData(sensorDataSet);
setSpeedSensorData(sensorDataSet, isSelectedTrackRecording());
setTotalElevationGain(elevationGain_m);
}
private void setHeartRateSensorData(SensorDataSet sensorDataSet) {
@@ -468,6 +479,26 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
cadenceValueView.setText(sensorValue);
}
// Set elevation gain
private void setTotalElevationGain(Float elevationGain_m) {
//TODO Check if we can distribute the total elevation gain via trackStatistics instead of doing some computation in the UI layer.
boolean metricUnits = PreferencesUtils.isMetricUnits(getContext());
Float totalElevationGain = elevationGain_m;
if (lastTrackStatistics != null && lastTrackStatistics.hasTotalElevationGain()) {
if (elevationGain_m == null) {
totalElevationGain = lastTrackStatistics.getTotalElevationGain();
} else {
totalElevationGain += lastTrackStatistics.getTotalElevationGain();
}
}
Pair<String, String> parts = StringUtils.formatElevation(getContext(), totalElevationGain, metricUnits);
elevationTotalGainValue.setText(parts.first);
elevationTotalGainUnit.setText(parts.second);
}
/**
* If cadence and hear rate groups are invisible then sensor horizontal line hast to be invisible too.
*/
@@ -475,7 +506,6 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
if (cadenceGroup.getVisibility() != View.VISIBLE && heartRateGroup.getVisibility() != View.VISIBLE) {
sensorHorizontalLine.setVisibility(View.GONE);
}
}
private void setSpeedSensorData(SensorDataSet sensorDataSet, boolean isRecording) {
@@ -555,8 +585,9 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
speedMovingUnit.setText(parts.second);
}
// Make elevation visible?
// Set elevation (gain)
{
// Make elevation visible?
boolean showElevation = PreferencesUtils.isShowStatsElevation(getContext());
elevationGroup.setVisibility(showElevation ? View.VISIBLE : View.GONE);
}
@@ -597,11 +628,11 @@ public class StatisticsRecordingFragment extends Fragment implements TrackDataLi
elevationGroup.setVisibility(showElevation ? View.VISIBLE : View.GONE);
if (showElevation) {
double altitude = lastTrackPoint != null && lastTrackPoint.hasAltitude() ? lastTrackPoint.getAltitude() : Double.NaN;
// Current elevation
Float altitude = lastTrackPoint != null && lastTrackPoint.hasAltitude() ? (float) lastTrackPoint.getAltitude() : null;
Pair<String, String> parts = StringUtils.formatElevation(getContext(), altitude, metricUnits);
elevationValue.setText(parts.first);
elevationUnit.setText(parts.second);
elevationCurrentValue.setText(parts.first);
elevationCurrentUnit.setText(parts.second);
}
// Set coordinate
@@ -0,0 +1,21 @@
package de.dennisguse.opentracks.io.file;
import androidx.documentfile.provider.DocumentFile;
import de.dennisguse.opentracks.content.data.Track;
public class ExportFile {
public static DocumentFile getExportDocumentFile(Track.Id trackId, String trackFileFormatExtension, DocumentFile directory, String mimeType) {
String fileName = getExportFileNameByTrackId(trackId, trackFileFormatExtension);
DocumentFile file = directory.findFile(fileName);
if (file == null) {
file = directory.createFile(mimeType, fileName);
}
return file;
}
private static String getExportFileNameByTrackId(Track.Id trackId, String trackFileFormatExtension) {
return trackId.getId() + "." + trackFileFormatExtension;
}
}
@@ -64,8 +64,8 @@ public class FileTrackExporter implements TrackExporter {
try {
trackWriter.prepare(outputStream);
trackWriter.writeHeader(tracks);
for (Track track1 : tracks) {
writeWaypoints(track1);
for (Track track : tracks) {
writeMarkers(track);
}
boolean hasMultipleTracks = tracks.length > 1;
if (hasMultipleTracks) {
@@ -89,34 +89,31 @@ public class FileTrackExporter implements TrackExporter {
}
}
/**
* Writes the waypoints.
*/
private void writeWaypoints(Track track) throws InterruptedException {
private void writeMarkers(Track track) throws InterruptedException {
/*
* TODO: Stream through the waypoints in chunks.
* I am leaving the number of waypoints very high which should not be a problem, because we don't try to load them into objects all at the same time.
* TODO: Stream through the markers in chunks.
* I am leaving the number of markers very high which should not be a problem, because we don't try to load them into objects all at the same time.
*/
boolean hasWaypoints = false;
boolean hasMarkers = false;
try (Cursor cursor = contentProviderUtils.getMarkerCursor(track.getId(), null, ContentProviderUtils.MAX_LOADED_MARKERS)) {
if (cursor != null && cursor.moveToFirst()) {
for (int i = 0; i < cursor.getCount(); i++) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
if (!hasWaypoints) {
trackWriter.writeBeginWaypoints(track);
hasWaypoints = true;
if (!hasMarkers) {
trackWriter.writeBeginMarkers(track);
hasMarkers = true;
}
Marker waypoint = contentProviderUtils.createMarker(cursor);
trackWriter.writeWaypoint(waypoint);
Marker marker = contentProviderUtils.createMarker(cursor);
trackWriter.writeMarker(marker);
cursor.moveToNext();
}
}
}
if (hasWaypoints) {
trackWriter.writeEndWaypoints();
if (hasMarkers) {
trackWriter.writeEndMarkers();
}
}
@@ -33,7 +33,7 @@ import de.dennisguse.opentracks.util.StringUtils;
*
* @author Sandor Dornbush
*/
//TODO Export waypoints
//TODO Export markers
public class GpxTrackWriter implements TrackWriter {
private static final NumberFormat ELEVATION_FORMAT = NumberFormat.getInstance(Locale.US);
@@ -120,27 +120,27 @@ public class GpxTrackWriter implements TrackWriter {
}
@Override
public void writeBeginWaypoints(Track track) {
public void writeBeginMarkers(Track track) {
// Do nothing
}
@Override
public void writeEndWaypoints() {
public void writeEndMarkers() {
// Do nothing
}
@Override
public void writeWaypoint(Marker waypoint) {
public void writeMarker(Marker marker) {
if (printWriter != null) {
Location location = waypoint.getLocation();
Location location = marker.getLocation();
printWriter.println("<wpt " + formatLocation(location) + ">");
if (location.hasAltitude()) {
printWriter.println("<ele>" + ELEVATION_FORMAT.format(location.getAltitude()) + "</ele>");
}
printWriter.println("<time>" + StringUtils.formatDateTimeIso8601(location.getTime()) + "</time>");
printWriter.println("<name>" + StringUtils.formatCData(waypoint.getName()) + "</name>");
printWriter.println("<desc>" + StringUtils.formatCData(waypoint.getDescription()) + "</desc>");
printWriter.println("<type>" + StringUtils.formatCData(waypoint.getCategory()) + "</type>");
printWriter.println("<name>" + StringUtils.formatCData(marker.getName()) + "</name>");
printWriter.println("<desc>" + StringUtils.formatCData(marker.getDescription()) + "</desc>");
printWriter.println("<type>" + StringUtils.formatCData(marker.getCategory()) + "</type>");
printWriter.println("</wpt>");
}
}
@@ -40,7 +40,7 @@ import de.dennisguse.opentracks.util.StringUtils;
*/
public class KmlTrackWriter implements TrackWriter {
public static final String WAYPOINT_STYLE = "waypoint";
public static final String MARKER_STYLE = "waypoint";
private static final String START_STYLE = "start";
private static final String END_STYLE = "end";
private static final String TRACK_STYLE = "track";
@@ -50,8 +50,9 @@ public class KmlTrackWriter implements TrackWriter {
public static final String EXTENDED_DATA_TYPE_CADENCE = "cadence";
public static final String EXTENDED_DATA_TYPE_HEART_RATE = "heart_rate";
public static final String EXTENDED_DATA_TYPE_POWER = "power";
public static final String EXTENDED_DATA_TYPE_ELEVATION_GAIN = "elevation_gain";
private static final String WAYPOINT_ICON = "http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png";
private static final String MARKER_ICON = "http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png";
private static final String START_ICON = "http://maps.google.com/mapfiles/kml/paddle/grn-circle.png";
private static final String END_ICON = "http://maps.google.com/mapfiles/kml/paddle/red-circle.png";
private static final String TRACK_ICON = "http://earth.google.com/images/kml-icons/track-directional/track-0.png";
@@ -68,12 +69,13 @@ public class KmlTrackWriter implements TrackWriter {
private final List<Float> powerList = new ArrayList<>();
private final List<Float> cadenceList = new ArrayList<>();
private final List<Float> heartRateList = new ArrayList<>();
private final List<Float> elevationGainList = new ArrayList<>();
private TrackPoint startTrackPoint;
/**
* @param context the context
* @param exportTrackDetail should detailed information about the track be exported (e.g., title, description, waypoints, timing)?
* @param exportTrackDetail should detailed information about the track be exported (e.g., title, description, markers, timing)?
* @param exportSensorData should {@link TrackPoint}'s sensor data be exported?
* @param exportPhotos should pictures be exported (if true: exports to KMZ)?
*/
@@ -122,7 +124,7 @@ public class KmlTrackWriter implements TrackWriter {
writeTrackStyle();
writePlacemarkerStyle(START_STYLE, START_ICON, 32, 1);
writePlacemarkerStyle(END_STYLE, END_ICON, 32, 1);
writePlacemarkerStyle(WAYPOINT_STYLE, WAYPOINT_ICON, 20, 2);
writePlacemarkerStyle(MARKER_STYLE, MARKER_ICON, 20, 2);
printWriter.println("<Schema id=\"" + SCHEMA_ID + "\">");
writeSimpleArrayStyle(EXTENDED_DATA_TYPE_SPEED, context.getString(R.string.description_speed_ms));
@@ -145,7 +147,7 @@ public class KmlTrackWriter implements TrackWriter {
}
@Override
public void writeBeginWaypoints(Track track) {
public void writeBeginMarkers(Track track) {
if (printWriter != null) {
printWriter.println("<Folder>");
if (exportTrackDetail) {
@@ -156,21 +158,21 @@ public class KmlTrackWriter implements TrackWriter {
}
@Override
public void writeEndWaypoints() {
public void writeEndMarkers() {
if (printWriter != null) {
printWriter.println("</Folder>");
}
}
@Override
public void writeWaypoint(Marker waypoint) {
public void writeMarker(Marker marker) {
if (printWriter != null && exportTrackDetail) {
boolean existsPhoto = FileUtils.getPhotoFileIfExists(context, waypoint.getTrackId(), waypoint.getPhotoURI()) != null;
if (waypoint.hasPhoto() && exportPhotos && existsPhoto) {
float heading = getHeading(waypoint.getTrackId(), waypoint.getLocation());
writePhotoOverlay(waypoint, heading);
boolean existsPhoto = FileUtils.getPhotoFileIfExists(context, marker.getTrackId(), marker.getPhotoURI()) != null;
if (marker.hasPhoto() && exportPhotos && existsPhoto) {
float heading = getHeading(marker.getTrackId(), marker.getLocation());
writePhotoOverlay(marker, heading);
} else {
writePlacemark(waypoint.getName(), waypoint.getCategory(), waypoint.getDescription(), WAYPOINT_STYLE, waypoint.getLocation());
writePlacemark(marker.getName(), marker.getCategory(), marker.getDescription(), MARKER_STYLE, marker.getLocation());
}
}
}
@@ -257,6 +259,9 @@ public class KmlTrackWriter implements TrackWriter {
if (heartRateList.size() > 0) {
writeSimpleArrayData(heartRateList, EXTENDED_DATA_TYPE_HEART_RATE);
}
if (elevationGainList.size() > 0) {
writeSimpleArrayData(elevationGainList, EXTENDED_DATA_TYPE_ELEVATION_GAIN);
}
}
printWriter.println("</SchemaData>");
printWriter.println("</ExtendedData>");
@@ -287,6 +292,9 @@ public class KmlTrackWriter implements TrackWriter {
if (trackPoint.hasPower()) {
powerList.add(trackPoint.getPower());
}
if (trackPoint.hasElevationGain()) {
elevationGainList.add(trackPoint.getElevationGain());
}
}
}
}
@@ -329,30 +337,24 @@ public class KmlTrackWriter implements TrackWriter {
}
}
/**
* Writes a photo overlay from waypoint.
*
* @param waypoint Waypoint object.
* @param heading the heading.
*/
private void writePhotoOverlay(Marker waypoint, float heading) {
private void writePhotoOverlay(Marker marker, float heading) {
if (exportTrackDetail) {
printWriter.println("<PhotoOverlay>");
printWriter.println("<name>" + StringUtils.formatCData(waypoint.getName()) + "</name>");
printWriter.println("<description>" + StringUtils.formatCData(waypoint.getDescription()) + "</description>");
printWriter.println("<name>" + StringUtils.formatCData(marker.getName()) + "</name>");
printWriter.println("<description>" + StringUtils.formatCData(marker.getDescription()) + "</description>");
printWriter.print("<Camera>");
printWriter.print("<longitude>" + waypoint.getLocation().getLongitude() + "</longitude>");
printWriter.print("<latitude>" + waypoint.getLocation().getLatitude() + "</latitude>");
printWriter.print("<longitude>" + marker.getLocation().getLongitude() + "</longitude>");
printWriter.print("<latitude>" + marker.getLocation().getLatitude() + "</latitude>");
printWriter.print("<altitude>20</altitude>");
printWriter.print("<heading>" + heading + "</heading>");
printWriter.print("<tilt>90</tilt>");
printWriter.println("</Camera>");
printWriter.println("<TimeStamp><when>" + getTime(waypoint.getLocation()) + "</when></TimeStamp>");
printWriter.println("<styleUrl>#" + KmlTrackWriter.WAYPOINT_STYLE + "</styleUrl>");
writeCategory(waypoint.getCategory());
printWriter.println("<TimeStamp><when>" + getTime(marker.getLocation()) + "</when></TimeStamp>");
printWriter.println("<styleUrl>#" + KmlTrackWriter.MARKER_STYLE + "</styleUrl>");
writeCategory(marker.getCategory());
if (exportPhotos) {
printWriter.println("<Icon><href>" + KmzTrackExporter.buildKmzImageFilePath(waypoint) + "</href></Icon>");
printWriter.println("<Icon><href>" + KmzTrackExporter.buildKmzImageFilePath(marker) + "</href></Icon>");
}
printWriter.print("<ViewVolume>");
@@ -363,7 +365,7 @@ public class KmlTrackWriter implements TrackWriter {
printWriter.print("<topFov>45</topFov>");
printWriter.println("</ViewVolume>");
printWriter.println("<Point>");
printWriter.println("<coordinates>" + getCoordinates(waypoint.getLocation(), ",") + "</coordinates>");
printWriter.println("<coordinates>" + getCoordinates(marker.getLocation(), ",") + "</coordinates>");
printWriter.println("</Point>");
printWriter.println("</PhotoOverlay>");
}
@@ -105,12 +105,12 @@ public class KmzTrackExporter implements TrackExporter {
if (Thread.interrupted()) {
throw new InterruptedException();
}
Marker waypoint = contentProviderUtils.createMarker(cursor);
if (waypoint.hasPhoto()) {
Uri uriPhoto = waypoint.getPhotoURI();
Marker marker = contentProviderUtils.createMarker(cursor);
if (marker.hasPhoto()) {
Uri uriPhoto = marker.getPhotoURI();
boolean existsPhoto = FileUtils.getPhotoFileIfExists(context, track.getId(), uriPhoto) != null;
if (existsPhoto) {
addImage(context, zipOutputStream, uriPhoto, waypoint);
addImage(context, zipOutputStream, uriPhoto, marker);
}
}
@@ -121,9 +121,9 @@ public class KmzTrackExporter implements TrackExporter {
}
}
private void addImage(Context context, ZipOutputStream zipOutputStream, Uri uri, Marker waypoint) throws IOException {
private void addImage(Context context, ZipOutputStream zipOutputStream, Uri uri, Marker marker) throws IOException {
try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
ZipEntry zipEntry = new ZipEntry(buildKmzImageFilePath(waypoint));
ZipEntry zipEntry = new ZipEntry(buildKmzImageFilePath(marker));
zipOutputStream.putNextEntry(zipEntry);
if (inputStream == null) throw new FileNotFoundException();
@@ -146,13 +146,11 @@ public class KmzTrackExporter implements TrackExporter {
}
/**
* Builds and returns the path for the image that will be saved inside KMZ_IMAGES_DIR for the waypoint.
*
* @param waypoint Waypoint object.
* Builds and returns the path for the image that will be saved inside KMZ_IMAGES_DIR for the marker.
*/
public static String buildKmzImageFilePath(Marker waypoint) {
String ext = FileUtils.getExtension(waypoint.getPhotoUrl());
public static String buildKmzImageFilePath(Marker marker) {
String ext = FileUtils.getExtension(marker.getPhotoUrl());
ext = ext == null ? "" : "." + ext;
return KMZ_IMAGES_DIR + File.separatorChar + FileUtils.sanitizeFileName(waypoint.getId() + ext);
return KMZ_IMAGES_DIR + File.separatorChar + FileUtils.sanitizeFileName(marker.getId().getId() + ext);
}
}
@@ -28,10 +28,10 @@ import de.dennisguse.opentracks.content.data.TrackPoint;
* {@link #prepare(OutputStream)}
* {@link #writeHeader(Track[])}
* For each track:
* {@link #writeBeginWaypoints(Track)}
* For each waypoint:
* {@link #writeWaypoint(Marker)}
* {@link #writeEndWaypoints()}
* {@link #writeBeginMarkers(Track)}
* For each marker:
* {@link #writeMarker(Marker)}
* {@link #writeEndMarkers()}
* {@link #writeMultiTrackBegin()}
* For each track:
* {@link #writeBeginTrack(Track, TrackPoint)}
@@ -50,11 +50,6 @@ import de.dennisguse.opentracks.content.data.TrackPoint;
*/
public interface TrackWriter {
/**
* Prepares the output stream.
*
* @param outputStream the output stream
*/
void prepare(OutputStream outputStream);
/**
@@ -62,77 +57,27 @@ public interface TrackWriter {
*/
void close();
/**
* Writes the header
*
* @param tracks the tracks
*/
void writeHeader(Track[] tracks);
/**
* Writes the footer.
*/
void writeFooter();
/**
* Writes the beginning of the waypoints.
*
* @param track the track
*/
void writeBeginWaypoints(Track track);
void writeBeginMarkers(Track track);
/**
* Writes the end of the waypoints.
*/
void writeEndWaypoints();
void writeEndMarkers();
/**
* Writes a waypoint.
*
* @param waypoint the waypoint
*/
void writeWaypoint(Marker waypoint);
void writeMarker(Marker marker);
/**
* Writes the beginning of the tracks.
*/
void writeMultiTrackBegin();
/**
* Writes the end of the tracks,
*/
void writeMultiTrackEnd();
/**
* Writes the beginning of a track.
*
* @param track the track
* @param startTrackPoint the start location
*/
void writeBeginTrack(Track track, TrackPoint startTrackPoint);
/**
* Writes the end of a track.
*
* @param track the track
* @param endTrackPoint the end location
*/
void writeEndTrack(Track track, TrackPoint endTrackPoint);
/**
* Writes open segment.
*/
void writeOpenSegment();
/**
* Writes close segment.
*/
void writeCloseSegment();
/**
* Writes a trackPoint.
*
* @param trackPoint the trackPoint
*/
void writeTrackPoint(TrackPoint trackPoint);
}
@@ -70,7 +70,7 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
private Track.Id importTrackId;
private final List<Track.Id> trackIds = new ArrayList<>();
private final List<Marker> waypoints = new ArrayList<>();
private final List<Marker> markers = new ArrayList<>();
// The current element content
//TODO Should be made private and getter be used by child classes.
@@ -88,7 +88,7 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
protected String heartrate;
protected String cadence;
protected String power;
protected String waypointType;
protected String markerType;
protected String photoUrl;
protected String uuid;
@@ -148,7 +148,7 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
* On file end.
*/
protected void onFileEnd() {
// Add waypoints to the last imported track
// Add markers to the last imported track
int size = trackIds.size();
if (size == 0) {
return;
@@ -159,8 +159,8 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
return;
}
int waypointPosition = -1;
Marker waypoint = null;
int markerPosition = -1;
Marker marker = null;
TrackPoint trackPoint = null;
TrackStatisticsUpdater trackStatisticsUpdater = new TrackStatisticsUpdater(track.getTrackStatistics().getStartTime_ms());
// TODO Should not be necessary anymore?
@@ -169,18 +169,18 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
try (TrackPointIterator trackPointIterator = contentProviderUtils.getTrackPointLocationIterator(track.getId(), -1L, false)) {
while (true) {
if (waypoint == null) {
waypointPosition++;
waypoint = waypointPosition < waypoints.size() ? waypoints.get(waypointPosition) : null;
if (waypoint == null) {
// No more waypoints
if (marker == null) {
markerPosition++;
marker = markerPosition < markers.size() ? markers.get(markerPosition) : null;
if (marker == null) {
// No more markers
return;
}
}
if (trackPoint == null) {
if (!trackPointIterator.hasNext()) {
// No more track points. Ignore the rest of the waypoints.
// No more track points. Ignore the rest of the markers.
return;
}
trackPoint = trackPointIterator.next();
@@ -188,13 +188,13 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
markerTrackStatisticsUpdater.addTrackPoint(trackPoint, recordingDistanceInterval);
}
if (waypoint.getLocation().getTime() > trackPoint.getTime()) {
if (marker.getLocation().getTime() > trackPoint.getTime()) {
trackPoint = null;
} else if (waypoint.getLocation().getTime() < trackPoint.getTime()) {
Log.w(TAG, "Ignoring waypoint: current trackPoint was after waypoint.");
waypoint = null;
} else if (marker.getLocation().getTime() < trackPoint.getTime()) {
Log.w(TAG, "Ignoring marker: current trackPoint was after marker.");
marker = null;
} else {
// The waypoint trackPoint time matches the track point time
// The marker trackPoint time matches the track point time
if (!LocationUtils.isValidLocation(trackPoint.getLocation())) {
// Invalid trackPoint, load the next trackPoint
trackPoint = null;
@@ -202,19 +202,19 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
}
// Valid trackPoint
if (trackPoint.getLatitude() == waypoint.getLocation().getLatitude() && trackPoint.getLongitude() == waypoint.getLocation().getLongitude()) {
String waypointDescription = waypoint.getDescription();
String icon = context.getString(R.string.marker_waypoint_icon_url);
if (trackPoint.getLatitude() == marker.getLocation().getLatitude() && trackPoint.getLongitude() == marker.getLocation().getLongitude()) {
String markerDescription = marker.getDescription();
String icon = context.getString(R.string.marker_icon_url);
double length = trackStatisticsUpdater.getTrackStatistics().getTotalDistance();
long duration = trackStatisticsUpdater.getTrackStatistics().getTotalTime();
// Insert waypoint
Marker newWaypoint = new Marker(waypoint.getName(), waypointDescription, waypoint.getCategory(), icon, track.getId(), length, duration, trackPoint.getLocation(), waypoint.getPhotoUrl());
contentProviderUtils.insertMarker(newWaypoint);
// Insert marker
Marker newMarker = new Marker(marker.getName(), markerDescription, marker.getCategory(), icon, track.getId(), length, duration, trackPoint.getLocation(), marker.getPhotoUrl());
contentProviderUtils.insertMarker(newMarker);
}
// Load the next waypoint
waypoint = null;
// Load the next marker
marker = null;
}
}
}
@@ -231,7 +231,7 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
trackId = new Track.Id(Long.parseLong(uri.getLastPathSegment()));
} else {
if (trackIds.size() > 0) {
throw new SAXException(createErrorMessage("Cannot import more than one track to an existing track " + importTrackId));
throw new SAXException(createErrorMessage("Cannot import more than one track to an existing track " + importTrackId.getId()));
}
trackId = importTrackId;
contentProviderUtils.clearTrack(trackId);
@@ -300,11 +300,8 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
trackData.lastLocationInCurrentSegment = null;
}
/**
* Adds a waypoint.
*/
protected void addWaypoint() throws SAXException {
// Waypoint must have a time, else cannot match to the track points
protected void addMarker() throws SAXException {
// Markers must have a time, else cannot match to the track points
if (time == null) {
return;
}
@@ -314,22 +311,22 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
if (!LocationUtils.isValidLocation(trackPoint.getLocation())) {
throw new SAXException(createErrorMessage("Invalid location detected: " + trackPoint));
}
Marker waypoint = new Marker(trackPoint.getLocation());
Marker marker = new Marker(trackPoint.getLocation());
if (name != null) {
waypoint.setName(name);
marker.setName(name);
}
if (description != null) {
waypoint.setDescription(description);
marker.setDescription(description);
}
if (category != null) {
waypoint.setCategory(category);
marker.setCategory(category);
}
if (photoUrl != null) {
waypoint.setPhotoUrl(photoUrl);
marker.setPhotoUrl(photoUrl);
}
waypoints.add(waypoint);
markers.add(marker);
}
/**
@@ -21,7 +21,7 @@ public abstract class DirectoryChooserActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
configureDirectoryChooserIntent(intent);
startActivityForResult(intent, DIRECTORY_PICKER_REQUEST_CODE);
}
@@ -33,19 +33,23 @@ public abstract class DirectoryChooserActivity extends AppCompatActivity {
if (resultCode == Activity.RESULT_OK) {
Uri directoryUri = resultData.getData();
startActivity(createIntent(directoryUri));
startActivity(createNextActivityIntent(directoryUri));
}
finish();
}
}
protected abstract Intent createIntent(Uri directoryUri);
protected void configureDirectoryChooserIntent(Intent intent) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
protected abstract Intent createNextActivityIntent(Uri directoryUri);
public static class ImportDirectoryChooserActivity extends DirectoryChooserActivity {
@Override
protected Intent createIntent(Uri directoryUri) {
protected Intent createNextActivityIntent(Uri directoryUri) {
Intent intent = IntentUtils.newIntent(this, ImportActivity.class);
intent.putExtra(ImportActivity.EXTRA_DIRECTORY_URI_KEY, directoryUri);
return intent;
@@ -55,11 +59,17 @@ public abstract class DirectoryChooserActivity extends AppCompatActivity {
public static class ExportDirectoryChooserActivity extends DirectoryChooserActivity {
@Override
protected Intent createIntent(Uri directoryUri) {
protected Intent createNextActivityIntent(Uri directoryUri) {
Intent intent = IntentUtils.newIntent(this, ExportActivity.class);
intent.putExtra(ExportActivity.EXTRA_DIRECTORY_URI_KEY, directoryUri);
intent.putExtra(ExportActivity.EXTRA_TRACKFILEFORMAT_KEY, PreferencesUtils.getExportTrackFileFormat(this));
return intent;
}
@Override
protected void configureDirectoryChooserIntent(Intent intent) {
super.configureDirectoryChooserIntent(intent);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
}
}
@@ -44,7 +44,7 @@ public class GpxFileTrackImporter extends AbstractFileTrackImporter {
private static final String TAG_TRACK_POINT = "trkpt";
private static final String TAG_TRACK_SEGMENT = "trkseg";
private static final String TAG_TYPE = "type";
private static final String TAG_WAYPOINT = "wpt";
private static final String TAG_MARKER = "wpt";
private static final String TAG_ID = "opentracks:trackid";
private static final String ATTRIBUTE_LAT = "lat";
@@ -71,8 +71,8 @@ public class GpxFileTrackImporter extends AbstractFileTrackImporter {
@Override
public void startElement(String uri, String localName, String tag, Attributes attributes) throws SAXException {
switch (tag) {
case TAG_WAYPOINT:
onWaypointStart(attributes);
case TAG_MARKER:
onMarkerStart(attributes);
break;
case TAG_TRACK:
onTrackStart();
@@ -92,8 +92,8 @@ public class GpxFileTrackImporter extends AbstractFileTrackImporter {
case TAG_GPX:
onFileEnd();
break;
case TAG_WAYPOINT:
onWaypointEnd();
case TAG_MARKER:
onMarkerEnd();
break;
case TAG_TRACK:
onTrackEnd();
@@ -128,7 +128,7 @@ public class GpxFileTrackImporter extends AbstractFileTrackImporter {
break;
case TAG_COMMENT:
if (content != null) {
waypointType = content.trim();
markerType = content.trim();
}
break;
case TAG_EXTENSION_SPEED:
@@ -187,12 +187,7 @@ public class GpxFileTrackImporter extends AbstractFileTrackImporter {
insertTrackPoint(trackPoint);
}
/**
* On waypoint start.
*
* @param attributes the attributes
*/
private void onWaypointStart(Attributes attributes) {
private void onMarkerStart(Attributes attributes) {
name = null;
description = null;
category = null;
@@ -201,13 +196,10 @@ public class GpxFileTrackImporter extends AbstractFileTrackImporter {
longitude = attributes.getValue(ATTRIBUTE_LON);
altitude = null;
time = null;
waypointType = null;
markerType = null;
}
/**
* On waypoint end.
*/
private void onWaypointEnd() throws SAXException {
addWaypoint();
private void onMarkerEnd() throws SAXException {
addMarker();
}
}
@@ -39,7 +39,7 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
private static final String TAG = KmlFileTrackImporter.class.getSimpleName();
private static final String WAYPOINT_STYLE = "#" + KmlTrackWriter.WAYPOINT_STYLE;
private static final String MARKER_STYLE = "#" + KmlTrackWriter.MARKER_STYLE;
private static final String TAG_COORDINATES = "coordinates";
private static final String TAG_DESCRIPTION = "description";
@@ -63,11 +63,12 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
private boolean trackStarted = false;
private String extendedDataType;
private ArrayList<TrackPoint> trackPoints;
private ArrayList<Float> speedList;
private ArrayList<Float> cadenceList;
private ArrayList<Float> heartRateList;
private ArrayList<Float> powerList;
private ArrayList<TrackPoint> trackPoints = new ArrayList<>();
private ArrayList<Float> speedList = new ArrayList<>();
private ArrayList<Float> cadenceList = new ArrayList<>();
private ArrayList<Float> heartRateList = new ArrayList<>();
private ArrayList<Float> powerList = new ArrayList<>();
private ArrayList<Float> elevationGainList = new ArrayList<>();
public KmlFileTrackImporter(Context context) {
this(context, new ContentProviderUtils(context));
@@ -83,8 +84,8 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
switch (tag) {
case TAG_PLACEMARK:
case TAG_PHOTO_OVERLAY:
// Note that a track is contained in a Placemark, calling onWaypointStart will clear various track variables like name, category, and description.
onWaypointStart();
// Note that a track is contained in a Placemark, calling onMarkerStart will clear various track variables like name, category, and description.
onMarkerStart();
break;
case TAG_GX_MULTI_TRACK:
trackStarted = true;
@@ -110,11 +111,11 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
break;
case TAG_PLACEMARK:
case TAG_PHOTO_OVERLAY:
// Note that a track is contained in a Placemark, calling onWaypointend is save since waypointType is not set for a track.
onWaypointEnd();
// Note that a track is contained in a Placemark, calling onMarkerEnd is save since markerType is not set for a track.
onMarkerEnd();
break;
case TAG_COORDINATES:
onWaypointLocationEnd();
onMarkerLocationEnd();
break;
case TAG_GX_MULTI_TRACK:
onTrackEnd();
@@ -160,7 +161,7 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
break;
case TAG_STYLE_URL:
if (content != null) {
waypointType = content.trim();
markerType = content.trim();
}
break;
case TAG_HREF:
@@ -174,10 +175,7 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
content = null;
}
/**
* On waypoint start.
*/
private void onWaypointStart() {
private void onMarkerStart() {
// Reset all Placemark variables
name = null;
icon = null;
@@ -188,27 +186,21 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
longitude = null;
altitude = null;
time = null;
waypointType = null;
markerType = null;
}
/**
* On waypoint end.
*/
private void onWaypointEnd() throws SAXException {
if (!WAYPOINT_STYLE.equals(waypointType)) {
private void onMarkerEnd() throws SAXException {
if (!MARKER_STYLE.equals(markerType)) {
return;
}
// If there is photoUrl it has to be changed because that url in kml file is a relative path to the internal kmz file.
photoUrl = getInternalPhotoUrl(photoUrl);
addWaypoint();
addMarker();
}
/**
* On waypoint location end.
*/
private void onWaypointLocationEnd() {
private void onMarkerLocationEnd() {
if (content != null) {
String[] parts = content.trim().split(",");
if (parts.length != 2 && parts.length != 3) {
@@ -223,11 +215,12 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
@Override
protected void onTrackSegmentStart() {
super.onTrackSegmentStart();
trackPoints = new ArrayList<>();
speedList = new ArrayList<>();
heartRateList = new ArrayList<>();
cadenceList = new ArrayList<>();
powerList = new ArrayList<>();
trackPoints.clear();
speedList.clear();
heartRateList.clear();
cadenceList.clear();
powerList.clear();
elevationGainList.clear();
}
/**
@@ -250,6 +243,9 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
if (i < powerList.size()) {
trackPoint.setPower(powerList.get(i));
}
if (i < elevationGainList.size()) {
trackPoint.setElevationGain(elevationGainList.get(i));
}
insertTrackPoint(trackPoint);
}
@@ -316,6 +312,9 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
case KmlTrackWriter.EXTENDED_DATA_TYPE_CADENCE:
cadenceList.add(value);
break;
case KmlTrackWriter.EXTENDED_DATA_TYPE_ELEVATION_GAIN:
elevationGainList.add(value);
break;
default:
Log.w(TAG, "Data from extended data " + extendedDataType + " is not (yet) supported.");
}
@@ -191,20 +191,20 @@ public class KmzTrackImporter implements TrackImporter {
}
/**
* Deletes all images that remained in external storage that doesn't have waypoint (marker) associated.
* Deletes all images that remained in external storage that doesn't have a marker associated.
*
* @param context the Context object.
* @param trackId the id of the Track.
*/
private void deleteOrphanImages(Context context, Track.Id trackId) {
if (!trackId.isValid()) {
// 1.- Gets all photo names in the waypoints of the track identified by id.
// 1.- Gets all photo names in the markers of the track identified by id.
ContentProviderUtils contentProviderUtils = new ContentProviderUtils(context);
List<Marker> waypoints = contentProviderUtils.getMarkers(trackId);
List<Marker> markers = contentProviderUtils.getMarkers(trackId);
List<String> photosName = new ArrayList<>();
for (Marker w : waypoints) {
if (w.hasPhoto()) {
String photoUrl = Uri.decode(w.getPhotoUrl());
for (Marker marker : markers) {
if (marker.hasPhoto()) {
String photoUrl = Uri.decode(marker.getPhotoUrl());
photosName.add(photoUrl.substring(photoUrl.lastIndexOf(File.separatorChar) + 1));
}
}
@@ -49,6 +49,7 @@ import de.dennisguse.opentracks.content.sensor.SensorDataSet;
import de.dennisguse.opentracks.services.handlers.GpsStatusValue;
import de.dennisguse.opentracks.services.handlers.HandlerServer;
import de.dennisguse.opentracks.services.sensors.BluetoothRemoteSensorManager;
import de.dennisguse.opentracks.services.sensors.ElevationSumManager;
import de.dennisguse.opentracks.services.tasks.AnnouncementPeriodicTaskFactory;
import de.dennisguse.opentracks.services.tasks.PeriodicTaskExecutor;
import de.dennisguse.opentracks.stats.TrackStatistics;
@@ -115,6 +116,7 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
// The following variables are set when recording:
private WakeLock wakeLock;
private BluetoothRemoteSensorManager remoteSensorManager;
private ElevationSumManager elevationSumManager;
private TrackStatisticsUpdater trackStatisticsUpdater;
private TrackPoint lastTrackPoint;
@@ -174,6 +176,11 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
remoteSensorManager = null;
}
if (elevationSumManager != null) {
elevationSumManager.stop(this);
elevationSumManager = null;
}
// Reverse order from onCreate
showNotification(false); //TODO Why?
@@ -247,7 +254,7 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
category = category != null ? category : "";
description = description != null ? description : "";
String icon = getString(R.string.marker_waypoint_icon_url);
String icon = getString(R.string.marker_icon_url);
photoUrl = photoUrl != null ? photoUrl : "";
TrackStatistics stats = trackStatisticsUpdater.getTrackStatistics();
@@ -304,7 +311,7 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
void resumeTrack(Track.Id trackId) {
Track track = contentProviderUtils.getTrack(trackId);
if (track == null) {
Log.e(TAG, "Ignore resumeTrack. Track " + trackId + " does not exists.");
Log.e(TAG, "Ignore resumeTrack. Track " + trackId.getId() + " does not exists.");
return;
}
@@ -328,7 +335,7 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
Track track = contentProviderUtils.getTrack(recordingTrackId);
if (track == null) {
if (isRecording()) {
Log.w(TAG, "track is null, but recordingTrackId not -1L. " + recordingTrackId);
Log.w(TAG, "track is null, but recordingTrackId not -1L. " + recordingTrackId.getId());
updateRecordingState(null, true);
}
showNotification(false);
@@ -371,6 +378,10 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
// Update instance variables
remoteSensorManager = new BluetoothRemoteSensorManager(this);
remoteSensorManager.start();
elevationSumManager = new ElevationSumManager();
elevationSumManager.start(this);
lastTrackPoint = null;
isIdle = false;
@@ -456,6 +467,11 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
remoteSensorManager.stop();
remoteSensorManager = null;
}
if (elevationSumManager != null) {
elevationSumManager.stop(this);
elevationSumManager = null;
}
lastTrackPoint = null;
handlerServer.stop(this);
@@ -556,15 +572,17 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
insertTrackPoint(track, TrackPoint.createPause());
insertTrackPoint(track, trackPoint);
isIdle = false;
isIdle = false;
lastTrackPoint = trackPoint;
return;
}
if (trackPoint.hasSensorData() || distanceToLastTrackLocation >= recordingDistanceInterval) {
insertTrackPointIfNewer(track, lastTrackPoint);
insertTrackPoint(track, trackPoint);
isIdle = false;
lastTrackPoint = trackPoint;
@@ -573,7 +591,9 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
if (!isIdle && !TrackPointUtils.isMoving(trackPoint)) {
insertTrackPointIfNewer(track, lastTrackPoint);
insertTrackPoint(track, trackPoint);
isIdle = true;
lastTrackPoint = trackPoint;
@@ -582,7 +602,9 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
if (isIdle && TrackPointUtils.isMoving(trackPoint)) {
insertTrackPointIfNewer(track, lastTrackPoint);
insertTrackPoint(track, trackPoint);
isIdle = false;
lastTrackPoint = trackPoint;
@@ -632,6 +654,10 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
*/
private void insertTrackPoint(@NonNull Track track, @NonNull TrackPoint trackPoint) {
try {
if (elevationSumManager != null) {
trackPoint.setElevationGain(elevationSumManager.getElevationGain_m());
elevationSumManager.reset();
}
contentProviderUtils.insertTrackPoint(trackPoint, track.getId());
trackStatisticsUpdater.addTrackPoint(trackPoint, recordingDistanceInterval);
updateTrackTotalTime(track);
@@ -672,6 +698,17 @@ public class TrackRecordingService extends Service implements HandlerServer.Hand
}
}
/**
* Returns the relative elevation gain (since last trackpoint).
*/
Float getElevationGain_m() {
if (elevationSumManager == null || !elevationSumManager.isConnected()) {
return null;
}
return elevationSumManager.getElevationGain_m();
}
private void showNotification(boolean isGpsStarted) {
if (isRecording()) {
Intent intent = IntentUtils.newIntent(this, TrackRecordingActivity.class)
@@ -99,6 +99,11 @@ class TrackRecordingServiceBinder extends android.os.Binder implements TrackReco
return trackRecordingService.getSensorDataSet();
}
@Override
public Float getElevationGain_m() {
return trackRecordingService.getElevationGain_m();
}
@VisibleForTesting
@Override
public void setRemoteSensorManager(BluetoothRemoteSensorManager remoteSensorManager) {
@@ -65,12 +65,19 @@ public interface TrackRecordingServiceInterface {
Marker.Id insertMarker(String name, String category, String description, String photoUrl);
/**
* Gets the current sensor data. Returns null if there is no data.
* Gets the current sensor data.
*
* @return SensorDataSet object.
* @return SensorDataSet object or null.
*/
SensorDataSet getSensorData();
/**
* Gets the current elevation gain.
*
* @return elevation gain in m or null.
*/
Float getElevationGain_m();
@VisibleForTesting
void setRemoteSensorManager(BluetoothRemoteSensorManager remoteSensorManager);
@@ -102,7 +102,7 @@ class GpsStatus {
* It look for GPS changes in lastLocation if it's not null. If it's null then look for in lastValidLocation if any.
*/
public void onLocationChanged(final Location location) {
if (checking == true) {
if (checking) {
return;
}
@@ -0,0 +1,117 @@
package de.dennisguse.opentracks.services.sensors;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import de.dennisguse.opentracks.util.PressureSensorUtils;
import de.dennisguse.opentracks.util.UnitConversions;
/**
* Estimates the elevation gain and elevation loss using the device's pressure sensor (i.e., barometer).
*/
public class ElevationSumManager implements SensorEventListener {
private static final String TAG = ElevationSumManager.class.getSimpleName();
private static final int SAMPLING_RATE = 3 * (int) UnitConversions.ONE_SECOND_US;
private boolean isConnected = false;
private float lastAcceptedPressureValue_hPa;
private float lastSeenSensorValue_hPa;
private float elevationGain_m;
private float elevationLoss_m;
public void start(Context context) {
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if (pressureSensor == null) {
Log.w(TAG, "No pressure sensor available.");
isConnected = false;
} else {
isConnected = sensorManager.registerListener(this, pressureSensor, SAMPLING_RATE);
}
lastAcceptedPressureValue_hPa = Float.NaN;
reset();
}
public void stop(Context context) {
Log.d(TAG, "Stop");
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensorManager.unregisterListener(this);
isConnected = false;
reset();
}
public boolean isConnected() {
return isConnected;
}
@VisibleForTesting
public void setConnected(boolean isConnected) {
this.isConnected = isConnected;
}
public @Nullable
Float getElevationGain_m() {
return isConnected ? elevationGain_m : null;
}
public @Nullable
Float getElevationLoss_m() {
return isConnected ? elevationLoss_m : null;
}
public void reset() {
Log.d(TAG, "Reset");
elevationGain_m = 0;
elevationLoss_m = 0;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.w(TAG, "Sensor accuracy changes are (currently) ignored.");
}
@Override
public void onSensorChanged(SensorEvent event) {
if (!isConnected) {
Log.w(TAG, "Not connected to sensor, cannot process data.");
return;
}
onSensorValueChanged(event.values[0]);
}
@VisibleForTesting
void onSensorValueChanged(float value_hPa) {
if (Float.isNaN(lastAcceptedPressureValue_hPa)) {
lastAcceptedPressureValue_hPa = value_hPa;
lastSeenSensorValue_hPa = value_hPa;
return;
}
PressureSensorUtils.ElevationChange elevationChange = PressureSensorUtils.computeChangesWithSmoothing_m(lastAcceptedPressureValue_hPa, lastSeenSensorValue_hPa, value_hPa);
if (elevationChange != null) {
elevationGain_m += elevationChange.getElevationGain_m();
elevationLoss_m += elevationChange.getElevationLoss_m();
lastAcceptedPressureValue_hPa = elevationChange.getCurrentSensorValue_hPa();
}
lastSeenSensorValue_hPa = value_hPa;
Log.v(TAG, "elevation gain: " + elevationGain_m);
}
}
@@ -169,9 +169,8 @@ public class AnnouncementPeriodicTask implements PeriodicTask {
List<TrackPoint> trackPoints = contentProviderUtils.getTrackPoints(track.getId());
IntervalStatistics intervalStatistics = new IntervalStatistics();
intervalStatistics.build(trackPoints, (float) (PreferencesUtils.isMetricUnits(context) ? 1 * UnitConversions.KM_TO_M : 1 * UnitConversions.MI_TO_M));
int numIntervals = intervalStatistics.getIntervalList().size();
IntervalStatistics.Interval lastInterval = numIntervals > 0 ? intervalStatistics.getIntervalList().get(numIntervals - 1) : null;
intervalStatistics.build(trackPoints, (float) (PreferencesUtils.isMetricUnits(context) ? 1d * UnitConversions.KM_TO_M : 1d * UnitConversions.MI_TO_M));
IntervalStatistics.Interval lastInterval = intervalStatistics.getLastInterval();
String announcement = AnnouncementUtils.getAnnouncement(context, trackStatistics, category, lastInterval);
speakAnnouncement(announcement);
@@ -21,6 +21,7 @@ import de.dennisguse.opentracks.io.file.TrackFileFormat;
import de.dennisguse.opentracks.settings.bluetooth.BluetoothLeCyclingCadenceAndSpeedPreference;
import de.dennisguse.opentracks.settings.bluetooth.BluetoothLeHeartRatePreference;
import de.dennisguse.opentracks.settings.bluetooth.BluetoothLeSensorPreference;
import de.dennisguse.opentracks.util.ActivityUtils;
import de.dennisguse.opentracks.util.BluetoothUtils;
import de.dennisguse.opentracks.util.HackUtils;
import de.dennisguse.opentracks.util.PreferencesUtils;
@@ -65,6 +66,9 @@ public class SettingsActivity extends AppCompatActivity implements ChooseActivit
if (PreferencesUtils.isKey(getActivity(), R.string.stats_units_key, key)) {
getActivity().runOnUiThread(this::updateUnits);
}
if (PreferencesUtils.isKey(getActivity(), R.string.night_mode_key, key)) {
getActivity().runOnUiThread(() -> ActivityUtils.applyNightMode(getContext()));
}
};
// Used to forward update from ChooseActivityTypeDialogFragment; TODO Could be replaced with LiveData.
@@ -19,13 +19,13 @@ package de.dennisguse.opentracks.stats;
import androidx.annotation.NonNull;
/**
* This class maintains a buffer of doubles.
* This class maintains a ring buffer of doubles.
* This buffer is a convenient class for storing a series of doubles and calculating information about them.
* This is a FIFO buffer.
*
* @author Sandor Dornbush
*/
class DoubleBuffer {
class DoubleRingBuffer {
// The sliding buffer of doubles.
private final double[] buffer;
@@ -41,7 +41,7 @@ class DoubleBuffer {
*
* @param size the size
*/
DoubleBuffer(int size) {
DoubleRingBuffer(int size) {
if (size < 1) {
throw new IllegalArgumentException("The buffer size must be greater than 1.");
}
@@ -17,6 +17,7 @@
package de.dennisguse.opentracks.stats;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* Statistical data about a {@link de.dennisguse.opentracks.content.data.Track}.
@@ -24,6 +25,7 @@ import androidx.annotation.NonNull;
*
* @author Rodrigo Damazio
*/
//TODO Use null instead of Double.isInfinite
public class TrackStatistics {
// The min and max elevation (meters) seen on this track.
@@ -42,7 +44,7 @@ public class TrackStatistics {
// The maximum speed (meters/second) that we believe is valid.
private double maxSpeed_mps;
// The total elevation gained (meters).
private double totalElevationGain_m;
private Float totalElevationGain_m = null;
public TrackStatistics() {
}
@@ -80,7 +82,15 @@ public class TrackStatistics {
elevationExtremities.update(other.elevationExtremities.getMin());
elevationExtremities.update(other.elevationExtremities.getMax());
}
totalElevationGain_m += other.totalElevationGain_m;
if (totalElevationGain_m == null) {
if (other.totalElevationGain_m != null) {
totalElevationGain_m = other.totalElevationGain_m;
}
} else {
if (other.totalElevationGain_m != null) {
totalElevationGain_m += other.totalElevationGain_m;
}
}
}
/**
@@ -227,18 +237,23 @@ public class TrackStatistics {
elevationExtremities.update(elevation_m);
}
/**
* Gets the total elevation gain in meters. This is calculated as the sum of all positive differences in the smoothed elevation.
*/
public double getTotalElevationGain() {
public boolean hasTotalElevationGain() {
return totalElevationGain_m != null;
}
public @Nullable
Float getTotalElevationGain() {
return totalElevationGain_m;
}
public void setTotalElevationGain(double totalElevationGain_m) {
public void setTotalElevationGain(float totalElevationGain_m) {
this.totalElevationGain_m = totalElevationGain_m;
}
public void addTotalElevationGain(double gain_m) {
public void addTotalElevationGain(float gain_m) {
if (totalElevationGain_m == null) {
totalElevationGain_m = 0f;
}
totalElevationGain_m += gain_m;
}
@@ -62,9 +62,9 @@ public class TrackStatisticsUpdater {
private final TrackStatistics trackStatistics;
// A buffer of the recent elevation readings (m)
private final DoubleBuffer elevationBuffer_m = new DoubleBuffer(ELEVATION_SMOOTHING_FACTOR);
private final DoubleRingBuffer elevationBuffer_m = new DoubleRingBuffer(ELEVATION_SMOOTHING_FACTOR);
// A buffer of the recent speed readings (m/s) for calculating max speed
private final DoubleBuffer speedBuffer_ms = new DoubleBuffer(SPEED_SMOOTHING_FACTOR);
private final DoubleRingBuffer speedBuffer_ms = new DoubleRingBuffer(SPEED_SMOOTHING_FACTOR);
// The current segment's statistics
private TrackStatistics currentSegment;
@@ -112,7 +112,7 @@ public class TrackStatisticsUpdater {
* Adds a trackPoint.
* TODO: This assume trackPoint has a valid time.
*
* @param trackPoint the trackPoint
* @param trackPoint the trackPoint
* @param minRecordingDistance the min recording distance
*/
public void addTrackPoint(TrackPoint trackPoint, int minRecordingDistance) {
@@ -134,8 +134,16 @@ public class TrackStatisticsUpdater {
return;
}
//TODO Use Barometer to compute elevation gain.
double elevationDifference = trackPoint.hasAltitude() ? updateElevation(trackPoint.getAltitude()) : 0.0;
//Update absolute (GPS-based) elevation
if (trackPoint.hasAltitude()) {
updateAbsoluteElevation(trackPoint.getAltitude());
}
//Get elevation gain
if (trackPoint.hasElevationGain()) {
currentSegment.addTotalElevationGain(trackPoint.getElevationGain());
Log.d(TAG, "elevation gain: " + trackPoint.getElevationGain());
}
if (lastTrackPoint == null || lastMovingTrackPoint == null) {
lastTrackPoint = trackPoint;
@@ -207,23 +215,21 @@ public class TrackStatisticsUpdater {
}
/**
* Updates an elevation reading. Returns the difference.
* Updates an elevation reading.
*
* @param elevation the elevation
* @return the difference
*/
@VisibleForTesting
private double updateElevation(double elevation) {
private double updateAbsoluteElevation(double elevation) {
// Update elevation using the smoothed average
double oldAverage = elevationBuffer_m.getAverage();
elevationBuffer_m.setNext(elevation);
double newAverage = elevationBuffer_m.getAverage();
currentSegment.updateElevationExtremities(newAverage);
double difference = newAverage - oldAverage;
if (difference > 0) {
currentSegment.addTotalElevationGain(difference);
}
return difference;
return newAverage - oldAverage;
}
private TrackStatistics init(long time) {
@@ -16,6 +16,7 @@ import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SearchView;
import java.util.ArrayList;
@@ -151,4 +152,7 @@ public class ActivityUtils {
toast.show();
}
public static void applyNightMode(Context context) {
AppCompatDelegate.setDefaultNightMode(PreferencesUtils.getDefaultNightMode(context));
}
}
@@ -31,13 +31,13 @@ public class AnnouncementUtils {
String rate;
String currentRate;
String currentRateMsg = "";
String currentRateMsg;
if (reportSpeed) {
int speedId = metricUnits ? R.plurals.voiceSpeedKilometersPerHour : R.plurals.voiceSpeedMilesPerHour;
rate = context.getResources().getQuantityString(speedId, getQuantityCount(distancePerTime), distancePerTime);
currentRate = context.getResources().getQuantityString(speedId, getQuantityCount(currentDistancePerTime), currentDistancePerTime);
currentRateMsg = metricUnits ? context.getString(R.string.voice_speed_current_kilometer, currentRate) : context.getString(R.string.voice_speed_current_mile, currentRate);
currentRateMsg = context.getString(R.string.voice_speed_lap, currentRate);
} else {
double timePerDistance = distancePerTime == 0 ? 0.0 : 1 / distancePerTime;
int paceId = metricUnits ? R.string.voice_pace_per_kilometer : R.string.voice_pace_per_mile;
@@ -47,7 +47,7 @@ public class AnnouncementUtils {
double currentTimePerDistance = currentDistancePerTime == 0 ? 0.0 : 1 / currentDistancePerTime;
long currentTime = Math.round(currentTimePerDistance * UnitConversions.HR_TO_MIN * UnitConversions.MIN_TO_S * UnitConversions.S_TO_MS);
currentRate = context.getString(paceId, getAnnounceTime(context, currentTime));
currentRateMsg = metricUnits ? context.getString(R.string.voice_pace_current_kilometer, currentRate) : context.getString(R.string.voice_pace_current_mile, currentRate);
currentRateMsg = context.getString(R.string.voice_pace_lap, currentRate);
}
int totalDistanceId = metricUnits ? R.plurals.voiceTotalDistanceKilometers : R.plurals.voiceTotalDistanceMiles;
@@ -16,12 +16,13 @@
package de.dennisguse.opentracks.util;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import androidx.appcompat.app.AlertDialog;
import de.dennisguse.opentracks.R;
/**
@@ -45,7 +46,7 @@ public class DialogUtils {
public static Dialog createConfirmationDialog(final Context context, int titleId, String message, DialogInterface.OnClickListener okListener) {
return new AlertDialog.Builder(context)
.setCancelable(true)
.setIcon(android.R.drawable.ic_dialog_alert)
.setIcon(R.drawable.ic_delete_forever_24dp)
.setMessage(message)
.setNegativeButton(R.string.generic_no, null)
.setPositiveButton(R.string.generic_yes, okListener)
@@ -34,7 +34,7 @@ public class IntentDashboardUtils {
private static final int TRACK_URI_INDEX = 0;
private static final int TRACKPOINTS_URI_INDEX = 1;
private static final int WAYPOINTS_URI_INDEX = 2;
private static final int MARKERS_URI_INDEX = 2;
private IntentDashboardUtils() {
}
@@ -55,7 +55,7 @@ public class IntentDashboardUtils {
ArrayList<Uri> uris = new ArrayList<>();
uris.add(TRACK_URI_INDEX, Uri.withAppendedPath(TracksColumns.CONTENT_URI, trackIdList));
uris.add(TRACKPOINTS_URI_INDEX, Uri.withAppendedPath(TrackPointsColumns.CONTENT_URI_BY_TRACKID, trackIdList));
uris.add(WAYPOINTS_URI_INDEX, Uri.withAppendedPath(MarkerColumns.CONTENT_URI_BY_TRACKID, trackIdList));
uris.add(MARKERS_URI_INDEX, Uri.withAppendedPath(MarkerColumns.CONTENT_URI_BY_TRACKID, trackIdList));
Intent intent = new Intent(ACTION_DASHBOARD);
intent.putParcelableArrayListExtra(ACTION_DASHBOARD_PAYLOAD, uris);
@@ -70,7 +70,7 @@ public class IntentDashboardUtils {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ClipData clipData = ClipData.newRawUri(null, uris.get(TRACK_URI_INDEX));
clipData.addItem(new ClipData.Item(uris.get(TRACKPOINTS_URI_INDEX)));
clipData.addItem(new ClipData.Item(uris.get(WAYPOINTS_URI_INDEX)));
clipData.addItem(new ClipData.Item(uris.get(MARKERS_URI_INDEX)));
intent.setClipData(clipData);
context.startActivity(intent);
@@ -87,7 +87,7 @@ public class IntentUtils {
for (Track.Id trackId : trackIds) {
Track track = contentProviderUtils.getTrack(trackId);
if (track == null) {
Log.e(TAG, "TrackId " + trackId + " could not be resolved.");
Log.e(TAG, "TrackId " + trackId.getId() + " could not be resolved.");
continue;
}
@@ -105,7 +105,7 @@ public class IntentUtils {
}
/**
* Creates an intent to share a waypoint image with an app.
* Creates an intent to share an image with an app.
*
* @param context the context.
* @param uri uri with the image to share.
@@ -128,8 +128,8 @@ public class IntentUtils {
.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.share_image_body));
}
public static void showCoordinateOnMap(Context context, Marker waypoint) {
showCoordinateOnMap(context, waypoint.getLocation().getLatitude(), waypoint.getLocation().getLongitude(), waypoint.getName());
public static void showCoordinateOnMap(Context context, Marker marker) {
showCoordinateOnMap(context, marker.getLocation().getLatitude(), marker.getLocation().getLongitude(), marker.getName());
}
/**
@@ -108,6 +108,8 @@ public class PreferencesUtils {
* @param keyId the key id
* @param value the value
*/
//TODO Don't use; this function is only to be used TrackRecordingService and will be removed.
@VisibleForTesting
public static void setBoolean(Context context, int keyId, boolean value) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
Editor editor = sharedPreferences.edit();
@@ -162,6 +164,9 @@ public class PreferencesUtils {
* @param keyId the key id
* @param value the value
*/
//TODO Don't use; this function is only to be used TrackRecordingService and will be removed.
@Deprecated
@VisibleForTesting
public static void setLong(Context context, int keyId, long value) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
Editor editor = sharedPreferences.edit();
@@ -188,6 +193,7 @@ public class PreferencesUtils {
* @param keyId the key id
* @param value the value
*/
@VisibleForTesting
public static void setString(Context context, int keyId, String value) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
Editor editor = sharedPreferences.edit();
@@ -346,6 +352,16 @@ public class PreferencesUtils {
return getBoolean(context, R.string.import_prevent_reimport_key, defaultValue);
}
/**
* @return {@link androidx.appcompat.app.AppCompatDelegate}.MODE_*
*/
public static int getDefaultNightMode(Context context) {
final String defaultValue = getKey(context, R.string.night_mode_default);
final String value = getString(context, R.string.night_mode_key, defaultValue);
return Integer.parseInt(value);
}
@Deprecated //Use TrackRecordingService
public static boolean isRecording(Context context) {
return isRecording(getRecordingTrackId(context));
@@ -0,0 +1,83 @@
package de.dennisguse.opentracks.util;
import android.hardware.SensorManager;
public class PressureSensorUtils {
//Everything above is considered a meaningful change in elevation.
private static float ELEVATION_CHANGE_DIFF_M = 3.0f;
private static float EXPONENTIAL_SMOOTHING = 0.3f;
private PressureSensorUtils() {
}
public static class ElevationChange {
private float currentSensorValue_hPa;
private float elevationChange_m;
public ElevationChange(float currentSensorValue_hPa, float elevationChange_m) {
this.currentSensorValue_hPa = currentSensorValue_hPa;
this.elevationChange_m = elevationChange_m;
}
public float getCurrentSensorValue_hPa() {
return currentSensorValue_hPa;
}
public float getElevationChange_m() {
return elevationChange_m;
}
public float getElevationGain_m() {
return elevationChange_m > 0 ? elevationChange_m : 0;
}
public float getElevationLoss_m() {
return elevationChange_m < 0 ? elevationChange_m : 0;
}
}
/**
* Applies exponential smoothing to sensor value before computation.
*/
public static ElevationChange computeChangesWithSmoothing_m(float lastAcceptedSensorValue_hPa, float lastSeenSensorValue_hPa, float currentSensorValue_hPa) {
float nextSensorValue_hPa = EXPONENTIAL_SMOOTHING * currentSensorValue_hPa + (1 - EXPONENTIAL_SMOOTHING) * lastSeenSensorValue_hPa;
return computeChanges_m(lastAcceptedSensorValue_hPa, nextSensorValue_hPa);
}
/**
* Computes the elevation gain and elevation loss.
*
* @return null if no meaningful elevation change occurred.
*/
public static ElevationChange computeChanges_m(float lastAcceptedSensorValue_hPa, float currentSensorValue_hPa) {
float lastSensorValue_m = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, lastAcceptedSensorValue_hPa);
float currentSensorValue_m = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, currentSensorValue_hPa);
float elevationChange_m = currentSensorValue_m - lastSensorValue_m;
if (Math.abs(elevationChange_m) < ELEVATION_CHANGE_DIFF_M) {
return null;
}
// Limit elevation change by ELEVATION_CHANGE_DIFF and computes pressure value accordingly.
ElevationChange elevationChange = new ElevationChange(currentSensorValue_hPa, elevationChange_m);
if (elevationChange.getElevationGain_m() > 0) {
return new ElevationChange(getBarometricPressure(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, lastSensorValue_m + ELEVATION_CHANGE_DIFF_M), ELEVATION_CHANGE_DIFF_M);
} else {
return new ElevationChange(getBarometricPressure(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, lastSensorValue_m - ELEVATION_CHANGE_DIFF_M), -1 * ELEVATION_CHANGE_DIFF_M);
}
}
/*
* Barometeric pressure to elevation estimation; inverts of SensorManager.getAltitude(float, float)
* https://de.wikipedia.org/wiki/Barometrische_H%C3%B6henformel#Internationale_H%C3%B6henformel
* {\color{White} p(h)} = p_0 \cdot \left( 1 - \frac{0{,}0065 \frac{\mathrm K}{\mathrm m} \cdot h}{T_0\ } \right)^{5{,}255}
*/
private static float getBarometricPressure(float p0, float altitude_m) {
return (float) (p0 * Math.pow(1.0 - 0.0065 * altitude_m / 288.15, 5.255f));
}
}
@@ -323,21 +323,21 @@ public class StringUtils {
}
/**
* Sets an elevation value.
* Sets an elevation_m value.
*
* @param context the context
* @param elevation the elevation in meters
* @param elevation_m the elevation_m
* @param metricUnits true if metric units
* @return the formatted elevation (or null) and it's unit as {@link Pair}
* @return the formatted elevation_m (or null) and it's unit as {@link Pair}
*/
public static Pair<String, String> formatElevation(Context context, double elevation, boolean metricUnits) {
public static Pair<String, String> formatElevation(Context context, Float elevation_m, boolean metricUnits) {
String value = context.getString(R.string.value_unknown);
String unit = context.getString(metricUnits ? R.string.unit_meter : R.string.unit_feet);
if (!Double.isNaN(elevation) && !Double.isInfinite(elevation)) {
if (elevation_m != null) {
if (!metricUnits) {
elevation *= UnitConversions.M_TO_FT;
elevation_m *= (float) UnitConversions.M_TO_FT;
}
value = StringUtils.formatDecimal(elevation, 0);
value = StringUtils.formatDecimal(elevation_m, 0);
}
return new Pair<>(value, unit);
}
@@ -0,0 +1,40 @@
package de.dennisguse.opentracks.util;
import android.content.Context;
import android.content.res.Resources;
import android.util.TypedValue;
import androidx.core.content.ContextCompat;
public class ThemeUtils {
private ThemeUtils() {
}
/**
* Get the material design default background color.
*/
public static int getBackgroundColor(Context context) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(android.R.attr.colorBackground, typedValue, true);
return ContextCompat.getColor(context, typedValue.resourceId);
}
public static int getTextColorPrimary(Context context) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
return ContextCompat.getColor(context, typedValue.resourceId);
}
public static int getTextColorSecondary(Context context) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(android.R.attr.textColorSecondary, typedValue, true);
return ContextCompat.getColor(context, typedValue.resourceId);
}
}
@@ -55,7 +55,7 @@ public class TrackIconUtils {
private static final String SKATE_BOARDING = "SKATE_BOARDING";
private static final String CLIMBING = "CLIMBING";
private static final int ACTIVITY_UNKNOWN_LOGO = R.drawable.ic_logo_white_24dp;
private static final int ACTIVITY_UNKNOWN_LOGO = R.drawable.ic_logo_24dp;
private static final int[] AIRPLANE_LIST = new int[]{R.string.activity_type_airplane, R.string.activity_type_commercial_airplane, R.string.activity_type_rc_airplane};
private static final int[] BIKE_LIST = new int[]{R.string.activity_type_biking, R.string.activity_type_cycling, R.string.activity_type_dirt_bike, R.string.activity_type_road_biking, R.string.activity_type_track_cycling};
@@ -154,7 +154,8 @@ public class TrackIconUtils {
* @param context the context
* @param activityType the activity type
*/
public static String getIconValue(Context context, String activityType) {
public static @NonNull
String getIconValue(Context context, String activityType) {
if (activityType == null || activityType.equals("")) {
return UNKNOWN;
}
@@ -35,17 +35,22 @@ public class TrackUtils {
}
public static void updateTrack(Context context, Track track, String name, String category, String description, ContentProviderUtils contentProviderUtils) {
boolean update = false;
if (name != null) {
track.setName(name);
update = true;
}
if (category != null) {
track.setCategory(category);
track.setIcon(TrackIconUtils.getIconValue(context, category));
update = true;
}
if (description != null) {
track.setDescription(description);
update = true;
}
if (update) {
contentProviderUtils.updateTrack(track);
}
contentProviderUtils.updateTrack(track);
}
}
@@ -26,7 +26,8 @@ public class UnitConversions {
public static final long S_TO_MS = 1000;
// Time
// 1 second in milliseconds
// TODO Use int instead of long.
public static final long ONE_SECOND_US = UnitConversions.S_TO_MS * 1000;
public static final long ONE_SECOND_MS = UnitConversions.S_TO_MS;
public static final long ONE_MINUTE_MS = (long) (UnitConversions.MIN_TO_S * UnitConversions.S_TO_MS);
public static final long ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
@@ -8,7 +8,8 @@ import de.dennisguse.opentracks.util.LocationUtils;
import de.dennisguse.opentracks.util.UnitConversions;
public class IntervalStatistics {
List<Interval> intervalList = new ArrayList<>();
private List<Interval> intervalList = new ArrayList<>();
private float distanceInterval_m;
/**
* @param trackPointList the list of TrackPoint.
@@ -16,6 +17,7 @@ public class IntervalStatistics {
*/
public void build(List<TrackPoint> trackPointList, float distanceInterval_m) {
intervalList.clear();
this.distanceInterval_m = distanceInterval_m;
if (trackPointList == null || trackPointList.size() == 0) {
return;
@@ -51,6 +53,30 @@ public class IntervalStatistics {
return intervalList;
}
/**
* Return the last completed interval.
* An interval is complete if its distance is equal to distanceInterval_m.
*
* @return the interval object or null if any interval is completed.
*/
public Interval getLastInterval() {
if (intervalList == null) {
return null;
}
if (intervalList.size() == 1 && intervalList.get(0).getDistance_m() < distanceInterval_m) {
return null;
}
for (int i = intervalList.size() - 1; i >= 0; i--) {
if (intervalList.get(i).getDistance_m() >= distanceInterval_m) {
return this.intervalList.get(i);
}
}
return null;
}
public static class Interval {
private float distance_m = 0f;
private float time_ms = 0f;
@@ -24,7 +24,6 @@ import de.dennisguse.opentracks.util.UnitConversions;
public class IntervalStatisticsModel extends AndroidViewModel {
private MutableLiveData<IntervalStatistics> intervalStats = new MutableLiveData<>();
private IntervalOption interval = IntervalOption.OPTION_1;
public IntervalStatisticsModel(@NonNull Application application) {
super(application);
@@ -76,5 +75,10 @@ public class IntervalStatisticsModel extends AndroidViewModel {
public int getValue() {
return value;
}
@Override
public String toString() {
return "" + value;
}
}
}
@@ -1,122 +0,0 @@
package de.dennisguse.opentracks.views;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
import de.dennisguse.opentracks.R;
import de.dennisguse.opentracks.adapters.IntervalStatisticsAdapter;
import de.dennisguse.opentracks.util.PreferencesUtils;
import de.dennisguse.opentracks.viewmodels.IntervalStatistics;
import de.dennisguse.opentracks.viewmodels.IntervalStatisticsModel;
/**
* LinearLayout view used to build a list of intervals.
* See {@link IntervalStatisticsAdapter}.
*/
public class IntervalListView extends LinearLayout {
protected IntervalStatisticsAdapter adapter;
protected LinearLayout linearLayoutIntervals;
protected Spinner spinnerIntervals;
protected TextView spinnerIntervalsUnit;
protected IntervalListListener listener;
protected final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = (preferences, key) -> {
if (PreferencesUtils.isKey(getContext(), R.string.stats_units_key, key) || PreferencesUtils.isKey(getContext(), R.string.stats_rate_key, key)) {
if (spinnerIntervalsUnit != null) {
spinnerIntervalsUnit.setText(PreferencesUtils.isMetricUnits(getContext()) ? getContext().getString(R.string.unit_kilometer) : getContext().getString(R.string.unit_mile));
listener.unitChanged();
}
}
};
public IntervalListView(Context context, IntervalListListener listener) {
super(context);
this.listener = listener;
PreferencesUtils.register(getContext(), sharedPreferenceChangeListener);
inflate(getContext(), R.layout.interval_list_view, this);
linearLayoutIntervals = findViewById(R.id.interval_list);
spinnerIntervals = findViewById(R.id.spinner_intervals);
int[] intValues = Arrays.stream(IntervalStatisticsModel.IntervalOption.values()).mapToInt(i -> i.getValue()).toArray();
spinnerIntervals.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, Arrays.stream(intValues).mapToObj(String::valueOf).toArray(String[]::new)));
spinnerIntervalsUnit = findViewById(R.id.spinner_intervals_unit);
spinnerIntervalsUnit.setText(PreferencesUtils.isMetricUnits(getContext()) ? getContext().getString(R.string.unit_kilometer) : getContext().getString(R.string.unit_mile));
spinnerIntervals.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
IntervalStatisticsModel.IntervalOption interval = IntervalStatisticsModel.IntervalOption.values()[i];
listener.intervalChanged(interval);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void destroy() {
PreferencesUtils.unregister(getContext(), sharedPreferenceChangeListener);
adapter = null;
linearLayoutIntervals = null;
spinnerIntervals = null;
spinnerIntervalsUnit = null;
listener = null;
}
public void display(List<IntervalStatistics.Interval> intervalList) {
if (intervalList == null) {
return;
}
adapter = new IntervalStatisticsAdapter(getContext(), intervalList);
linearLayoutIntervals.removeAllViews();
for (int i = 0; i < adapter.getCount(); i++) {
View intervalView = adapter.getView(i, null, linearLayoutIntervals);
linearLayoutIntervals.addView(intervalView);
}
}
public interface IntervalListListener {
void intervalChanged(IntervalStatisticsModel.IntervalOption interval);
void unitChanged();
}
/**
* LinearLayout view used to build a list of intervals in a reverse mode, the last one will appear in the first position on the LinearLayout.
* This class is an specialization of {@link IntervalListView} that display the views contained in the LinearLayout in a reverse mode.
*/
public static class IntervalReverseListView extends IntervalListView {
public IntervalReverseListView(Context context, IntervalListListener listener) {
super(context, listener);
}
public void display(List<IntervalStatistics.Interval> intervalList) {
if (intervalList == null) {
return;
}
adapter = new IntervalStatisticsAdapter(getContext(), intervalList);
linearLayoutIntervals.removeAllViews();
for (int i = 0; i < adapter.getCount(); i++) {
View intervalView = adapter.getView(i, null, linearLayoutIntervals);
linearLayoutIntervals.addView(intervalView, 0);
}
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 383 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 354 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 404 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 727 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 585 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Some files were not shown because too many files have changed in this diff Show More