diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bf73fc6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,113 @@ +*.iml +.gradle +/local.properties +.DS_Store +/build +/captures +.externalNativeBuild +.cxx + +############## +# Custom # +############## +publish-checklist.txt +build_signed_release.sh +build_debug.sh +*icon.svg +banner.svg +*ic_launcher-playstore.png +.idea/ +app/release/ +app/debug/ +app/src/androidTest/ +app/src/test/ + +##################################################################### +# https://github.com/github/gitignore/blob/master/Android.gitignore # +##################################################################### + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +#*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +#.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2beb9e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..df6bc11 --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +# MyLocation [![Download](https://img.shields.io/github/v/release/mirfatif/MyLocation?label="Download")](https://github.com/mirfatif/MyLocation/releases/latest) +Know your geo coordinates using on-device GPS and Network location providers + + + +## Features + +My Location finds your device's location in the following ways: + +* GPS is usually the most accurate method. But a position fix may take some time or may not work at all due to signal loss. "Lock GPS" feature runs a persistent service to keep connected with the satellites. + + You can also see the list of visible satellites with their PRNs (unique identifiers) and SNR (signal quality). + +* Network Location Provider uses Wi-Fi or Cellular ids to estimate the location. On the devices with Google Play Services installed, NLP usually uses Google Location Service at backend. +* UnifiedNLP is an open source API which has been used to develop multiple NLP backends (https://github.com/microg/UnifiedNlp/wiki/Backends). + +Furthermore: + +* Location coordinates can be copied to clipboard or opened in a maps app, if installed. +* Clearing A-GPS aiding data is also supported. + +## Screenshots + + + +## Third-Party Resources + +* https://github.com/androidx/androidx +* https://github.com/microg/android_external_UnifiedNlpApi +* https://github.com/square/leakcanary +* https://github.com/sherter/google-java-format-gradle-plugin + +## License [![License](https://img.shields.io/github/license/mirfatif/MyLocation?label="License")](https://github.com/mirfatif/MyLocation/blob/master/LICENSE) + +You **CANNOT** use and distribute the app icon in anyway, except for **My Location** (`com.mirfatif.mylocation`) app. + + My Location is free software: you can redistribute it and/or modify + it under the terms of the Affero GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + Affero GNU General Public License for more details. + + You should have received a copy of the Affero GNU General Public License + along with this program. If not, see . diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..1fb562e --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,48 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion compileSdkVer + buildToolsVersion buildToolsVer + + defaultConfig { + applicationId "com.mirfatif.mylocation" + minSdkVersion minSdkVer + targetSdkVersion targetSdkVer + versionCode 101 + versionName "v1.01" + + buildConfigField "boolean", "IS_PS", "false" + } + + buildTypes { + release { + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + dependenciesInfo { + includeInApk false + } + + buildFeatures { + viewBinding true + } +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.3.0' + implementation 'androidx.recyclerview:recyclerview:1.2.1' + implementation 'androidx.browser:browser:1.3.0' + implementation "androidx.security:security-crypto:1.1.0-alpha03" + debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7' +} + +apply plugin: 'com.github.sherter.google-java-format' +preBuild.dependsOn(verifyGoogleJavaFormat) diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..3020142 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,5 @@ +# Preserve the line number information for debugging stack traces. +-keepattributes SourceFile,LineNumberTable + +# Hide the original source file name. +-renamesourcefileattribute SourceFile diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..71630de --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/aidl/org/microg/nlp/api/LocationBackend.aidl b/app/src/main/aidl/org/microg/nlp/api/LocationBackend.aidl new file mode 100644 index 0000000..70c9878 --- /dev/null +++ b/app/src/main/aidl/org/microg/nlp/api/LocationBackend.aidl @@ -0,0 +1,14 @@ +package org.microg.nlp.api; + +import org.microg.nlp.api.LocationCallback; +import android.content.Intent; +import android.location.Location; + +interface LocationBackend { + void open(LocationCallback callback); + Location update(); + void close(); + Intent getInitIntent(); + Intent getSettingsIntent(); + Intent getAboutIntent(); +} diff --git a/app/src/main/aidl/org/microg/nlp/api/LocationCallback.aidl b/app/src/main/aidl/org/microg/nlp/api/LocationCallback.aidl new file mode 100644 index 0000000..fa323ad --- /dev/null +++ b/app/src/main/aidl/org/microg/nlp/api/LocationCallback.aidl @@ -0,0 +1,7 @@ +package org.microg.nlp.api; + +import android.location.Location; + +interface LocationCallback { + void report(in Location location); +} diff --git a/app/src/main/java/com/mirfatif/mylocation/AboutDialogFragment.java b/app/src/main/java/com/mirfatif/mylocation/AboutDialogFragment.java new file mode 100644 index 0000000..237d520 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/AboutDialogFragment.java @@ -0,0 +1,57 @@ +package com.mirfatif.mylocation; + +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AlertDialog.Builder; +import androidx.appcompat.app.AppCompatDialogFragment; +import com.mirfatif.mylocation.databinding.AboutDialogBinding; + +public class AboutDialogFragment extends AppCompatDialogFragment { + + public AboutDialogFragment() {} + + private MainActivity mA; + + @Override + public void onAttach(@NonNull Context context) { + super.onAttach(context); + mA = (MainActivity) getActivity(); + } + + @NonNull + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + AboutDialogBinding b = AboutDialogBinding.inflate(mA.getLayoutInflater()); + b.version.setText(BuildConfig.VERSION_NAME); + openWebUrl(b.telegram, R.string.telegram_link); + openWebUrl(b.sourceCode, R.string.source_url); + openWebUrl(b.rating, R.string.play_store_url); + openWebUrl(b.privacyPolicy, R.string.privacy_policy_link); + b.contact.setOnClickListener(v -> Utils.sendMail(mA, null)); + b.shareApp.setOnClickListener(v -> sendShareIntent()); + if (BuildConfig.IS_PS) { + openWebUrl(b.checkUpdate, R.string.play_store_url); + } else { + openWebUrl(b.checkUpdate, R.string.release_url); + } + + AlertDialog dialog = new Builder(mA).setView(b.getRoot()).create(); + return Utils.setDialogBg(dialog); + } + + private void openWebUrl(View view, int linkResId) { + view.setOnClickListener(v -> Utils.openWebUrl(mA, getString(linkResId))); + } + + private void sendShareIntent() { + Intent intent = new Intent(Intent.ACTION_SEND).setType("text/plain"); + intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name)); + String text = getString(R.string.share_text, getString(R.string.play_store_url)); + startActivity(Intent.createChooser(intent.putExtra(Intent.EXTRA_TEXT, text), null)); + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/App.java b/app/src/main/java/com/mirfatif/mylocation/App.java new file mode 100644 index 0000000..9c9aaeb --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/App.java @@ -0,0 +1,51 @@ +package com.mirfatif.mylocation; + +import android.app.Application; +import android.content.Context; +import android.content.res.Resources; +import android.util.Log; +import java.io.PrintWriter; +import java.io.StringWriter; + +public class App extends Application { + + private static final String TAG = "App"; + + private static Context mAppContext; + private Thread.UncaughtExceptionHandler defaultExceptionHandler; + + @Override + public void onCreate() { + super.onCreate(); + mAppContext = getApplicationContext(); + defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); + + Thread.setDefaultUncaughtExceptionHandler( + (t, e) -> { + Log.e(TAG, e.toString()); + + StringWriter stringWriter = new StringWriter(); + PrintWriter writer = new PrintWriter(stringWriter, true); + e.printStackTrace(writer); + writer.close(); + Utils.writeCrashLog(stringWriter.toString()); + + defaultExceptionHandler.uncaughtException(t, e); + }); + + Utils.runBg(this::getEncPrefs); + } + + public static Context getCxt() { + return mAppContext; + } + + public static Resources getRes() { + return mAppContext.getResources(); + } + + // To avoid delays later + private void getEncPrefs() { + Utils.getEncPrefs(); + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/DonateDialogFragment.java b/app/src/main/java/com/mirfatif/mylocation/DonateDialogFragment.java new file mode 100644 index 0000000..028c759 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/DonateDialogFragment.java @@ -0,0 +1,77 @@ +package com.mirfatif.mylocation; + +import static com.mirfatif.mylocation.Utils.openWebUrl; + +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Bundle; +import android.view.View; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AlertDialog.Builder; +import androidx.appcompat.app.AppCompatDialogFragment; +import com.mirfatif.mylocation.databinding.DonateDialogBinding; + +public class DonateDialogFragment extends AppCompatDialogFragment { + + public DonateDialogFragment() {} + + private MainActivity mA; + + @Override + public void onAttach(@NonNull Context context) { + super.onAttach(context); + mA = (MainActivity) getActivity(); + } + + private DonateDialogBinding mB; + + @NonNull + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + mB = DonateDialogBinding.inflate(mA.getLayoutInflater()); + + setButtonClickListener(mB.bitcoinButton, mB.bitcoinContainer); + setButtonClickListener(mB.bankAccountButton, mB.bankAccountLink); + setButtonClickListener(mB.playStoreButton, mB.playStoreLink); + + mB.bitcoinLink.setOnClickListener(v -> handleBitcoinClick()); + mB.playStoreLink.setOnClickListener(v -> openWebUrl(mA, getString(R.string.play_store_url))); + String msg = Utils.getString(R.string.bank_account_request); + mB.bankAccountLink.setOnClickListener(v -> Utils.sendMail(mA, msg)); + + AlertDialog dialog = + new Builder(mA).setTitle(R.string.donate_menu_item).setView(mB.getRoot()).create(); + return Utils.setDialogBg(dialog); + } + + private void setButtonClickListener(View button, View detailsView) { + button.setOnClickListener( + v -> { + hideAll(); + detailsView.setVisibility(View.VISIBLE); + }); + } + + private void hideAll() { + mB.bitcoinContainer.setVisibility(View.GONE); + mB.bankAccountLink.setVisibility(View.GONE); + mB.playStoreLink.setVisibility(View.GONE); + } + + private void handleBitcoinClick() { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setData(Uri.parse("bitcoin:" + Utils.getString(R.string.bitcoin_address))); + if (App.getCxt() + .getPackageManager() + .queryIntentActivities(intent, PackageManager.MATCH_ALL) + .isEmpty()) { + Utils.showToast(R.string.no_bitcoin_app_installed); + } else { + mA.startActivity(intent); + } + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/GpsSvc.java b/app/src/main/java/com/mirfatif/mylocation/GpsSvc.java new file mode 100644 index 0000000..fabef51 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/GpsSvc.java @@ -0,0 +1,251 @@ +package com.mirfatif.mylocation; + +import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; +import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST; +import static androidx.core.app.NotificationManagerCompat.IMPORTANCE_DEFAULT; +import static com.mirfatif.mylocation.BuildConfig.APPLICATION_ID; +import static com.mirfatif.mylocation.Utils.formatLatLng; +import static com.mirfatif.mylocation.Utils.formatLocAccuracy; +import static com.mirfatif.mylocation.Utils.hasFineLocPerm; + +import android.annotation.SuppressLint; +import android.app.PendingIntent; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.location.GpsSatellite; +import android.location.GpsStatus; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Build.VERSION; +import android.os.Build.VERSION_CODES; +import android.os.Bundle; +import android.os.IBinder; +import android.os.PowerManager; +import android.os.PowerManager.WakeLock; +import androidx.core.app.NotificationCompat; +import androidx.core.app.NotificationCompat.BigTextStyle; +import androidx.core.app.NotificationCompat.Builder; +import androidx.core.app.NotificationManagerCompat; +import java.util.concurrent.Future; + +public class GpsSvc extends Service implements LocationListener, GpsStatus.Listener { + + public static final String ACTION_STOP_SERVICE = APPLICATION_ID + ".action.STOP_SERVICE"; + + public static boolean mIsRunning = false; + + private final LocationManager mLocManager = + (LocationManager) App.getCxt().getSystemService(Context.LOCATION_SERVICE); + + private final PowerManager mPowerManager = + (PowerManager) App.getCxt().getSystemService(Context.POWER_SERVICE); + + private final NotificationManagerCompat mNotifManager = + NotificationManagerCompat.from(App.getCxt()); + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (hasFineLocPerm() && (intent == null || !ACTION_STOP_SERVICE.equals(intent.getAction()))) { + showNotif(); + startGpsLocListener(); + mIsRunning = true; + return START_STICKY; + } else { + stop(); + return START_NOT_STICKY; + } + } + + @Override + public void onDestroy() { + stop(); + super.onDestroy(); + } + + private Location mGpsLoc; + + @Override + public void onLocationChanged(Location location) { + mGpsLoc = location; + updateNotification(); + } + + @Override + public void onProviderEnabled(String provider) { + mLastUpdate = 0; + updateNotification(); + } + + @Override + public void onProviderDisabled(String provider) { + mLastUpdate = 0; + updateNotification(); + } + + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + mLastUpdate = 0; + updateNotification(); + } + + private void stop() { + mIsRunning = false; + stopGpsLocListener(); + if (mFuture != null) { + mFuture.cancel(true); + } + stopSelf(); + } + + @Override + public void onGpsStatusChanged(int event) { + updateGpsSats(); + } + + private WakeLock mWakeLock; + private Builder mNotifBuilder; + + private static final int NOTIF_ID = Utils.getInteger(R.integer.channel_gps_lock); + private static final String CHANNEL_ID = "channel_gps_lock"; + private static final String CHANNEL_NAME = Utils.getString(R.string.channel_gps_lock); + + private void showNotif() { + mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); + mWakeLock.acquire(30 * 60 * 1000L); + + Utils.createNotifChannel(CHANNEL_ID, CHANNEL_NAME, IMPORTANCE_DEFAULT); + + Intent intent = new Intent(App.getCxt(), MainActivity.class); + PendingIntent pi = + PendingIntent.getActivity(App.getCxt(), NOTIF_ID, intent, FLAG_UPDATE_CURRENT); + + mNotifBuilder = + new Builder(App.getCxt(), CHANNEL_ID) + .setSilent(true) + .setOnlyAlertOnce(true) + .setSmallIcon(R.drawable.notification_icon) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) // For N and below + .setContentIntent(pi) + .setAutoCancel(false) + .setOngoing(true) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setContentTitle(getString(R.string.channel_gps_lock)); + + if (VERSION.SDK_INT >= VERSION_CODES.Q) { + startForeground(NOTIF_ID, mNotifBuilder.build(), FOREGROUND_SERVICE_TYPE_MANIFEST); + } else { + startForeground(NOTIF_ID, mNotifBuilder.build()); + } + + updateGpsSats(); + mLastUpdate = 0; + updateNotification(); + } + + public static final long MIN_DELAY = 5000; + + @SuppressLint("MissingPermission") + private void startGpsLocListener() { + mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_DELAY, 0, this); + mLocManager.addGpsStatusListener(this); + } + + private void stopGpsLocListener() { + if (mWakeLock != null) { + mWakeLock.release(); + mWakeLock = null; + } + mLocManager.removeUpdates(this); + mLocManager.removeGpsStatusListener(this); + } + + private final Object UPDATE_GPS_SATS_LOCK = new Object(); + private int mTotalSats, mSatsStrongSig, mUsedSats; + + @SuppressLint("MissingPermission") + private void updateGpsSats() { + synchronized (UPDATE_GPS_SATS_LOCK) { + if (!hasFineLocPerm()) { + stop(); + return; + } + GpsStatus gpsStatus = mLocManager.getGpsStatus(null); + mTotalSats = mSatsStrongSig = mUsedSats = 0; + for (GpsSatellite gpsSat : gpsStatus.getSatellites()) { + mTotalSats++; + if (gpsSat.getSnr() != 0) { + mSatsStrongSig++; + } + if (gpsSat.usedInFix()) { + mUsedSats++; + } + } + updateNotification(); + } + } + + private Future mFuture; + + private synchronized void updateNotification() { + if (mFuture != null) { + mFuture.cancel(true); + } + mFuture = Utils.runBg(this::updateNotifBg); + } + + private final Object NOTIF_UPDATE_LOCK = new Object(); + private long mLastUpdate; + + private void updateNotifBg() { + synchronized (NOTIF_UPDATE_LOCK) { + long sleep = 5000 + mLastUpdate - System.currentTimeMillis(); + if (sleep > 0) { + try { + NOTIF_UPDATE_LOCK.wait(sleep); + } catch (InterruptedException e) { + return; + } + } + mLastUpdate = System.currentTimeMillis(); + + String sText, bText; + long when = 0; + if (!mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + sText = bText = getString(R.string.turned_off); + } else { + sText = bText = getString(R.string.satellites_count, mTotalSats, mSatsStrongSig, mUsedSats); + double lat, lng; + if (mGpsLoc != null + && (lat = mGpsLoc.getLatitude()) != 0 + && (lng = mGpsLoc.getLongitude()) != 0) { + sText = + getString( + R.string.location, + formatLatLng(lat), + formatLatLng(lng), + formatLocAccuracy(mGpsLoc.getAccuracy())); + bText += "\n" + sText; + } + if (mGpsLoc != null && mGpsLoc.getTime() != 0) { + when = mGpsLoc.getTime(); + } + } + mNotifBuilder.setContentText(sText); + mNotifBuilder.setStyle(new BigTextStyle().bigText(bText)); + if (when != 0) { + mNotifBuilder.setWhen(when); + mNotifBuilder.setShowWhen(true); + } else { + mNotifBuilder.setShowWhen(false); + } + mNotifManager.notify(NOTIF_ID, mNotifBuilder.build()); + } + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/LicenseChecker.java b/app/src/main/java/com/mirfatif/mylocation/LicenseChecker.java new file mode 100644 index 0000000..15ba0af --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/LicenseChecker.java @@ -0,0 +1,17 @@ +package com.mirfatif.mylocation; + +import androidx.fragment.app.FragmentActivity; + +public class LicenseChecker { + + @SuppressWarnings("UnusedParameters") + LicenseChecker(FragmentActivity activity) {} + + void check() {} + + void onDestroy() {} + + public boolean isVerified() { + return true; + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/MainActivity.java b/app/src/main/java/com/mirfatif/mylocation/MainActivity.java new file mode 100644 index 0000000..d7e7139 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/MainActivity.java @@ -0,0 +1,750 @@ +package com.mirfatif.mylocation; + +import static android.content.pm.PackageManager.PERMISSION_GRANTED; +import static android.location.LocationManager.GPS_PROVIDER; +import static android.location.LocationManager.NETWORK_PROVIDER; +import static android.os.Build.VERSION.SDK_INT; +import static com.mirfatif.mylocation.GpsSvc.ACTION_STOP_SERVICE; +import static com.mirfatif.mylocation.GpsSvc.MIN_DELAY; +import static com.mirfatif.mylocation.MySettings.SETTINGS; +import static com.mirfatif.mylocation.Utils.copyLoc; +import static com.mirfatif.mylocation.Utils.hasCoarseLocPerm; +import static com.mirfatif.mylocation.Utils.hasFineLocPerm; +import static com.mirfatif.mylocation.Utils.isNaN; +import static com.mirfatif.mylocation.Utils.openMap; +import static com.mirfatif.mylocation.Utils.setNightTheme; + +import android.Manifest.permission; +import android.annotation.SuppressLint; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.location.GpsSatellite; +import android.location.GpsStatus; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Build.VERSION; +import android.os.Build.VERSION_CODES; +import android.os.Bundle; +import android.provider.Settings; +import android.text.format.DateUtils; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import androidx.annotation.NonNull; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.view.menu.MenuBuilder; +import androidx.core.app.ActivityCompat; +import androidx.core.view.MenuCompat; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.recyclerview.widget.DividerItemDecoration; +import androidx.recyclerview.widget.LinearLayoutManager; +import com.mirfatif.mylocation.NlpAdapter.NlpClickListener; +import com.mirfatif.mylocation.databinding.ActivityMainBinding; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.locks.ReentrantLock; + +public class MainActivity extends AppCompatActivity { + + private ActivityMainBinding mB; + + private final LocationManager mLocManager = + (LocationManager) App.getCxt().getSystemService(Context.LOCATION_SERVICE); + + private LicenseChecker mLicenseChecker; + private boolean mGpsProviderSupported = false; + private boolean mNetProviderSupported = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + setTheme(R.style.AppTheme); + super.onCreate(savedInstanceState); + if (setNightTheme(this)) { + return; + } + mB = ActivityMainBinding.inflate(getLayoutInflater()); + setContentView(mB.getRoot()); + + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayUseLogoEnabled(true); + actionBar.setDisplayShowHomeEnabled(true); + actionBar.setIcon(R.drawable.action_bar_icon); + } + + for (String provider : mLocManager.getAllProviders()) { + if (provider.equals(GPS_PROVIDER)) { + mGpsProviderSupported = true; + } + if (provider.equals(NETWORK_PROVIDER)) { + mNetProviderSupported = true; + } + } + + setupGps(); + updateGpsUi(); + setupNetwork(); + updateNetUi(); + setupUnifiedNlp(); + checkPerms(); + + mB.grantPerm.setOnClickListener(v -> Utils.openAppSettings(this, getPackageName())); + + mLicenseChecker = new LicenseChecker(this); + } + + @Override + protected void onStart() { + super.onStart(); + startLocListeners(); + setTimer(); + setGrantPermButtonState(); + } + + @Override + protected void onStop() { + stopTimer(); + stopLocListeners(); + super.onStop(); + } + + @Override + protected void onResume() { + super.onResume(); + checkLicense(); + } + + @Override + protected void onDestroy() { + if (mLicenseChecker != null) { + mLicenseChecker.onDestroy(); + } + super.onDestroy(); + } + + @Override + protected void onSaveInstanceState(@NonNull Bundle outState) { + FragmentManager fm = getSupportFragmentManager(); + Fragment frag = fm.findFragmentByTag(SATS_DIALOG_TAG); + if (frag != null) { + fm.beginTransaction().remove(frag).commitNowAllowingStateLoss(); + } + super.onSaveInstanceState(outState); + } + + @Override + public void onBackPressed() { + if (VERSION.SDK_INT == VERSION_CODES.Q) { + // Bug: https://issuetracker.google.com/issues/139738913 + finishAfterTransition(); + } else { + super.onBackPressed(); + } + } + + @SuppressLint("RestrictedApi") + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.main_overflow, menu); + MenuCompat.setGroupDividerEnabled(menu, true); + if (menu instanceof MenuBuilder) { + ((MenuBuilder) menu).setOptionalIconsVisible(true); + } + menu.findItem(R.id.action_dark_theme).setChecked(SETTINGS.getForceDarkMode()); + if (BuildConfig.IS_PS) { + menu.findItem(R.id.action_donate).setVisible(false); + } + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == R.id.action_loc_settings) { + try { + startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); + } catch (ActivityNotFoundException ignored) { + Utils.showToast(R.string.failed_open_loc_settings); + } + return true; + } + if (itemId == R.id.action_dark_theme) { + SETTINGS.setForceDarkMode(!item.isChecked()); + setNightTheme(this); + return true; + } + if (itemId == R.id.action_donate) { + new DonateDialogFragment().show(getSupportFragmentManager(), "DONATE"); + return true; + } + if (itemId == R.id.action_about) { + new AboutDialogFragment().showNow(getSupportFragmentManager(), "ABOUT_DIALOG"); + return true; + } + return super.onOptionsItemSelected(item); + } + + ////////////////////////////////////////////////////////////////// + ////////////////////////// LOC PROVIDERS ///////////////////////// + ////////////////////////////////////////////////////////////////// + + private void setupGps() { + if (!mGpsProviderSupported) { + return; + } + + mB.clearAgps.setOnClickListener(v -> clearAGPSData()); + mB.lockGps.setOnClickListener( + v -> { + if (mB.lockGps.isChecked()) { + Intent intent = new Intent(App.getCxt(), GpsSvc.class); + // If startForeground() in Service is called on UI thread, it won't show notification + // unless Service is started with startForegroundService(). + if (SDK_INT >= VERSION_CODES.O) { + startForegroundService(intent); + } else { + startService(intent); + } + } else { + startService(new Intent(App.getCxt(), GpsSvc.class).setAction(ACTION_STOP_SERVICE)); + } + }); + + mB.gpsCont.map.setOnClickListener(v -> openMap(this, mGpsLocation)); + mB.gpsCont.copy.setOnClickListener(v -> copyLoc(mGpsLocation)); + + // setOnCheckedChangeListener() doesn't work well on screen rotation. + mB.gpsCont.switchV.setOnClickListener( + v -> { + if (SETTINGS.getGpsEnabled() != mB.gpsCont.switchV.isChecked()) { + SETTINGS.setGpsEnabled(mB.gpsCont.switchV.isChecked()); + startGpsLocListener(); + setTimer(); + } + }); + + if (GpsSvc.mIsRunning) { + mB.lockGps.setChecked(true); + } + + mB.gpsCont.satDetail.setOnClickListener(v -> showSatsDialog()); + + Utils.setTooltip(mB.gpsCont.map); + Utils.setTooltip(mB.gpsCont.copy); + Utils.setTooltip(mB.gpsCont.satDetail); + } + + private void setupNetwork() { + if (!mNetProviderSupported) { + return; + } + + mB.netCont.map.setOnClickListener(v -> openMap(this, mNetLocation)); + mB.netCont.copy.setOnClickListener(v -> copyLoc(mNetLocation)); + + mB.netCont.switchV.setOnClickListener( + v -> { + if (SETTINGS.getNetworkEnabled() != mB.netCont.switchV.isChecked()) { + SETTINGS.setNetworkEnabled(mB.netCont.switchV.isChecked()); + startNetLocListener(); + setTimer(); + } + }); + + Utils.setTooltip(mB.netCont.map); + Utils.setTooltip(mB.netCont.copy); + } + + private static final String ACTION_LOCATION_BACKEND = "org.microg.nlp.LOCATION_BACKEND"; + + private final List mBackends = new ArrayList<>(); + private NlpAdapter mNlpAdapter; + + private void setupUnifiedNlp() { + Intent intent = new Intent(ACTION_LOCATION_BACKEND); + List infoList = getPackageManager().queryIntentServices(intent, 0); + synchronized (mBackends) { + mBackends.clear(); + for (ResolveInfo info : infoList) { + mBackends.add(new NlpBackend(info.serviceInfo)); + } + } + + if (infoList.size() == 0) { + mB.nlpCont.stateV.setText(R.string.not_installed); + } + mB.nlpCont.switchV.setOnClickListener( + v -> { + if (SETTINGS.getNlpEnabled() != mB.nlpCont.switchV.isChecked()) { + SETTINGS.setNlpEnabled(mB.nlpCont.switchV.isChecked()); + startNlpBackends(); + setTimer(); + } + }); + + mNlpAdapter = + new NlpAdapter( + new NlpClickListener() { + @Override + public void mapClicked(Location loc) { + openMap(MainActivity.this, loc); + } + + @Override + public void copyClicked(Location loc) { + copyLoc(loc); + } + + @Override + public void settingsClicked(String pkg) { + Utils.openAppSettings(MainActivity.this, pkg); + } + }, + mBackends); + mB.nlpCont.rv.setAdapter(mNlpAdapter); + mB.nlpCont.rv.setLayoutManager(new LinearLayoutManager(this)); + mB.nlpCont.rv.addItemDecoration( + new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); + } + + private final Object LOC_LISTENER_LOCK = new Object(); + + private void startLocListeners() { + startGpsLocListener(); + startNetLocListener(); + startNlpBackends(); + } + + private LocListener mGpsLocListener; + private GpsStatus.Listener mGpsStatusListener; + + @SuppressLint("MissingPermission") + private void startGpsLocListener() { + synchronized (LOC_LISTENER_LOCK) { + stopGpsLocListener(); + if (SETTINGS.getGpsEnabled() && mGpsProviderSupported && hasFineLocPerm()) { + mGpsLocListener = new LocListener(true); + mLocManager.requestLocationUpdates(GPS_PROVIDER, MIN_DELAY, 0, mGpsLocListener); + mGpsStatusListener = new GpsStatusListener(); + mLocManager.addGpsStatusListener(mGpsStatusListener); + } + } + } + + private LocListener mNetLocListener; + + @SuppressLint("MissingPermission") + private void startNetLocListener() { + synchronized (LOC_LISTENER_LOCK) { + stopNetLocListener(); + if (SETTINGS.getNetworkEnabled() + && mNetProviderSupported + && (hasCoarseLocPerm() || hasFineLocPerm())) { + mNetLocListener = new LocListener(false); + mLocManager.requestLocationUpdates(NETWORK_PROVIDER, MIN_DELAY, 0, mNetLocListener); + } + } + } + + private void startNlpBackends() { + synchronized (mBackends) { + stopNlpBackends(); + if (SETTINGS.getNlpEnabled()) { + for (NlpBackend backend : mBackends) { + backend.start(); + } + } + } + } + + private void stopLocListeners() { + stopGpsLocListener(); + stopNetLocListener(); + stopNlpBackends(); + } + + private void stopGpsLocListener() { + synchronized (LOC_LISTENER_LOCK) { + if (mGpsLocListener != null) { + mLocManager.removeUpdates(mGpsLocListener); + mGpsLocListener = null; + } + if (mGpsStatusListener != null) { + mLocManager.removeGpsStatusListener(mGpsStatusListener); + mGpsStatusListener = null; + } + clearGpsData(); + } + } + + private void clearGpsData() { + mGpsLocation = null; + synchronized (mSats) { + mSats.clear(); + } + } + + private void stopNetLocListener() { + synchronized (LOC_LISTENER_LOCK) { + if (mNetLocListener != null) { + mLocManager.removeUpdates(mNetLocListener); + mNetLocListener = null; + } + mNetLocation = null; + } + } + + private void stopNlpBackends() { + synchronized (mBackends) { + for (NlpBackend backend : mBackends) { + backend.stop(); + } + } + } + + ////////////////////////////////////////////////////////////////// + /////////////////////////////// UI ////////////////////////////// + ////////////////////////////////////////////////////////////////// + + private final List mSats = new ArrayList<>(); + private final ReentrantLock UPDATE_SATS_LOCK = new ReentrantLock(); + + @SuppressLint("MissingPermission") + private void updateGpsSats() { + if (!UPDATE_SATS_LOCK.tryLock()) { + return; + } + if (hasFineLocPerm()) { + GpsStatus gpsStatus = mLocManager.getGpsStatus(null); + synchronized (mSats) { + mSats.clear(); + for (GpsSatellite gpsSat : gpsStatus.getSatellites()) { + mSats.add(new Sat(gpsSat.getPrn(), gpsSat.usedInFix(), gpsSat.getSnr())); + } + Collections.sort(mSats, (s1, s2) -> Float.compare(s2.mSnr, s1.mSnr)); + } + } + UPDATE_SATS_LOCK.unlock(); + } + + private Timer mTimer; + private long mPeriod = 1000; + private int mTickCount; + + private void setTimer() { + mPeriod = 1000; + mTickCount = 0; + startTimer(); + } + + private void startTimer() { + stopTimer(); + mTimer = new Timer(); + mTimer.scheduleAtFixedRate( + new TimerTask() { + @Override + public void run() { + Utils.runUi(() -> updateUi()); + mTickCount++; + if (mTickCount == 5) { + mPeriod = 5000; + startTimer(); + } + } + }, + 0, + mPeriod); + } + + private void stopTimer() { + if (mTimer != null) { + mTimer.cancel(); + mTimer = null; + } + } + + private Location mGpsLocation, mNetLocation; + + private void updateUi() { + if (mB != null && mLicenseChecker != null && mLicenseChecker.isVerified()) { + updateGpsUi(); + updateNetUi(); + updateNlpUi(); + } + } + + private void updateGpsUi() { + String state = null, lat = "--", lng = "--", acc = "--", time = "--"; + boolean hasFineLocPerm = false, showSats = false, locAvailable = false; + if (!mGpsProviderSupported) { + state = getString(R.string.not_supported); + } else { + hasFineLocPerm = hasFineLocPerm(); + if (!hasFineLocPerm) { + state = getString(R.string.perm_not_granted); + } else if (!mLocManager.isProviderEnabled(GPS_PROVIDER)) { + state = getString(R.string.turned_off); + } else { + showSats = SETTINGS.getGpsEnabled(); + if (mGpsLocation != null + && !isNaN(mGpsLocation.getLatitude()) + && !isNaN(mGpsLocation.getLongitude())) { + locAvailable = true; + lat = Utils.formatLatLng(mGpsLocation.getLatitude()); + lng = Utils.formatLatLng(mGpsLocation.getLongitude()); + if (!isNaN(mGpsLocation.getAccuracy()) && mGpsLocation.getAccuracy() != 0) { + acc = getString(R.string.acc_unit, Utils.formatLocAccuracy(mGpsLocation.getAccuracy())); + } + long curr = System.currentTimeMillis(); + long t = mGpsLocation.getTime(); + t = t - Math.max(0, t - curr); + time = DateUtils.getRelativeTimeSpanString(t).toString(); + } + } + } + mB.clearAgps.setEnabled(hasFineLocPerm); + mB.lockGps.setEnabled(hasFineLocPerm); + mB.gpsCont.map.setEnabled(locAvailable); + mB.gpsCont.copy.setEnabled(locAvailable); + mB.gpsCont.switchV.setEnabled(hasFineLocPerm); + mB.gpsCont.switchV.setChecked(hasFineLocPerm && SETTINGS.getGpsEnabled()); + mB.gpsCont.stateV.setText(state); + mB.gpsCont.latV.setText(lat); + mB.gpsCont.lngV.setText(lng); + mB.gpsCont.accV.setText(acc); + mB.gpsCont.timeV.setText(time); + mB.gpsCont.satDetail.setEnabled(showSats); + if (!showSats && mSatsDialog != null) { + mSatsDialog.dismissAllowingStateLoss(); + } + + int total, good = 0, used = 0; + synchronized (mSats) { + total = mSats.size(); + for (Sat sat : mSats) { + if (sat.mSnr != 0) { + good++; + } + if (sat.mUsed) { + used++; + } + } + } + + mB.gpsCont.totalSatV.setText(String.valueOf(total)); + mB.gpsCont.goodSatV.setText(String.valueOf(good)); + mB.gpsCont.usedSatV.setText(String.valueOf(used)); + + synchronized (SATS_DIALOG_TAG) { + if (mSatsDialog != null) { + mSatsDialog.submitList(mSats); + } + } + } + + private void updateNetUi() { + String state = null, lat = "--", lng = "--", acc = "--", time = "--"; + boolean hasLocPerm = false, locAvailable = false; + if (!mNetProviderSupported) { + state = getString(R.string.not_supported); + } else { + hasLocPerm = hasCoarseLocPerm() || hasFineLocPerm(); + if (!hasLocPerm) { + state = getString(R.string.perm_not_granted); + } else if (!mLocManager.isProviderEnabled(NETWORK_PROVIDER)) { + state = getString(R.string.turned_off); + } else if (mNetLocation != null + && !isNaN(mNetLocation.getLatitude()) + && !isNaN(mNetLocation.getLongitude())) { + locAvailable = true; + lat = Utils.formatLatLng(mNetLocation.getLatitude()); + lng = Utils.formatLatLng(mNetLocation.getLongitude()); + if (!isNaN(mNetLocation.getAccuracy()) && mNetLocation.getAccuracy() != 0) { + acc = getString(R.string.acc_unit, Utils.formatLocAccuracy(mNetLocation.getAccuracy())); + } + long curr = System.currentTimeMillis(); + long t = mNetLocation.getTime(); + t = t - Math.max(0, t - curr); + time = DateUtils.getRelativeTimeSpanString(t).toString(); + } + } + mB.netCont.map.setEnabled(locAvailable); + mB.netCont.copy.setEnabled(locAvailable); + mB.netCont.switchV.setEnabled(hasLocPerm); + mB.netCont.switchV.setChecked(hasLocPerm && SETTINGS.getNetworkEnabled()); + mB.netCont.stateV.setText(state); + mB.netCont.latV.setText(lat); + mB.netCont.lngV.setText(lng); + mB.netCont.accV.setText(acc); + mB.netCont.timeV.setText(time); + } + + private void updateNlpUi() { + boolean hasLocPerm = hasCoarseLocPerm(); + mB.nlpCont.switchV.setEnabled(hasLocPerm); + mB.nlpCont.switchV.setChecked(hasLocPerm && SETTINGS.getNlpEnabled()); + synchronized (mBackends) { + for (NlpBackend backend : mBackends) { + backend.refresh(); + if (mNlpAdapter != null) { + mNlpAdapter.notifyDataSetChanged(); + } + } + } + } + + private void setGrantPermButtonState() { + if (mB != null) { + if (hasFineLocPerm() && hasCoarseLocPerm()) { + mB.grantPerm.setVisibility(View.GONE); + } else { + mB.grantPerm.setVisibility(View.VISIBLE); + } + } + } + + private SatsDialogFragment mSatsDialog; + private static final String SATS_DIALOG_TAG = "SATELLITES_DETAIL"; + + private void showSatsDialog() { + mSatsDialog = new SatsDialogFragment(); + mSatsDialog.setOnDismissListener( + d -> { + synchronized (SATS_DIALOG_TAG) { + mSatsDialog = null; + } + }); + mSatsDialog.showNow(getSupportFragmentManager(), SATS_DIALOG_TAG); + mSatsDialog.submitList(mSats); + } + + ////////////////////////////////////////////////////////////////// + /////////////////////////// PERM REQUEST ///////////////////////// + ////////////////////////////////////////////////////////////////// + + private void checkPerms() { + List perms = new ArrayList<>(); + if (!hasFineLocPerm()) { + perms.add(permission.ACCESS_FINE_LOCATION); + } + if (!hasCoarseLocPerm()) { + perms.add(permission.ACCESS_COARSE_LOCATION); + } + if (!perms.isEmpty()) { + ActivityCompat.requestPermissions(this, perms.toArray(new String[] {}), 0); + } + } + + @Override + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + List results = new ArrayList<>(); + for (int i : grantResults) { + results.add(i); + } + if (results.contains(PERMISSION_GRANTED)) { + startLocListeners(); + setGrantPermButtonState(); + setTimer(); + } + } + + ////////////////////////////////////////////////////////////////// + ////////////////////////////// OTHER ///////////////////////////// + ////////////////////////////////////////////////////////////////// + + void checkLicense() { + if (mLicenseChecker != null) { + mLicenseChecker.check(); + } + } + + private void clearAGPSData() { + if (hasFineLocPerm()) { + mLocManager.sendExtraCommand(GPS_PROVIDER, "delete_aiding_data", null); + mLocManager.sendExtraCommand(GPS_PROVIDER, "force_time_injection", null); + String command = SDK_INT >= VERSION_CODES.Q ? "force_psds_injection" : "force_xtra_injection"; + mLocManager.sendExtraCommand(GPS_PROVIDER, command, null); + Utils.showShortToast(R.string.cleared); + } + } + + private class LocListener implements LocationListener { + + private final boolean mIsGps; + + private LocListener(boolean isGps) { + mIsGps = isGps; + } + + @Override + public void onLocationChanged(Location location) { + if (mIsGps) { + mGpsLocation = location; + } else { + mNetLocation = location; + } + } + + @Override + public void onProviderEnabled(String provider) { + setTimer(); + } + + @Override + public void onProviderDisabled(String provider) { + if (mIsGps) { + clearGpsData(); + } else { + mNetLocation = null; + } + setTimer(); + } + + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + setTimer(); + } + } + + private class GpsStatusListener implements GpsStatus.Listener { + + @Override + public void onGpsStatusChanged(int event) { + Utils.runBg(MainActivity.this::updateGpsSats); + } + } + + static class Sat { + + final int mPrn; + final boolean mUsed; + final float mSnr; + + Sat(int prn, boolean used, float snr) { + mPrn = prn; + mUsed = used; + mSnr = snr; + if (snr > maxSnr) { + maxSnr = snr + correction; + } else if (snr < minSnr) { + minSnr = snr; + if (minSnr < 0) { + correction = -minSnr; + } + } + } + + static float maxSnr; + private static float minSnr, correction; + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/MySettings.java b/app/src/main/java/com/mirfatif/mylocation/MySettings.java new file mode 100644 index 0000000..98e61bd --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/MySettings.java @@ -0,0 +1,96 @@ +package com.mirfatif.mylocation; + +import static com.mirfatif.mylocation.Utils.getString; + +import android.content.SharedPreferences; +import java.util.concurrent.TimeUnit; + +public class MySettings { + + public static final MySettings SETTINGS = new MySettings(); + + private final SharedPreferences mPrefs; + + private MySettings() { + mPrefs = Utils.getDefPrefs(); + } + + public boolean getBoolPref(int keyResId, boolean defValue) { + String prefKey = getString(keyResId); + return mPrefs.getBoolean(prefKey, defValue); + } + + public int getIntPref(int keyResId, int defValue) { + String prefKey = getString(keyResId); + return mPrefs.getInt(prefKey, defValue); + } + + @SuppressWarnings("SameParameterValue") + private long getLongPref(int keyResId) { + String prefKey = getString(keyResId); + return mPrefs.getLong(prefKey, 0); + } + + public void savePref(int key, boolean bool) { + String prefKey = getString(key); + mPrefs.edit().putBoolean(prefKey, bool).apply(); + } + + public void savePref(int key, int integer) { + String prefKey = getString(key); + mPrefs.edit().putInt(prefKey, integer).apply(); + } + + @SuppressWarnings("SameParameterValue") + private void savePref(int key, long _long) { + String prefKey = getString(key); + mPrefs.edit().putLong(prefKey, _long).apply(); + } + + public boolean getGpsEnabled() { + return mPrefs.getBoolean(getString(R.string.pref_main_gps_enabled_key), true); + } + + public void setGpsEnabled(boolean enabled) { + mPrefs.edit().putBoolean(getString(R.string.pref_main_gps_enabled_key), enabled).apply(); + } + + public boolean getNetworkEnabled() { + return mPrefs.getBoolean(getString(R.string.pref_main_network_enabled_key), true); + } + + public void setNetworkEnabled(boolean enabled) { + mPrefs.edit().putBoolean(getString(R.string.pref_main_network_enabled_key), enabled).apply(); + } + + public boolean getNlpEnabled() { + return mPrefs.getBoolean(getString(R.string.pref_main_nlp_enabled_key), true); + } + + public void setNlpEnabled(boolean enabled) { + mPrefs.edit().putBoolean(getString(R.string.pref_main_nlp_enabled_key), enabled).apply(); + } + + public boolean shouldAskToSendCrashReport() { + int crashCount = getIntPref(R.string.pref_main_crash_report_count_key, 1); + long lastTS = getLongPref(R.string.pref_main_crash_report_ts_key); + long currTime = System.currentTimeMillis(); + + if (crashCount >= 5 || (currTime - lastTS) >= TimeUnit.DAYS.toMillis(1)) { + savePref(R.string.pref_main_crash_report_ts_key, currTime); + savePref(R.string.pref_main_crash_report_count_key, 1); + return true; + } + + savePref(R.string.pref_main_crash_report_count_key, crashCount + 1); + return false; + } + + public boolean getForceDarkMode() { + return getBoolPref(R.string.pref_main_dark_theme_key, true); + } + + public void setForceDarkMode(boolean force) { + savePref(R.string.pref_main_dark_theme_key, force); + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/NlpAdapter.java b/app/src/main/java/com/mirfatif/mylocation/NlpAdapter.java new file mode 100644 index 0000000..187fc18 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/NlpAdapter.java @@ -0,0 +1,138 @@ +package com.mirfatif.mylocation; + +import static com.mirfatif.mylocation.MySettings.SETTINGS; +import static com.mirfatif.mylocation.Utils.getString; +import static com.mirfatif.mylocation.Utils.hasCoarseLocPerm; +import static com.mirfatif.mylocation.Utils.isNaN; +import static com.mirfatif.mylocation.Utils.setTooltip; + +import android.location.Location; +import android.text.format.DateUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; +import com.mirfatif.mylocation.NlpAdapter.NlpViewHolder; +import com.mirfatif.mylocation.databinding.NlpItemBinding; +import java.util.List; + +public class NlpAdapter extends RecyclerView.Adapter { + + private final List mBackends; + private final NlpClickListener mListener; + + NlpAdapter(NlpClickListener listener, List backends) { + mListener = listener; + mBackends = backends; + } + + @NonNull + @Override + public NlpViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + LayoutInflater inflater = LayoutInflater.from(parent.getContext()); + return new NlpViewHolder(NlpItemBinding.inflate(inflater, parent, false)); + } + + @Override + public void onBindViewHolder(@NonNull NlpViewHolder holder, int position) { + holder.bind(position); + } + + @Override + public int getItemCount() { + return mBackends.size(); + } + + protected class NlpViewHolder extends RecyclerView.ViewHolder { + + private final NlpItemBinding mB; + + public NlpViewHolder(NlpItemBinding binding) { + super(binding.getRoot()); + mB = binding; + setTooltip(mB.map); + setTooltip(mB.copy); + mB.map.setOnClickListener( + v -> { + int pos = getBindingAdapterPosition(); + NlpBackend backend; + if (pos != RecyclerView.NO_POSITION + && pos < mBackends.size() + && (backend = mBackends.get(pos)) != null) + mListener.mapClicked(backend.getLocation()); + }); + mB.copy.setOnClickListener( + v -> { + int pos = getBindingAdapterPosition(); + NlpBackend backend; + if (pos != RecyclerView.NO_POSITION + && pos < mBackends.size() + && (backend = mBackends.get(pos)) != null) + mListener.copyClicked(backend.getLocation()); + }); + mB.settings.setOnClickListener( + v -> { + int pos = getBindingAdapterPosition(); + NlpBackend backend; + if (pos != RecyclerView.NO_POSITION + && pos < mBackends.size() + && (backend = mBackends.get(pos)) != null) + mListener.settingsClicked(backend.getPkgName()); + }); + } + + private void bind(int pos) { + NlpBackend backend; + if (pos >= mBackends.size() || (backend = mBackends.get(pos)) == null) { + return; + } + + String state = null, lat = "--", lng = "--", acc = "--", time = "--"; + boolean locAvailable = false; + if (SETTINGS.getNlpEnabled() && hasCoarseLocPerm()) { + if (backend.permsRequired()) { + state = getString(R.string.perm_not_granted); + } else if (backend.failed()) { + state = getString(R.string.failed); + } else { + Location loc = backend.getLocation(); + if (loc != null && !isNaN(loc.getLatitude()) && !isNaN(loc.getLongitude())) { + locAvailable = true; + lat = Utils.formatLatLng(loc.getLatitude()); + lng = Utils.formatLatLng(loc.getLongitude()); + if (!isNaN(loc.getAccuracy()) && loc.getAccuracy() != 0) { + acc = getString(R.string.acc_unit, Utils.formatLocAccuracy(loc.getAccuracy())); + } + long curr = System.currentTimeMillis(); + long t = loc.getTime(); + t = t - Math.max(0, t - curr); + time = DateUtils.getRelativeTimeSpanString(t).toString(); + } + } + } + mB.name.setText(backend.getLabel()); + int vis = state == null ? View.VISIBLE : View.GONE; + mB.map.setVisibility(vis); + mB.copy.setVisibility(vis); + mB.map.setEnabled(locAvailable); + mB.copy.setEnabled(locAvailable); + vis = state == null ? View.GONE : View.VISIBLE; + mB.settings.setVisibility(vis); + mB.stateV.setText(state); + mB.latV.setText(lat); + mB.lngV.setText(lng); + mB.accV.setText(acc); + mB.timeV.setText(time); + } + } + + interface NlpClickListener { + + void mapClicked(Location loc); + + void copyClicked(Location loc); + + void settingsClicked(String pkg); + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/NlpBackend.java b/app/src/main/java/com/mirfatif/mylocation/NlpBackend.java new file mode 100644 index 0000000..727642b --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/NlpBackend.java @@ -0,0 +1,183 @@ +package com.mirfatif.mylocation; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.content.pm.ServiceInfo; +import android.location.Location; +import android.os.IBinder; +import android.os.RemoteException; +import android.util.Log; +import java.util.concurrent.Future; +import org.microg.nlp.api.LocationBackend; +import org.microg.nlp.api.LocationBackend.Stub; +import org.microg.nlp.api.LocationCallback; + +public class NlpBackend { + + private static final String TAG = "NlpBackend"; + + private final ServiceInfo mInfo; + private final String mLabel; + + NlpBackend(ServiceInfo info) { + mInfo = info; + mLabel = info.loadLabel(App.getCxt().getPackageManager()).toString(); + } + + void start() { + Utils.runBg(this::bind); + } + + private SvcConnection mConnection; + private boolean mBound; + private Future mInitializedSetter; + private final Object INITIALIZED_SETTER_WAITER = new Object(); + + private void bind() { + Intent intent = new Intent().setClassName(mInfo.packageName, mInfo.name); + mConnection = new SvcConnection(); + mBound = App.getCxt().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + if (!mBound) { + mConnection = null; + } + + if (mInitializedSetter != null) { + mInitializedSetter.cancel(true); + } + mInitializedSetter = + Utils.runBg( + () -> { + synchronized (INITIALIZED_SETTER_WAITER) { + try { + INITIALIZED_SETTER_WAITER.wait(5000); + mInitialized = true; + } catch (InterruptedException ignored) { + } + } + }); + } + + public String getPkgName() { + return mInfo.packageName; + } + + String getLabel() { + return mLabel; + } + + private Location mLoc; + + Location getLocation() { + return mLoc; + } + + private boolean mInitialized = false; + + boolean failed() { + return mInitialized && (!mBound || !mConnected); + } + + private boolean mPermsRequired; + + boolean permsRequired() { + return mPermsRequired; + } + + private long mLastCall; + + void refresh() { + long curr = System.currentTimeMillis(); + if (((mLoc == null && (curr - mLastCall) > 5000) + || (mLoc != null && (curr - mLastCall) > 30000)) + && mSvc != null + && !failed() + && !mPermsRequired) { + mLastCall = curr; + Utils.runBg( + () -> { + try { + Location loc = mSvc.update(); + if (loc != null) { + mLoc = loc; + } + } catch (RemoteException e) { + Log.e(TAG, mLabel + ": " + e.toString()); + cleanUp(); + } + }); + } + } + + void stop() { + cleanUp(); + if (mInitializedSetter != null) { + mInitializedSetter.cancel(true); + mInitializedSetter = null; + } + mInitialized = false; + } + + private void cleanUp() { + if (mSvc != null) { + try { + mSvc.close(); + } catch (RemoteException ignored) { + } + mSvc = null; + } + if (mConnection != null) { + App.getCxt().unbindService(mConnection); + mConnection = null; + } + mInitialized = true; + mBound = mConnected = false; + mLoc = null; + } + + private LocationBackend mSvc; + private boolean mConnected = false; + + private class SvcConnection implements ServiceConnection { + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + mSvc = Stub.asInterface(service); + try { + mSvc.open(new Callback()); + mPermsRequired = mSvc.getInitIntent() != null; + Location loc = mSvc.update(); + if (loc != null) { + mLoc = loc; + } + mConnected = mInitialized = true; + } catch (RemoteException | SecurityException e) { + Log.e(TAG, mLabel + ": " + e.toString()); + cleanUp(); + } + } + + @Override + public void onServiceDisconnected(ComponentName name) { + mConnected = false; + } + + @Override + public void onBindingDied(ComponentName name) { + cleanUp(); + } + + @Override + public void onNullBinding(ComponentName name) { + cleanUp(); + } + } + + private class Callback extends LocationCallback.Stub { + + @Override + public void report(Location location) { + mLoc = location; + } + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/NotifDismissSvc.java b/app/src/main/java/com/mirfatif/mylocation/NotifDismissSvc.java new file mode 100644 index 0000000..4bb1f6f --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/NotifDismissSvc.java @@ -0,0 +1,41 @@ +package com.mirfatif.mylocation; + +import android.app.NotificationManager; +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +public class NotifDismissSvc extends Service { + + public static final String EXTRA_INTENT_TYPE = BuildConfig.APPLICATION_ID + ".extra.INTENT_TYPE"; + public static final String EXTRA_NOTIF_ID = BuildConfig.APPLICATION_ID + ".extra.NOTIF_ID"; + public static final int INTENT_TYPE_ACTIVITY = 1; + public static final int INTENT_TYPE_SERVICE = 2; + private static final int NONE = -1; + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + int type = intent.getIntExtra(EXTRA_INTENT_TYPE, NONE); + int id = intent.getIntExtra(EXTRA_NOTIF_ID, NONE); + if (type != NONE && id != NONE) { + NotificationManager.from(App.getCxt()).cancel(id); + intent.setComponent(null); + intent.removeExtra(EXTRA_INTENT_TYPE); + intent.removeExtra(EXTRA_NOTIF_ID); + if (type == INTENT_TYPE_ACTIVITY) { + // FLAG_ACTIVITY_NEW_TASK is required to start Activity from outside an Activity + intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + } else if (type == INTENT_TYPE_SERVICE) { + startService(intent); + } + } + stopSelf(startId); // Stop if no pending requests + return Service.START_NOT_STICKY; + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/SatAdapter.java b/app/src/main/java/com/mirfatif/mylocation/SatAdapter.java new file mode 100644 index 0000000..19ac579 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/SatAdapter.java @@ -0,0 +1,80 @@ +package com.mirfatif.mylocation; + +import android.content.res.ColorStateList; +import android.graphics.Color; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import androidx.annotation.NonNull; +import androidx.core.graphics.ColorUtils; +import androidx.recyclerview.widget.RecyclerView; +import com.mirfatif.mylocation.MainActivity.Sat; +import com.mirfatif.mylocation.SatAdapter.SatViewHolder; +import com.mirfatif.mylocation.databinding.SatItemBinding; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class SatAdapter extends RecyclerView.Adapter { + + private final List mSats = new ArrayList<>(); + + void submitList(List sats) { + synchronized (mSats) { + mSats.clear(); + mSats.addAll(sats); + notifyDataSetChanged(); + } + } + + @Override + public int getItemCount() { + return mSats.size(); + } + + @NonNull + @Override + public SatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + LayoutInflater inflater = LayoutInflater.from(parent.getContext()); + return new SatViewHolder(SatItemBinding.inflate(inflater, parent, false)); + } + + @Override + public void onBindViewHolder(@NonNull SatViewHolder holder, int position) { + holder.bind(position); + } + + protected class SatViewHolder extends RecyclerView.ViewHolder { + + private final SatItemBinding mB; + + public SatViewHolder(@NonNull SatItemBinding binding) { + super(binding.getRoot()); + mB = binding; + } + + private void bind(int pos) { + Sat sat; + if (pos >= mSats.size() || (sat = mSats.get(pos)) == null) { + return; + } + mB.idV.setText(String.valueOf(sat.mPrn)); + + int strength = Math.min((int) (100 * sat.mSnr / Sat.maxSnr), 100); + if (strength < 5) { + strength = ThreadLocalRandom.current().nextInt(0, 3); + } + mB.progV.setProgress(strength); + float ratio = Math.max(Math.min((float) strength / 100, 1), 0); + int color = ColorUtils.blendARGB(Color.RED, Color.GREEN, ratio); + mB.progV.setProgressTintList(ColorStateList.valueOf(color)); + + mB.signalV.setText(String.valueOf(sat.mSnr)); + if (sat.mUsed) { + mB.fixedV.setVisibility(View.VISIBLE); + } else { + mB.fixedV.setVisibility(View.GONE); + } + } + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/SatsDialogFragment.java b/app/src/main/java/com/mirfatif/mylocation/SatsDialogFragment.java new file mode 100644 index 0000000..357fbf3 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/SatsDialogFragment.java @@ -0,0 +1,65 @@ +package com.mirfatif.mylocation; + +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnDismissListener; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AlertDialog.Builder; +import androidx.appcompat.app.AppCompatDialogFragment; +import androidx.recyclerview.widget.DividerItemDecoration; +import androidx.recyclerview.widget.LinearLayoutManager; +import com.mirfatif.mylocation.MainActivity.Sat; +import com.mirfatif.mylocation.databinding.RvSatsBinding; +import java.util.List; + +public class SatsDialogFragment extends AppCompatDialogFragment { + + public SatsDialogFragment() {} + + private MainActivity mA; + + @Override + public void onAttach(@NonNull Context context) { + super.onAttach(context); + mA = (MainActivity) getActivity(); + } + + private SatAdapter mAdapter; + + synchronized void submitList(List satList) { + mAdapter.submitList(satList); + } + + @NonNull + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + RvSatsBinding b = RvSatsBinding.inflate(mA.getLayoutInflater()); + + mAdapter = new SatAdapter(); + b.rv.setAdapter(mAdapter); + LinearLayoutManager layoutManager = new LinearLayoutManager(mA); + b.rv.setLayoutManager(layoutManager); + b.rv.addItemDecoration(new DividerItemDecoration(mA, DividerItemDecoration.VERTICAL)); + + AlertDialog d = new Builder(mA).setTitle(R.string.satellites).setView(b.getRoot()).create(); + return Utils.setDialogBg(d); + } + + // We cannot use Dialog's OnDismiss and OnCancel Listeners, DialogFragment owns them. + private OnDismissListener mDismissListener; + + public void setOnDismissListener(OnDismissListener dismissListener) { + mDismissListener = dismissListener; + } + + @Override + public void onDismiss(@NonNull DialogInterface dialog) { + super.onDismiss(dialog); + if (mDismissListener != null) { + mDismissListener.onDismiss(dialog); + } + } +} diff --git a/app/src/main/java/com/mirfatif/mylocation/Utils.java b/app/src/main/java/com/mirfatif/mylocation/Utils.java new file mode 100644 index 0000000..ea40fd1 --- /dev/null +++ b/app/src/main/java/com/mirfatif/mylocation/Utils.java @@ -0,0 +1,480 @@ +package com.mirfatif.mylocation; + +import static android.Manifest.permission.ACCESS_COARSE_LOCATION; +import static android.Manifest.permission.ACCESS_FINE_LOCATION; +import static android.content.pm.PackageManager.PERMISSION_GRANTED; +import static com.mirfatif.mylocation.MySettings.SETTINGS; + +import android.app.Activity; +import android.app.NotificationManager.Importance; +import android.app.PendingIntent; +import android.content.ActivityNotFoundException; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.content.res.Configuration; +import android.location.Location; +import android.net.Uri; +import android.os.Build; +import android.os.Build.VERSION; +import android.os.Build.VERSION_CODES; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.provider.Settings; +import android.util.Log; +import android.view.Window; +import android.widget.ImageView; +import android.widget.Toast; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatDelegate; +import androidx.appcompat.widget.TooltipCompat; +import androidx.browser.customtabs.CustomTabColorSchemeParams; +import androidx.browser.customtabs.CustomTabsIntent; +import androidx.browser.customtabs.CustomTabsService; +import androidx.core.app.ActivityCompat; +import androidx.core.app.NotificationChannelCompat; +import androidx.core.app.NotificationCompat; +import androidx.core.app.NotificationManagerCompat; +import androidx.core.content.FileProvider; +import androidx.security.crypto.EncryptedSharedPreferences; +import androidx.security.crypto.EncryptedSharedPreferences.PrefKeyEncryptionScheme; +import androidx.security.crypto.EncryptedSharedPreferences.PrefValueEncryptionScheme; +import androidx.security.crypto.MasterKey; +import androidx.security.crypto.MasterKey.KeyScheme; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +public class Utils { + + private static final String TAG = "Utils"; + + private Utils() {} + + public static String getString(int resId, Object... args) { + return App.getCxt().getString(resId, args); + } + + public static int getInteger(int resId) { + return App.getCxt().getResources().getInteger(resId); + } + + public static boolean isNaN(double d) { + return d != d; + } + + public static void copyLoc(Location location) { + if (location != null) { + ClipboardManager clipboard = + (ClipboardManager) App.getCxt().getSystemService(Context.CLIPBOARD_SERVICE); + String loc = location.getLatitude() + "," + location.getLongitude(); + ClipData data = ClipData.newPlainText("location", loc); + clipboard.setPrimaryClip(data); + Utils.showShortToast(R.string.copied); + } + } + + public static void openMap(Activity act, Location location) { + if (location != null) { + String loc = location.getLatitude() + "," + location.getLongitude(); + try { + act.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:" + loc + "?q=" + loc))); + } catch (ActivityNotFoundException ignored) { + Utils.showToast(R.string.no_maps_installed); + } + } + } + + public static void openAppSettings(Activity act, String pkg) { + Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); + intent.setData(Uri.parse("package:" + pkg)); + try { + act.startActivity(intent); + } catch (ActivityNotFoundException ignored) { + Utils.showToast(R.string.failed_open_app_settings); + } + } + + public static boolean openWebUrl(Activity activity, String url) { + Intent intent = new Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION); + PackageManager pm = App.getCxt().getPackageManager(); + int flags = VERSION.SDK_INT >= VERSION_CODES.M ? PackageManager.MATCH_ALL : 0; + List infoList = pm.queryIntentServices(intent, flags); + boolean customTabsSupported = !infoList.isEmpty(); + + if (customTabsSupported) { + CustomTabColorSchemeParams colorSchemeParams = + new CustomTabColorSchemeParams.Builder() + .setToolbarColor(App.getRes().getColor(R.color.primary)) + .build(); + CustomTabsIntent customTabsIntent = + new CustomTabsIntent.Builder() + .setShareState(CustomTabsIntent.SHARE_STATE_ON) + .setDefaultColorSchemeParams(colorSchemeParams) + .build(); + customTabsIntent.launchUrl(activity, Uri.parse(url)); + return true; + } + + intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); + intent.addCategory(Intent.CATEGORY_BROWSABLE).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + try { + activity.startActivity(intent); + return true; + } catch (ActivityNotFoundException ignored) { + } + + if (VERSION.SDK_INT >= VERSION_CODES.R) { + intent.setFlags(Intent.FLAG_ACTIVITY_REQUIRE_NON_BROWSER); + try { + activity.startActivity(intent); + return true; + } catch (ActivityNotFoundException ignored) { + } + } + + showToast(R.string.no_browser_installed); + return true; + } + + public static void sendMail(Activity activity, String body) { + Intent emailIntent = new Intent(Intent.ACTION_SENDTO).setData(Uri.parse("mailto:")); + emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {getString(R.string.email_address)}); + emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name)); + if (body != null) { + emailIntent.putExtra(Intent.EXTRA_TEXT, body); + } + try { + activity.startActivity(emailIntent); + } catch (ActivityNotFoundException e) { + showToast(R.string.no_email_app_installed); + } + } + + ////////////////////////////////////////////////////////////////// + /////////////////////////// FORMATTING /////////////////////////// + ////////////////////////////////////////////////////////////////// + + private static final DecimalFormat mLatLngFormat = new DecimalFormat(); + + static { + mLatLngFormat.setMaximumFractionDigits(5); + } + + public static String formatLatLng(double coordinate) { + return mLatLngFormat.format(coordinate); + } + + public static String formatLocAccuracy(float accuracy) { + return String.format(Locale.getDefault(), "%.0f", accuracy); + } + + public static String getDeviceInfo() { + return "Version: " + + BuildConfig.VERSION_NAME + + "\nSDK: " + + VERSION.SDK_INT + + "\nROM: " + + Build.DISPLAY + + "\nBuild: " + + Build.TYPE + + "\nDevice: " + + Build.DEVICE + + "\nManufacturer: " + + Build.MANUFACTURER + + "\nModel: " + + Build.MODEL + + "\nProduct: " + + Build.PRODUCT; + } + + public static String getCurrDateTime(boolean spaced) { + if (spaced) { + return new SimpleDateFormat("dd-MMM-yy HH:mm:ss", Locale.ENGLISH) + .format(System.currentTimeMillis()); + } else { + return new SimpleDateFormat("dd-MMM-yy_HH-mm-ss", Locale.ENGLISH) + .format(System.currentTimeMillis()); + } + } + + ////////////////////////////////////////////////////////////////// + ////////////////////////////// PERMS ///////////////////////////// + ////////////////////////////////////////////////////////////////// + + public static boolean hasFineLocPerm() { + return hasPerm(ACCESS_FINE_LOCATION); + } + + public static boolean hasCoarseLocPerm() { + return hasPerm(ACCESS_COARSE_LOCATION); + } + + public static boolean hasPerm(String perm) { + return ActivityCompat.checkSelfPermission(App.getCxt(), perm) == PERMISSION_GRANTED; + } + + public static SharedPreferences getDefPrefs() { + return App.getCxt().getSharedPreferences("def_prefs", Context.MODE_PRIVATE); + } + + private static SharedPreferences mEncPrefs; + private static final Object ENC_PREFS_LOCK = new Object(); + + @SuppressWarnings("UnusedReturnValue") + public static SharedPreferences getEncPrefs() { + synchronized (ENC_PREFS_LOCK) { + if (mEncPrefs != null) { + return mEncPrefs; + } + + for (int i = 0; i < 10; i++) { + try { + mEncPrefs = + EncryptedSharedPreferences.create( + App.getCxt(), + BuildConfig.APPLICATION_ID + "_nb_prefs", + new MasterKey.Builder(App.getCxt()).setKeyScheme(KeyScheme.AES256_GCM).build(), + PrefKeyEncryptionScheme.AES256_SIV, + PrefValueEncryptionScheme.AES256_GCM); + return mEncPrefs; + } catch (Exception e) { + if (i == 9) { + e.printStackTrace(); + } else { + Log.e(TAG, "getEncPrefs: " + e.toString()); + } + SystemClock.sleep(100); + } + } + + // Temp fix for https://github.com/google/tink/issues/413 + mEncPrefs = App.getCxt().getSharedPreferences("_nb_prefs2", Context.MODE_PRIVATE); + return mEncPrefs; + } + } + + ////////////////////////////////////////////////////////////////// + //////////////////////////// EXECUTORS /////////////////////////// + ////////////////////////////////////////////////////////////////// + + private static final Handler UI_EXECUTOR = new Handler(Looper.getMainLooper()); + + public static UiRunnable runUi(Runnable runnable) { + UiRunnable uiRunnable = new UiRunnable(runnable); + UI_EXECUTOR.post(uiRunnable); + return uiRunnable; + } + + public static class UiRunnable implements Runnable { + + private final Runnable mRunnable; + + UiRunnable(Runnable runnable) { + mRunnable = runnable; + } + + @Override + public void run() { + mRunnable.run(); + mDone = true; + synchronized (WAITER) { + WAITER.notify(); + } + } + + private boolean mDone = false; + private final Object WAITER = new Object(); + + public void waitForMe() { + if (Thread.currentThread() == UI_EXECUTOR.getLooper().getThread()) { + Log.e(TAG, "UiRunnable: waitForMe() called on main thread"); + return; + } + synchronized (WAITER) { + while (!mDone) { + try { + WAITER.wait(); + } catch (InterruptedException ignored) { + } + } + } + } + } + + private static final ExecutorService BG_EXECUTOR = Executors.newCachedThreadPool(); + + public static Future runBg(Runnable runnable) { + return BG_EXECUTOR.submit(runnable); + } + + ////////////////////////////////////////////////////////////////// + /////////////////////////////// UI /////////////////////////////// + ////////////////////////////////////////////////////////////////// + + public static void showToast(String msg) { + if (msg != null) { + runUi(() -> showToast(msg, Toast.LENGTH_LONG)); + } + } + + public static void showToast(int resId, Object... args) { + if (resId != 0) { + showToast(getString(resId, args)); + } + } + + public static void showShortToast(int resId, Object... args) { + if (resId != 0) { + runUi(() -> showToast(getString(resId, args), Toast.LENGTH_SHORT)); + } + } + + private static void showToast(String msg, int duration) { + Toast toast = Toast.makeText(App.getCxt(), msg, duration); + toast.show(); + } + + public static void createNotifChannel(String id, String name, @Importance int importance) { + NotificationManagerCompat nm = NotificationManagerCompat.from(App.getCxt()); + NotificationChannelCompat ch = nm.getNotificationChannelCompat(id); + if (ch == null) { + ch = new NotificationChannelCompat.Builder(id, importance).setName(name).build(); + nm.createNotificationChannel(ch); + } + } + + public static void setTooltip(ImageView v) { + TooltipCompat.setTooltipText(v, v.getContentDescription()); + } + + public static boolean isNightMode(Activity activity) { + int uiMode = activity.getResources().getConfiguration().uiMode; + return (uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; + } + + public static boolean setNightTheme(Activity activity) { + if (!SETTINGS.getForceDarkMode()) { + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); + return false; + } + + // Dark Mode applied on whole device + if (isNightMode(activity)) { + return false; + } + + // Dark Mode already applied in app + int defMode = AppCompatDelegate.getDefaultNightMode(); + if (defMode == AppCompatDelegate.MODE_NIGHT_YES) { + return false; + } + + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); + return true; + } + + public static AlertDialog setDialogBg(AlertDialog dialog) { + Window window = dialog.getWindow(); + if (window != null) { + window.setBackgroundDrawableResource(R.drawable.alert_dialog_bg_bordered); + window.setWindowAnimations(android.R.style.Animation_Dialog); + } + return dialog; + } + + ////////////////////////////////////////////////////////////////// + ///////////////////////////// LOGGING //////////////////////////// + ////////////////////////////////////////////////////////////////// + + private static final Object CRASH_LOG_LOCK = new Object(); + + public static void writeCrashLog(String stackTrace) { + synchronized (CRASH_LOG_LOCK) { + File logFile = new File(App.getCxt().getExternalFilesDir(null), "MyLocation_crash.log"); + boolean append = true; + if (!logFile.exists() + || logFile.length() > 512 * 1024 + || logFile.lastModified() < System.currentTimeMillis() - TimeUnit.DAYS.toMillis(90)) { + append = false; + } + try { + PrintWriter writer = new PrintWriter(new FileWriter(logFile, append)); + writer.println("================================="); + writer.println(getDeviceInfo()); + writer.println("Time: " + getCurrDateTime(true)); + writer.println("Log ID: " + UUID.randomUUID().toString()); + writer.println("================================="); + writer.println(stackTrace); + writer.close(); + showCrashNotification(logFile); + } catch (IOException ignored) { + } + } + } + + private static void showCrashNotification(File logFile) { + if (!SETTINGS.shouldAskToSendCrashReport()) { + return; + } + + String authority = BuildConfig.APPLICATION_ID + ".FileProvider"; + Uri logFileUri = FileProvider.getUriForFile(App.getCxt(), authority, logFile); + + final String CHANNEL_ID = "channel_crash_report"; + final String CHANNEL_NAME = getString(R.string.channel_crash_report); + final int UNIQUE_ID = getInteger(R.integer.channel_crash_report); + + Intent intent = new Intent(Intent.ACTION_SEND); + intent + .setData(logFileUri) + .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + .setType("text/plain") + .putExtra(Intent.EXTRA_EMAIL, new String[] {getString(R.string.email_address)}) + .putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " - Crash Report") + .putExtra(Intent.EXTRA_TEXT, "Find attachment.") + .putExtra(Intent.EXTRA_STREAM, logFileUri); + + // Adding extra information to dismiss notification after the action is tapped + intent + .setClass(App.getCxt(), NotifDismissSvc.class) + .putExtra(NotifDismissSvc.EXTRA_INTENT_TYPE, NotifDismissSvc.INTENT_TYPE_ACTIVITY) + .putExtra(NotifDismissSvc.EXTRA_NOTIF_ID, UNIQUE_ID); + + PendingIntent pi = + PendingIntent.getService( + App.getCxt(), UNIQUE_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT); + createNotifChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManagerCompat.IMPORTANCE_HIGH); + + NotificationCompat.Builder nb = + new NotificationCompat.Builder(App.getCxt(), CHANNEL_ID) + .setSmallIcon(R.drawable.notification_icon) + .setContentTitle(getString(R.string.crash_report)) + .setContentText(getString(R.string.ask_to_report_crash_small)) + .setStyle( + new NotificationCompat.BigTextStyle() + .bigText(getString(R.string.ask_to_report_crash))) + .setContentIntent(pi) + .addAction(0, getString(R.string.send_report), pi) + .setDefaults(NotificationCompat.DEFAULT_LIGHTS) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setAutoCancel(true); + + NotificationManagerCompat.from(App.getCxt()).notify(UNIQUE_ID, nb.build()); + } +} diff --git a/app/src/main/res/drawable-hdpi/app_name.webp b/app/src/main/res/drawable-hdpi/app_name.webp new file mode 100644 index 0000000..b555165 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/app_name.webp differ diff --git a/app/src/main/res/drawable-hdpi/icon.webp b/app/src/main/res/drawable-hdpi/icon.webp new file mode 100644 index 0000000..8165805 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/icon.webp differ diff --git a/app/src/main/res/drawable-xhdpi/app_name.webp b/app/src/main/res/drawable-xhdpi/app_name.webp new file mode 100644 index 0000000..bc7a9b4 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/app_name.webp differ diff --git a/app/src/main/res/drawable-xhdpi/icon.webp b/app/src/main/res/drawable-xhdpi/icon.webp new file mode 100644 index 0000000..0b50b11 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/icon.webp differ diff --git a/app/src/main/res/drawable-xxhdpi/action_bar_icon.webp b/app/src/main/res/drawable-xxhdpi/action_bar_icon.webp new file mode 100644 index 0000000..58ee250 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/action_bar_icon.webp differ diff --git a/app/src/main/res/drawable-xxhdpi/app_name.webp b/app/src/main/res/drawable-xxhdpi/app_name.webp new file mode 100644 index 0000000..a8ae64a Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/app_name.webp differ diff --git a/app/src/main/res/drawable-xxhdpi/icon.webp b/app/src/main/res/drawable-xxhdpi/icon.webp new file mode 100644 index 0000000..8c75d6f Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/icon.webp differ diff --git a/app/src/main/res/drawable/alert_dialog_bg_bordered.xml b/app/src/main/res/drawable/alert_dialog_bg_bordered.xml new file mode 100644 index 0000000..1779355 --- /dev/null +++ b/app/src/main/res/drawable/alert_dialog_bg_bordered.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/bitcoin.xml b/app/src/main/res/drawable/bitcoin.xml new file mode 100644 index 0000000..45b2e0f --- /dev/null +++ b/app/src/main/res/drawable/bitcoin.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/bitcoin_qr_code.webp b/app/src/main/res/drawable/bitcoin_qr_code.webp new file mode 100644 index 0000000..06c5f9e Binary files /dev/null and b/app/src/main/res/drawable/bitcoin_qr_code.webp differ diff --git a/app/src/main/res/drawable/copy.xml b/app/src/main/res/drawable/copy.xml new file mode 100644 index 0000000..579c61e --- /dev/null +++ b/app/src/main/res/drawable/copy.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/dark_mode.xml b/app/src/main/res/drawable/dark_mode.xml new file mode 100644 index 0000000..8e1ac01 --- /dev/null +++ b/app/src/main/res/drawable/dark_mode.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/dollar.xml b/app/src/main/res/drawable/dollar.xml new file mode 100644 index 0000000..a11312c --- /dev/null +++ b/app/src/main/res/drawable/dollar.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/donate.xml b/app/src/main/res/drawable/donate.xml new file mode 100644 index 0000000..7820841 --- /dev/null +++ b/app/src/main/res/drawable/donate.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/email.xml b/app/src/main/res/drawable/email.xml new file mode 100644 index 0000000..bfa837f --- /dev/null +++ b/app/src/main/res/drawable/email.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/github_mark.xml b/app/src/main/res/drawable/github_mark.xml new file mode 100644 index 0000000..c05a644 --- /dev/null +++ b/app/src/main/res/drawable/github_mark.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/app/src/main/res/drawable/info.xml b/app/src/main/res/drawable/info.xml new file mode 100644 index 0000000..8553aae --- /dev/null +++ b/app/src/main/res/drawable/info.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/loc_settings.xml b/app/src/main/res/drawable/loc_settings.xml new file mode 100644 index 0000000..9fff5f1 --- /dev/null +++ b/app/src/main/res/drawable/loc_settings.xml @@ -0,0 +1,13 @@ + + + + diff --git a/app/src/main/res/drawable/lock.xml b/app/src/main/res/drawable/lock.xml new file mode 100644 index 0000000..f0ab1ce --- /dev/null +++ b/app/src/main/res/drawable/lock.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/map.xml b/app/src/main/res/drawable/map.xml new file mode 100644 index 0000000..05b7419 --- /dev/null +++ b/app/src/main/res/drawable/map.xml @@ -0,0 +1,13 @@ + + + + diff --git a/app/src/main/res/drawable/notification_icon.xml b/app/src/main/res/drawable/notification_icon.xml new file mode 100644 index 0000000..370bcab --- /dev/null +++ b/app/src/main/res/drawable/notification_icon.xml @@ -0,0 +1,13 @@ + + + + diff --git a/app/src/main/res/drawable/play_store.xml b/app/src/main/res/drawable/play_store.xml new file mode 100644 index 0000000..33d7199 --- /dev/null +++ b/app/src/main/res/drawable/play_store.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/privacy_policy.xml b/app/src/main/res/drawable/privacy_policy.xml new file mode 100644 index 0000000..ed323e7 --- /dev/null +++ b/app/src/main/res/drawable/privacy_policy.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/progress.xml b/app/src/main/res/drawable/progress.xml new file mode 100644 index 0000000..0489cdf --- /dev/null +++ b/app/src/main/res/drawable/progress.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/drawable/rectangular_border.xml b/app/src/main/res/drawable/rectangular_border.xml new file mode 100644 index 0000000..f497137 --- /dev/null +++ b/app/src/main/res/drawable/rectangular_border.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/src/main/res/drawable/round_border.xml b/app/src/main/res/drawable/round_border.xml new file mode 100644 index 0000000..27bf79a --- /dev/null +++ b/app/src/main/res/drawable/round_border.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/app/src/main/res/drawable/round_button_bg.xml b/app/src/main/res/drawable/round_button_bg.xml new file mode 100644 index 0000000..127b967 --- /dev/null +++ b/app/src/main/res/drawable/round_button_bg.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/round_ripple.xml b/app/src/main/res/drawable/round_ripple.xml new file mode 100644 index 0000000..4abb309 --- /dev/null +++ b/app/src/main/res/drawable/round_ripple.xml @@ -0,0 +1,5 @@ + + + + diff --git a/app/src/main/res/drawable/satellite.xml b/app/src/main/res/drawable/satellite.xml new file mode 100644 index 0000000..c8b34f6 --- /dev/null +++ b/app/src/main/res/drawable/satellite.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/app/src/main/res/drawable/settings.xml b/app/src/main/res/drawable/settings.xml new file mode 100644 index 0000000..69aa928 --- /dev/null +++ b/app/src/main/res/drawable/settings.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/share.xml b/app/src/main/res/drawable/share.xml new file mode 100644 index 0000000..d62d94c --- /dev/null +++ b/app/src/main/res/drawable/share.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/splash_background.xml b/app/src/main/res/drawable/splash_background.xml new file mode 100644 index 0000000..a47c444 --- /dev/null +++ b/app/src/main/res/drawable/splash_background.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/star.xml b/app/src/main/res/drawable/star.xml new file mode 100644 index 0000000..0afc060 --- /dev/null +++ b/app/src/main/res/drawable/star.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/telegram.xml b/app/src/main/res/drawable/telegram.xml new file mode 100644 index 0000000..e863a37 --- /dev/null +++ b/app/src/main/res/drawable/telegram.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/update.xml b/app/src/main/res/drawable/update.xml new file mode 100644 index 0000000..e234018 --- /dev/null +++ b/app/src/main/res/drawable/update.xml @@ -0,0 +1,13 @@ + + + + diff --git a/app/src/main/res/layout/about_dialog.xml b/app/src/main/res/layout/about_dialog.xml new file mode 100644 index 0000000..b59f522 --- /dev/null +++ b/app/src/main/res/layout/about_dialog.xml @@ -0,0 +1,234 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..3adb466 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,68 @@ + + + + + +