├── .gitignore ├── .travis.yml ├── Android.mk ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── settings.gradle ├── unifiednlp-api ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ ├── aidl │ └── org │ │ └── microg │ │ └── nlp │ │ └── api │ │ ├── GeocoderBackend.aidl │ │ ├── LocationBackend.aidl │ │ └── LocationCallback.aidl │ ├── java │ ├── android │ │ └── location │ │ │ └── Address.aidl │ └── org │ │ └── microg │ │ └── nlp │ │ └── api │ │ ├── AbstractBackendHelper.java │ │ ├── AbstractBackendService.java │ │ ├── BluetoothBackendHelper.java │ │ ├── CellBackendHelper.java │ │ ├── Constants.java │ │ ├── GeocoderBackendService.java │ │ ├── HelperLocationBackendService.java │ │ ├── LocationBackendService.java │ │ ├── LocationHelper.java │ │ ├── MPermissionHelperActivity.java │ │ ├── NlpApiConstants.java │ │ ├── VersionUtil.java │ │ └── WiFiBackendHelper.java │ └── res │ └── values │ └── version.xml └── unifiednlp-backend-sample ├── build.gradle └── src └── main ├── AndroidManifest.xml ├── java └── org │ └── microg │ └── nlp │ └── api │ └── sample │ ├── SampleBackendService.java │ ├── SecondSampleService.java │ ├── SecondSettings.java │ └── ThirdSampleService.java └── res ├── drawable └── icon.png └── values └── strings.xml /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | gen/ 3 | local.properties 4 | build.xml 5 | proguard-project.txt 6 | .gradle 7 | build/ 8 | *.iml 9 | .idea/ 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | sudo: false 3 | before_script: 4 | - echo sdk.dir $ANDROID_HOME > local.properties 5 | script: 6 | - jdk_switcher use oraclejdk8 7 | - export TERM=dumb 8 | - export JAVA_OPTS="-XX:+CMSClassUnloadingEnabled -XX:+HeapDumpOnOutOfMemoryError -Xmx2048m" 9 | - ./gradlew build 10 | android: 11 | components: 12 | - tools 13 | - platform-tools 14 | - build-tools-27.0.3 15 | - android-27 16 | - extra-android-m2repository 17 | licenses: 18 | - '.+' 19 | before_install: 20 | - yes | sdkmanager "platforms;android-27" 21 | before_cache: 22 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 23 | cache: 24 | directories: 25 | - $HOME/.gradle/caches/ 26 | - $HOME/.gradle/wrapper/ 27 | -------------------------------------------------------------------------------- /Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir) 2 | include $(CLEAR_VARS) 3 | 4 | LOCAL_MODULE := UnifiedNlpApi 5 | LOCAL_SRC_FILES := $(call all-java-files-under, unifiednlp-api/src/main/java) 6 | LOCAL_SRC_FILES += unifiednlp-api/src/main/aidl/org/microg/nlp/api/LocationBackend.aidl \ 7 | unifiednlp-api/src/main/aidl/org/microg/nlp/api/GeocoderBackend.aidl \ 8 | unifiednlp-api/src/main/aidl/org/microg/nlp/api/LocationCallback.aidl 9 | LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/unifiednlp-api/src/main/aidl 10 | 11 | include $(BUILD_STATIC_JAVA_LIBRARY) 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | UnifiedNlpApi 2 | ============= 3 | This library contains anything needed to build a backend for UnifiedNlp. 4 | 5 | Writing the service 6 | ------------------- 7 | ### The easy way (Location) 8 | Writing a service is fairly easy. Just create a class that extends `org.microg.nlp.api.LocationBackendService`, it provides several methods: 9 | 10 | #### `update()`-method 11 | You'll most likely want to override this method. It is called every time when an application requests a location. 12 | 13 | However, as this method is blocking, you should not do heavy I/O operations (like network) in it. 14 | If your backend uses a remote provider for location retrieval, do requests in an additional thread and return null in `update()`. 15 | On request success, use `report()` to send the new location to the requesting application. 16 | 17 | See JavaDoc for additional information. 18 | 19 | #### `onOpen()`-method and `onClose()`-method 20 | These might be interesting to override too. `onOpen()` is called after UnifiedNlp connected to this backend and `onClose()` is called before connection closure. 21 | This is a good place to initialize or respectively destroy whatever you need during `update()` calls. 22 | 23 | #### `report(Location)`-method 24 | You can call this method every time to report the given location as soon as possible. 25 | 26 | ### The easy way (Geocoding) 27 | Providing a Geocoder is even simpler than a LocationProvider. Extend `org.microg.nlp.api.GeocoderBackendService` and implement the methods `getFromLocation` and `getFromLocationName`. 28 | Both methods reflect a call to the corresponding method in `android.location.Geocoder`. 29 | 30 | ### The flexible way 31 | Instead of using the `LocationBackendService` helper class you can do it by hand. 32 | It's important that your service overrides the `onBind()` method and responds with a `Binder` to the `LocationBackend` interface. 33 | 34 | Advertise your service 35 | ---------------------- 36 | To let UnifiedNlp see your service you need to advertise it by providing the `org.microg.nlp.LOCATION_BACKEND` action. 37 | 38 | For security reasons, you should add an `android:permission` restriction to `android.permission.ACCESS_COARSE_LOCATION`. This ensures only application with access to coarse locations will be able to connect to your service. 39 | 40 | You may want to set `android:icon` and `android:label` to something reasonable, else your applications icon/label are used. 41 | If your backend has settings you can advertise it's activity using the `org.microg.nlp.BACKEND_SETTINGS_ACTIVITY` meta-data so that it is callable from the UnifiedNlp settings. 42 | 43 | A service entry for a backend service could be: 44 | 45 | 50 | 51 | 52 | 53 | 56 | 57 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | google() 21 | } 22 | dependencies { 23 | classpath 'com.android.tools.build:gradle:3.0.1' 24 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1' 25 | } 26 | } 27 | 28 | allprojects { 29 | apply plugin: 'idea' 30 | ext.androidBuildVersionTools = "27.0.3" 31 | } 32 | 33 | def androidCompileSdk() { return 27 } 34 | 35 | def androidTargetSdk() { return 24 } 36 | 37 | def androidMinSdk() { return 9 } 38 | 39 | subprojects { 40 | repositories { 41 | jcenter() 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microg/android_external_UnifiedNlpApi/434a738bf844bb379d4df2c9730ad3fda656bd2a/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2013-2017 microG Project Team 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | #Sat Apr 22 15:09:21 CEST 2017 18 | distributionBase=GRADLE_USER_HOME 19 | distributionPath=wrapper/dists 20 | zipStoreBase=GRADLE_USER_HOME 21 | zipStorePath=wrapper/dists 22 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4.1-all.zip 23 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':unifiednlp-api' 2 | include ':unifiednlp-backend-sample' 3 | -------------------------------------------------------------------------------- /unifiednlp-api/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.library' 18 | 19 | String getMyVersionName() { 20 | def stdout = new ByteArrayOutputStream() 21 | if (rootProject.file("gradlew").exists()) 22 | exec { commandLine 'git', 'describe', '--tags', '--always', '--dirty'; standardOutput = stdout } 23 | else // automatic build system, don't tag dirty 24 | exec { commandLine 'git', 'describe', '--tags', '--always'; standardOutput = stdout } 25 | return stdout.toString().trim().substring(1) 26 | } 27 | 28 | version = getMyVersionName() 29 | 30 | android { 31 | compileSdkVersion androidCompileSdk() 32 | buildToolsVersion "$androidBuildVersionTools" 33 | 34 | defaultConfig { 35 | versionName getMyVersionName() 36 | minSdkVersion androidMinSdk() 37 | targetSdkVersion androidTargetSdk() 38 | } 39 | 40 | compileOptions { 41 | sourceCompatibility JavaVersion.VERSION_1_8 42 | targetCompatibility JavaVersion.VERSION_1_8 43 | } 44 | 45 | lintOptions { 46 | ignore "MissingPermission" 47 | } 48 | } 49 | 50 | dependencies { 51 | } 52 | -------------------------------------------------------------------------------- /unifiednlp-api/gradle.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2013-2017 microG Project Team 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | POM_NAME=UnifiedNlp API 18 | POM_DESCRIPTION=API interfaces and helpers to create backends for UnifiedNlp 19 | 20 | POM_PACKAGING=aar 21 | 22 | POM_URL=https://github.com/microg/android_external_UnifiedNlpApi 23 | 24 | POM_SCM_URL=https://github.com/microg/android_external_UnifiedNlpApi 25 | POM_SCM_CONNECTION=scm:git@github.com:microg/android_external_UnifiedNlpApi.git 26 | POM_SCM_DEV_CONNECTION=scm:git@github.com:microg/android_external_UnifiedNlpApi.git 27 | 28 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 29 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 30 | POM_LICENCE_DIST=repo 31 | 32 | POM_DEVELOPER_ID=mar-v-in 33 | POM_DEVELOPER_NAME=Marvin W 34 | 35 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 19 | 20 | 21 | 24 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/aidl/org/microg/nlp/api/GeocoderBackend.aidl: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api; 2 | 3 | import android.content.Intent; 4 | import android.location.Location; 5 | import android.location.Address; 6 | 7 | interface GeocoderBackend { 8 | void open(); 9 | List
getFromLocation(double latitude, double longitude, int maxResults, String locale); 10 | List
getFromLocationName(String locationName, int maxResults, double lowerLeftLatitude, 11 | double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude, 12 | String locale); 13 | void close(); 14 | Intent getInitIntent(); 15 | Intent getSettingsIntent(); 16 | Intent getAboutIntent(); 17 | } 18 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/aidl/org/microg/nlp/api/LocationBackend.aidl: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api; 2 | 3 | import org.microg.nlp.api.LocationCallback; 4 | import android.content.Intent; 5 | import android.location.Location; 6 | 7 | interface LocationBackend { 8 | void open(LocationCallback callback); 9 | Location update(); 10 | void close(); 11 | Intent getInitIntent(); 12 | Intent getSettingsIntent(); 13 | Intent getAboutIntent(); 14 | } 15 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/aidl/org/microg/nlp/api/LocationCallback.aidl: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api; 2 | 3 | import android.location.Location; 4 | 5 | interface LocationCallback { 6 | void report(in Location location); 7 | } 8 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/android/location/Address.aidl: -------------------------------------------------------------------------------- 1 | package android.location; 2 | parcelable Address; 3 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/AbstractBackendHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.content.Context; 20 | 21 | public class AbstractBackendHelper { 22 | protected final Context context; 23 | protected State state = State.DISABLED; 24 | protected boolean currentDataUsed = true; 25 | 26 | public AbstractBackendHelper(Context context) { 27 | if (context == null) 28 | throw new IllegalArgumentException("context must not be null"); 29 | this.context = context; 30 | } 31 | 32 | /** 33 | * Call this in {@link org.microg.nlp.api.LocationBackendService#onOpen()}. 34 | */ 35 | public synchronized void onOpen() { 36 | if (state == State.WAITING || state == State.SCANNING) 37 | throw new IllegalStateException("Do not call onOpen if not closed before"); 38 | currentDataUsed = true; 39 | state = State.WAITING; 40 | } 41 | 42 | /** 43 | * Call this in {@link org.microg.nlp.api.LocationBackendService#onClose()}. 44 | */ 45 | public synchronized void onClose() { 46 | if (state == State.DISABLED || state == State.DISABLING) 47 | throw new IllegalStateException("Do not call onClose if not opened before"); 48 | if (state == State.WAITING) { 49 | state = State.DISABLED; 50 | } else { 51 | state = State.DISABLING; 52 | } 53 | } 54 | 55 | /** 56 | * Call this in {@link org.microg.nlp.api.LocationBackendService#update()}. 57 | */ 58 | public synchronized void onUpdate() { 59 | } 60 | 61 | public String[] getRequiredPermissions() { 62 | return new String[0]; 63 | } 64 | 65 | protected enum State {DISABLED, WAITING, SCANNING, DISABLING} 66 | } 67 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/AbstractBackendService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.app.Service; 20 | import android.content.Intent; 21 | import android.os.IBinder; 22 | 23 | public abstract class AbstractBackendService extends Service { 24 | 25 | @Override 26 | public IBinder onBind(Intent intent) { 27 | return getBackend(); 28 | } 29 | 30 | /** 31 | * Called after a connection was setup 32 | */ 33 | protected void onOpen() { 34 | 35 | } 36 | 37 | /** 38 | * Called before connection closure 39 | */ 40 | protected void onClose() { 41 | 42 | } 43 | 44 | protected Intent getInitIntent() { 45 | return null; 46 | } 47 | 48 | protected Intent getSettingsIntent() { 49 | return null; 50 | } 51 | 52 | protected Intent getAboutIntent() { 53 | return null; 54 | } 55 | 56 | @Override 57 | public boolean onUnbind(Intent intent) { 58 | disconnect(); 59 | return super.onUnbind(intent); 60 | } 61 | 62 | public abstract void disconnect(); 63 | 64 | protected abstract IBinder getBackend(); 65 | 66 | protected String getServiceApiVersion() { 67 | return VersionUtil.getServiceApiVersion(this); 68 | } 69 | 70 | protected String getSelfApiVersion() { 71 | return VersionUtil.getSelfApiVersion(this); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/BluetoothBackendHelper.java: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api; 2 | 3 | import android.bluetooth.BluetoothAdapter; 4 | import android.bluetooth.BluetoothDevice; 5 | import android.content.BroadcastReceiver; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.content.IntentFilter; 9 | 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | 13 | import static android.Manifest.permission.ACCESS_COARSE_LOCATION; 14 | import static android.Manifest.permission.BLUETOOTH; 15 | import static android.Manifest.permission.BLUETOOTH_ADMIN; 16 | 17 | /** 18 | * Utility class to support backend using Bluetooth for geolocation. 19 | */ 20 | @SuppressWarnings("MissingPermission") 21 | public class BluetoothBackendHelper extends AbstractBackendHelper { 22 | private final static IntentFilter bluetoothBroadcastFilter = 23 | new IntentFilter(); 24 | 25 | private final Listener listener; 26 | private final BluetoothAdapter bluetoothAdapter; 27 | private final Set bluetooths = new HashSet(); 28 | private final BroadcastReceiver bluetoothBroadcastReceiver = new BroadcastReceiver() { 29 | @Override 30 | public void onReceive(Context context, Intent intent) { 31 | String action = intent.getAction(); 32 | if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { 33 | bluetooths.clear(); 34 | } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 35 | onBluetoothChanged(); 36 | } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { 37 | BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 38 | int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE); 39 | Bluetooth bluetoothDiscovered = new Bluetooth(device.getAddress(), device.getName(), rssi); 40 | bluetooths.add(bluetoothDiscovered); 41 | } 42 | } 43 | }; 44 | 45 | public BluetoothBackendHelper(Context context, Listener listener){ 46 | super(context); 47 | if (listener == null) 48 | throw new IllegalArgumentException("listener must not be null"); 49 | this.listener = listener; 50 | this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 51 | bluetoothBroadcastFilter.addAction(BluetoothDevice.ACTION_FOUND); 52 | bluetoothBroadcastFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 53 | bluetoothBroadcastFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 54 | } 55 | 56 | public synchronized void onOpen() { 57 | super.onOpen(); 58 | bluetoothBroadcastFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 59 | bluetoothBroadcastFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 60 | bluetoothBroadcastFilter.addAction(BluetoothDevice.ACTION_FOUND); 61 | context.registerReceiver(bluetoothBroadcastReceiver, bluetoothBroadcastFilter); 62 | } 63 | 64 | public synchronized void onClose() { 65 | super.onClose(); 66 | context.unregisterReceiver(bluetoothBroadcastReceiver); 67 | } 68 | 69 | public synchronized void onUpdate() { 70 | if (!currentDataUsed) { 71 | listener.onBluetoothChanged(getBluetooths()); 72 | } else { 73 | scanBluetooth(); 74 | } 75 | } 76 | 77 | @Override 78 | public String[] getRequiredPermissions() { 79 | return new String[]{BLUETOOTH, BLUETOOTH_ADMIN, ACCESS_COARSE_LOCATION}; 80 | } 81 | 82 | private void onBluetoothChanged() { 83 | if (loadBluetooths()) { 84 | listener.onBluetoothChanged(getBluetooths()); 85 | } 86 | } 87 | 88 | private synchronized boolean scanBluetooth() { 89 | if (state == State.DISABLED) 90 | return false; 91 | if (bluetoothAdapter.isEnabled()) { 92 | state = State.SCANNING; 93 | bluetoothAdapter.startDiscovery(); 94 | return true; 95 | } 96 | return false; 97 | } 98 | 99 | private synchronized boolean loadBluetooths() { 100 | currentDataUsed = false; 101 | if (state == State.DISABLING) 102 | state = State.DISABLED; 103 | switch (state) { 104 | default: 105 | case DISABLED: 106 | return false; 107 | case SCANNING: 108 | state = State.WAITING; 109 | return true; 110 | } 111 | } 112 | 113 | public synchronized Set getBluetooths() { 114 | currentDataUsed = true; 115 | return new HashSet(bluetooths); 116 | } 117 | 118 | public interface Listener { 119 | public void onBluetoothChanged(Set bluetooth); 120 | } 121 | 122 | public static class Bluetooth { 123 | private final String bssid; 124 | private final String name; 125 | private final int rssi; 126 | 127 | public String getBssid() { return bssid; } 128 | 129 | public String getName() {return name; } 130 | 131 | public int getRssi() { return rssi; } 132 | 133 | public Bluetooth(String bssid, String name, int rssi) { 134 | this.bssid = wellFormedMac(bssid); 135 | this.name = name; 136 | this.rssi = rssi; 137 | } 138 | 139 | @Override 140 | public String toString() { 141 | return "Bluetooth{" + 142 | "name=" + name + 143 | ", bssid=" + bssid + 144 | ", rssi=" + rssi + 145 | "}"; 146 | } 147 | } 148 | 149 | /** 150 | * Bring a mac address to the form 01:23:45:AB:CD:EF 151 | * 152 | * @param mac address to be well-formed 153 | * @return well-formed mac address 154 | */ 155 | public static String wellFormedMac(String mac) { 156 | int HEX_RADIX = 16; 157 | int[] bytes = new int[6]; 158 | String[] splitAtColon = mac.split(":"); 159 | if (splitAtColon.length == 6) { 160 | for (int i = 0; i < 6; ++i) { 161 | bytes[i] = Integer.parseInt(splitAtColon[i], HEX_RADIX); 162 | } 163 | } else { 164 | String[] splitAtLine = mac.split("-"); 165 | if (splitAtLine.length == 6) { 166 | for (int i = 0; i < 6; ++i) { 167 | bytes[i] = Integer.parseInt(splitAtLine[i], HEX_RADIX); 168 | } 169 | } else if (mac.length() == 12) { 170 | for (int i = 0; i < 6; ++i) { 171 | bytes[i] = Integer.parseInt(mac.substring(i * 2, (i + 1) * 2), HEX_RADIX); 172 | } 173 | } else if (mac.length() == 17) { 174 | for (int i = 0; i < 6; ++i) { 175 | bytes[i] = Integer.parseInt(mac.substring(i * 3, (i * 3) + 2), HEX_RADIX); 176 | } 177 | } else { 178 | throw new IllegalArgumentException("Can't read this string as mac address"); 179 | } 180 | } 181 | StringBuilder sb = new StringBuilder(); 182 | for (int i = 0; i < 6; ++i) { 183 | String hex = Integer.toHexString(bytes[i]); 184 | if (hex.length() == 1) { 185 | hex = "0" + hex; 186 | } 187 | if (sb.length() != 0) 188 | sb.append(":"); 189 | sb.append(hex); 190 | } 191 | return sb.toString(); 192 | } 193 | 194 | } 195 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/CellBackendHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.os.Build; 22 | import android.os.Handler; 23 | import android.telephony.CellIdentityCdma; 24 | import android.telephony.CellIdentityGsm; 25 | import android.telephony.CellIdentityLte; 26 | import android.telephony.CellIdentityWcdma; 27 | import android.telephony.CellInfo; 28 | import android.telephony.CellInfoCdma; 29 | import android.telephony.CellInfoGsm; 30 | import android.telephony.CellInfoLte; 31 | import android.telephony.CellInfoWcdma; 32 | import android.telephony.CellLocation; 33 | import android.telephony.CellSignalStrengthCdma; 34 | import android.telephony.CellSignalStrengthGsm; 35 | import android.telephony.CellSignalStrengthLte; 36 | import android.telephony.CellSignalStrengthWcdma; 37 | import android.telephony.NeighboringCellInfo; 38 | import android.telephony.PhoneStateListener; 39 | import android.telephony.SignalStrength; 40 | import android.telephony.TelephonyManager; 41 | import android.telephony.cdma.CdmaCellLocation; 42 | import android.telephony.gsm.GsmCellLocation; 43 | 44 | import java.lang.reflect.Field; 45 | import java.util.ArrayList; 46 | import java.util.HashSet; 47 | import java.util.List; 48 | import java.util.Set; 49 | 50 | import static android.Manifest.permission.ACCESS_COARSE_LOCATION; 51 | import static android.Manifest.permission.READ_PHONE_STATE; 52 | 53 | /** 54 | * Utility class to support backends that use Cells for geolocation. 55 | *

56 | * Due to changes in APIs for cell retrieval, this class will only work on Android 4.2+ 57 | * Support for earlier Android versions might be added later... 58 | */ 59 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) 60 | public class CellBackendHelper extends AbstractBackendHelper { 61 | private final Listener listener; 62 | private final TelephonyManager telephonyManager; 63 | private final Set cells = new HashSet(); 64 | private PhoneStateListener phoneStateListener; 65 | private boolean supportsCellInfoChanged = true; 66 | 67 | public static final int MIN_UPDATE_INTERVAL = 30 * 1000; 68 | public static final int FALLBACK_UPDATE_INTERVAL = 5 * 60 * 1000; 69 | private long lastScan = 0; 70 | 71 | /** 72 | * Create a new instance of {@link CellBackendHelper}. Call this in 73 | * {@link LocationBackendService#onCreate()}. 74 | * 75 | * @throws IllegalArgumentException if either context or listener is null. 76 | * @throws IllegalStateException if android version is below 4.2 77 | */ 78 | public CellBackendHelper(Context context, Listener listener) { 79 | super(context); 80 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) 81 | throw new IllegalStateException("Requires Android 4.2+"); 82 | if (listener == null) 83 | throw new IllegalArgumentException("listener must not be null"); 84 | this.listener = listener; 85 | this.telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 86 | } 87 | 88 | private int getMcc() { 89 | try { 90 | return Integer.parseInt(telephonyManager.getNetworkOperator().substring(0, 3)); 91 | } catch (Exception e) { 92 | return -1; 93 | } 94 | } 95 | 96 | private int getMnc() { 97 | try { 98 | return Integer.parseInt(telephonyManager.getNetworkOperator().substring(3)); 99 | } catch (Exception e) { 100 | return -1; 101 | } 102 | } 103 | 104 | private static Cell.CellType getCellType(int networkType) { 105 | switch (networkType) { 106 | case TelephonyManager.NETWORK_TYPE_GPRS: 107 | case TelephonyManager.NETWORK_TYPE_EDGE: 108 | return Cell.CellType.GSM; 109 | case TelephonyManager.NETWORK_TYPE_UMTS: 110 | case TelephonyManager.NETWORK_TYPE_HSDPA: 111 | case TelephonyManager.NETWORK_TYPE_HSUPA: 112 | case TelephonyManager.NETWORK_TYPE_HSPA: 113 | case TelephonyManager.NETWORK_TYPE_HSPAP: 114 | return Cell.CellType.UMTS; 115 | case TelephonyManager.NETWORK_TYPE_LTE: 116 | return Cell.CellType.LTE; 117 | case TelephonyManager.NETWORK_TYPE_EVDO_0: 118 | case TelephonyManager.NETWORK_TYPE_EVDO_A: 119 | case TelephonyManager.NETWORK_TYPE_EVDO_B: 120 | case TelephonyManager.NETWORK_TYPE_1xRTT: 121 | case TelephonyManager.NETWORK_TYPE_EHRPD: 122 | case TelephonyManager.NETWORK_TYPE_IDEN: 123 | return Cell.CellType.CDMA; 124 | } 125 | return null; 126 | } 127 | 128 | @SuppressWarnings("ChainOfInstanceofChecks") 129 | private Cell parseCellInfo(CellInfo info) { 130 | try { 131 | if (info instanceof CellInfoGsm) { 132 | CellIdentityGsm identity = ((CellInfoGsm) info).getCellIdentity(); 133 | if (identity.getMcc() == Integer.MAX_VALUE) return null; 134 | CellSignalStrengthGsm strength = ((CellInfoGsm) info).getCellSignalStrength(); 135 | return new Cell(Cell.CellType.GSM, identity.getMcc(), identity.getMnc(), 136 | identity.getLac(), identity.getCid(), -1, strength.getDbm()); 137 | } else if (info instanceof CellInfoCdma) { 138 | CellIdentityCdma identity = ((CellInfoCdma) info).getCellIdentity(); 139 | CellSignalStrengthCdma strength = ((CellInfoCdma) info).getCellSignalStrength(); 140 | return new Cell(Cell.CellType.CDMA, getMcc(), identity.getSystemId(), 141 | identity.getNetworkId(), identity.getBasestationId(), -1, strength.getDbm()); 142 | } else { 143 | return parceCellInfo18(info); 144 | } 145 | } catch (Exception ignored) { 146 | } 147 | return null; 148 | } 149 | 150 | @SuppressWarnings("ChainOfInstanceofChecks") 151 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 152 | private Cell parceCellInfo18(CellInfo info) { 153 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) return null; 154 | if (info instanceof CellInfoWcdma) { 155 | CellIdentityWcdma identity = ((CellInfoWcdma) info).getCellIdentity(); 156 | if (identity.getMcc() == Integer.MAX_VALUE) return null; 157 | CellSignalStrengthWcdma strength = ((CellInfoWcdma) info).getCellSignalStrength(); 158 | return new Cell(Cell.CellType.UMTS, identity.getMcc(), identity.getMnc(), 159 | identity.getLac(), identity.getCid(), identity.getPsc(), strength.getDbm()); 160 | } else if (info instanceof CellInfoLte) { 161 | CellIdentityLte identity = ((CellInfoLte) info).getCellIdentity(); 162 | if (identity.getMcc() == Integer.MAX_VALUE) return null; 163 | CellSignalStrengthLte strength = ((CellInfoLte) info).getCellSignalStrength(); 164 | return new Cell(Cell.CellType.LTE, identity.getMcc(), identity.getMnc(), 165 | identity.getTac(), identity.getCi(), identity.getPci(), strength.getDbm()); 166 | } 167 | return null; 168 | } 169 | 170 | private Cell parseCellInfo(NeighboringCellInfo info) { 171 | try { 172 | if (getCellType(info.getNetworkType()) != Cell.CellType.GSM) return null; 173 | return new Cell(Cell.CellType.GSM, getMcc(), getMnc(), info.getLac(), info.getCid(), 174 | info.getPsc(), info.getRssi()); 175 | } catch (Exception ignored) { 176 | } 177 | return null; 178 | } 179 | 180 | private void onCellsChanged(List cellInfo) { 181 | lastScan = System.currentTimeMillis(); 182 | if (loadCells(cellInfo)) { 183 | listener.onCellsChanged(getCells()); 184 | } 185 | } 186 | 187 | /** 188 | * This will fix empty MNC since Android 9 with 0-prefixed MNCs. 189 | * Issue: https://issuetracker.google.com/issues/113560852 190 | */ 191 | private void fixEmptyMnc(List cellInfo) { 192 | if (Build.VERSION.SDK_INT < 28 || cellInfo == null) { 193 | return; 194 | } 195 | 196 | String networkOperator = telephonyManager.getNetworkOperator(); 197 | 198 | if (networkOperator.length() < 5 || networkOperator.charAt(3) != '0') { 199 | return; 200 | } 201 | 202 | String mnc = networkOperator.substring(3); 203 | 204 | for (CellInfo info : cellInfo) { 205 | if (!info.isRegistered()) { 206 | continue; 207 | } 208 | 209 | Object identity = null; 210 | 211 | if (info instanceof CellInfoGsm) { 212 | identity = ((CellInfoGsm) info).getCellIdentity(); 213 | } else if (info instanceof CellInfoWcdma) { 214 | identity = ((CellInfoWcdma) info).getCellIdentity(); 215 | } else if (info instanceof CellInfoLte) { 216 | identity = ((CellInfoLte) info).getCellIdentity(); 217 | } 218 | 219 | if (identity == null) { 220 | continue; 221 | } 222 | 223 | try { 224 | Field mncField = identity.getClass().getSuperclass().getDeclaredField("mMncStr"); 225 | mncField.setAccessible(true); 226 | if (mncField.get(identity) == null) { 227 | mncField.set(identity, mnc); 228 | } 229 | } catch (NoSuchFieldException | IllegalAccessException ignored) { 230 | 231 | } 232 | } 233 | } 234 | 235 | /** 236 | * This will fix values returned by {@link TelephonyManager#getAllCellInfo()} as described 237 | * here: https://github.com/mozilla/ichnaea/issues/340 238 | */ 239 | @SuppressWarnings({"ChainOfInstanceofChecks", "MagicNumber"}) 240 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 241 | private void fixAllCellInfo(List cellInfo) { 242 | if (cellInfo == null) return; 243 | String networkOperator = telephonyManager.getNetworkOperator(); 244 | if (networkOperator.length() != 5) return; 245 | int realMnc = Integer.parseInt(networkOperator.substring(3)); 246 | boolean theBug = false; 247 | for (CellInfo info : cellInfo) { 248 | if (info instanceof CellInfoCdma) return; 249 | if (info.isRegistered()) { 250 | Cell cell = parseCellInfo(info); 251 | if (cell == null) continue; 252 | int infoMnc = cell.getMnc(); 253 | if (infoMnc == (realMnc * 10 + 15)) { 254 | theBug = true; 255 | } 256 | } 257 | } 258 | if (theBug) { 259 | for (CellInfo info : cellInfo) { 260 | Object identity = null; 261 | if (info instanceof CellInfoGsm) 262 | identity = ((CellInfoGsm) info).getCellIdentity(); 263 | else if (info instanceof CellInfoLte) 264 | identity = ((CellInfoLte) info).getCellIdentity(); 265 | else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && 266 | info instanceof CellInfoWcdma) 267 | identity = ((CellInfoWcdma) info).getCellIdentity(); 268 | if (identity == null) continue; 269 | try { 270 | Field mncField = identity.getClass().getDeclaredField("mMnc"); 271 | mncField.setAccessible(true); 272 | int mnc = (Integer) mncField.get(identity); 273 | if (mnc >= 25 && mnc <= 1005) { 274 | mnc = (mnc - 15) / 10; 275 | mncField.setInt(identity, mnc); 276 | } 277 | } catch (Exception ignored) { 278 | } 279 | } 280 | } 281 | } 282 | 283 | private boolean hasCid(long cid) { 284 | for (Cell cell : cells) { 285 | if (cell.getCid() == cid) return true; 286 | } 287 | return false; 288 | } 289 | 290 | /** 291 | * This is to support some broken implementations that do not support {@link TelephonyManager#getAllCellInfo()} 292 | */ 293 | @SuppressWarnings("ChainOfInstanceofChecks") 294 | private CellInfo fromCellLocation(CellLocation cellLocation) { 295 | try { 296 | if (cellLocation instanceof GsmCellLocation) { 297 | GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation; 298 | CellIdentityGsm identity = CellIdentityGsm.class.getConstructor(int.class, int.class, int.class, int.class) 299 | .newInstance(getMcc(), getMnc(), gsmCellLocation.getLac(), gsmCellLocation.getCid()); 300 | CellSignalStrengthGsm strength = CellSignalStrengthGsm.class.newInstance(); 301 | CellInfoGsm info = CellInfoGsm.class.newInstance(); 302 | CellInfoGsm.class.getMethod("setCellIdentity", CellIdentityGsm.class).invoke(info, identity); 303 | CellInfoGsm.class.getMethod("setCellSignalStrength", CellSignalStrengthGsm.class).invoke(info, strength); 304 | return info; 305 | } 306 | if (cellLocation instanceof CdmaCellLocation) { 307 | CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation; 308 | CellIdentityCdma identity = CellIdentityCdma.class.getConstructor(int.class, int.class, int.class, int.class, int.class) 309 | .newInstance(cdmaCellLocation.getNetworkId(), cdmaCellLocation.getSystemId(), cdmaCellLocation.getBaseStationId(), 310 | cdmaCellLocation.getBaseStationLongitude(), cdmaCellLocation.getBaseStationLatitude()); 311 | CellSignalStrengthCdma strength = CellSignalStrengthCdma.class.newInstance(); 312 | CellInfoCdma info = CellInfoCdma.class.newInstance(); 313 | CellInfoCdma.class.getMethod("setCellIdentity", CellIdentityCdma.class).invoke(info, identity); 314 | CellInfoCdma.class.getMethod("setCellSignalStrength", CellSignalStrengthCdma.class).invoke(info, strength); 315 | return info; 316 | } 317 | } catch (Exception e) { 318 | } 319 | return null; 320 | } 321 | 322 | @SuppressWarnings("deprecation") 323 | private synchronized boolean loadCells(List cellInfo) { 324 | cells.clear(); 325 | currentDataUsed = false; 326 | try { 327 | if (cellInfo != null) { 328 | fixEmptyMnc(cellInfo); 329 | fixAllCellInfo(cellInfo); 330 | for (CellInfo info : cellInfo) { 331 | Cell cell = parseCellInfo(info); 332 | if (cell == null) continue; 333 | cells.add(cell); 334 | } 335 | } 336 | List neighboringCellInfo = telephonyManager.getNeighboringCellInfo(); 337 | if (neighboringCellInfo != null) { 338 | for (NeighboringCellInfo info : neighboringCellInfo) { 339 | if (!hasCid(info.getCid())) { 340 | Cell cell = parseCellInfo(info); 341 | if (cell == null) continue; 342 | cells.add(cell); 343 | } 344 | } 345 | } 346 | } catch (Exception ignored) { 347 | } 348 | if (state == State.DISABLING) 349 | state = State.DISABLED; 350 | switch (state) { 351 | default: 352 | case DISABLED: 353 | return false; 354 | case SCANNING: 355 | state = State.WAITING; 356 | return true; 357 | } 358 | } 359 | 360 | public synchronized Set getCells() { 361 | currentDataUsed = true; 362 | return new HashSet(cells); 363 | } 364 | 365 | /** 366 | * Call this in {@link org.microg.nlp.api.LocationBackendService#onOpen()}. 367 | */ 368 | @Override 369 | public synchronized void onOpen() { 370 | super.onOpen(); 371 | 372 | if (phoneStateListener == null) { 373 | Handler mainHandler = new Handler(context.getMainLooper()); 374 | mainHandler.post(new Runnable() { 375 | @Override 376 | public void run() { 377 | phoneStateListener = new PhoneStateListener() { 378 | 379 | @Override 380 | public void onCellInfoChanged(List cellInfo) { 381 | if (cellInfo != null && !cellInfo.isEmpty()) { 382 | onCellsChanged(cellInfo); 383 | } else if (supportsCellInfoChanged) { 384 | supportsCellInfoChanged = false; 385 | onSignalStrengthsChanged(null); 386 | } 387 | } 388 | 389 | @Override 390 | public void onSignalStrengthsChanged(SignalStrength signalStrength) { 391 | if (!supportsCellInfoChanged) { 392 | fallbackScan(); 393 | } 394 | } 395 | }; 396 | registerPhoneStateListener(); 397 | } 398 | }); 399 | } else { 400 | registerPhoneStateListener(); 401 | } 402 | } 403 | 404 | @SuppressWarnings("deprecation") 405 | private synchronized void fallbackScan() { 406 | if (lastScan + MIN_UPDATE_INTERVAL > System.currentTimeMillis()) return; 407 | List allCellInfo = telephonyManager.getAllCellInfo(); 408 | if ((allCellInfo == null || allCellInfo.isEmpty()) && telephonyManager.getNetworkType() > 0) { 409 | allCellInfo = new ArrayList(); 410 | CellLocation cellLocation = telephonyManager.getCellLocation(); 411 | CellInfo cellInfo = fromCellLocation(cellLocation); 412 | if (cellInfo != null) allCellInfo.add(cellInfo); 413 | } 414 | onCellsChanged(allCellInfo); 415 | } 416 | 417 | private synchronized void registerPhoneStateListener() { 418 | try { 419 | telephonyManager.listen(phoneStateListener, 420 | PhoneStateListener.LISTEN_CELL_INFO 421 | | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); 422 | } catch (Exception e) { 423 | // Can't listen 424 | phoneStateListener = null; 425 | } 426 | } 427 | 428 | /** 429 | * Call this in {@link org.microg.nlp.api.LocationBackendService#onClose()}. 430 | */ 431 | @Override 432 | public synchronized void onClose() { 433 | super.onClose(); 434 | if (phoneStateListener != null) 435 | telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); 436 | } 437 | 438 | @Override 439 | public synchronized void onUpdate() { 440 | if (!currentDataUsed) { 441 | listener.onCellsChanged(getCells()); 442 | } else { 443 | state = State.SCANNING; 444 | if (lastScan + FALLBACK_UPDATE_INTERVAL < System.currentTimeMillis()) { 445 | fallbackScan(); 446 | } 447 | } 448 | } 449 | 450 | @Override 451 | public String[] getRequiredPermissions() { 452 | return new String[]{READ_PHONE_STATE, ACCESS_COARSE_LOCATION}; 453 | } 454 | 455 | public interface Listener { 456 | void onCellsChanged(Set cells); 457 | } 458 | 459 | public static class Cell { 460 | private CellType type; 461 | private int mcc; 462 | private int mnc; 463 | private int lac; 464 | private long cid; 465 | private int psc; 466 | private int signal; 467 | 468 | public Cell(CellType type, int mcc, int mnc, int lac, long cid, int psc, int signal) { 469 | if (type == null) 470 | throw new IllegalArgumentException("Each cell has an type!"); 471 | this.type = type; 472 | boolean cdma = type == CellType.CDMA; 473 | if (mcc < 0 || mcc > 999) 474 | throw new IllegalArgumentException("Invalid MCC: " + mcc); 475 | this.mcc = mcc; 476 | if (cdma ? (mnc < 1 || mnc > 32767) : (mnc < 0 || mnc > 999)) 477 | throw new IllegalArgumentException("Invalid MNC: " + mnc); 478 | this.mnc = mnc; 479 | if (lac < 1 || lac > (cdma ? 65534 : 65533)) 480 | throw new IllegalArgumentException("Invalid LAC: " + lac); 481 | this.lac = lac; 482 | if (cid < 0) 483 | throw new IllegalArgumentException("Invalid CID: " + cid); 484 | this.cid = cid; 485 | this.psc = psc; 486 | this.signal = signal; 487 | } 488 | 489 | /** 490 | * @return RSCP for UMTS, RSRP for LTE, RSSI for GSM and CDMA 491 | */ 492 | public int getSignal() { 493 | return signal; 494 | } 495 | 496 | public CellType getType() { 497 | return type; 498 | } 499 | 500 | public int getMcc() { 501 | return mcc; 502 | } 503 | 504 | public int getMnc() { 505 | return mnc; 506 | } 507 | 508 | public int getLac() { 509 | return lac; 510 | } 511 | 512 | public long getCid() { 513 | return cid; 514 | } 515 | 516 | public int getPsc() { 517 | return psc; 518 | } 519 | 520 | @Override 521 | public boolean equals(Object o) { 522 | if (this == o) return true; 523 | if (o == null || getClass() != o.getClass()) return false; 524 | 525 | Cell cell = (Cell) o; 526 | 527 | if (cid != cell.cid) return false; 528 | if (lac != cell.lac) return false; 529 | if (mcc != cell.mcc) return false; 530 | if (mnc != cell.mnc) return false; 531 | if (psc != cell.psc) return false; 532 | if (signal != cell.signal) return false; 533 | if (type != cell.type) return false; 534 | 535 | return true; 536 | } 537 | 538 | @Override 539 | public int hashCode() { 540 | int result = type.hashCode(); 541 | result = 31 * result + mcc; 542 | result = 31 * result + mnc; 543 | result = 31 * result + lac; 544 | result = 31 * result + (int) (cid ^ (cid >>> 32)); 545 | result = 31 * result + psc; 546 | result = 31 * result + signal; 547 | return result; 548 | } 549 | 550 | @Override 551 | public String toString() { 552 | return "Cell{" + 553 | "type=" + type + 554 | ", mcc=" + mcc + 555 | ", mnc=" + mnc + 556 | ", lac=" + lac + 557 | ", cid=" + cid + 558 | (psc != -1 ? (", psc=" + psc) : "") + 559 | ", signal=" + signal + 560 | '}'; 561 | } 562 | 563 | public enum CellType {GSM, UMTS, LTE, CDMA} 564 | } 565 | } 566 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | public class Constants { 20 | public static final String ACTION_LOCATION_BACKEND = "org.microg.nlp.LOCATION_BACKEND"; 21 | public static final String ACTION_GEOCODER_BACKEND = "org.microg.nlp.GEOCODER_BACKEND"; 22 | public static final String ACTION_RELOAD_SETTINGS = "org.microg.nlp.RELOAD_SETTINGS"; 23 | public static final String ACTION_FORCE_LOCATION = "org.microg.nlp.FORCE_LOCATION"; 24 | public static final String PERMISSION_FORCE_LOCATION = "org.microg.permission.FORCE_COARSE_LOCATION"; 25 | public static final String INTENT_EXTRA_LOCATION = "location"; 26 | public static final String LOCATION_EXTRA_BACKEND_PROVIDER = "SERVICE_BACKEND_PROVIDER"; 27 | public static final String LOCATION_EXTRA_BACKEND_COMPONENT = "SERVICE_BACKEND_COMPONENT"; 28 | public static final String LOCATION_EXTRA_OTHER_BACKENDS = "OTHER_BACKEND_RESULTS"; 29 | public static final String METADATA_BACKEND_SETTINGS_ACTIVITY = "org.microg.nlp.BACKEND_SETTINGS_ACTIVITY"; 30 | public static final String METADATA_BACKEND_ABOUT_ACTIVITY = "org.microg.nlp.BACKEND_ABOUT_ACTIVITY"; 31 | public static final String METADATA_BACKEND_INIT_ACTIVITY = "org.microg.nlp.BACKEND_INIT_ACTIVITY"; 32 | public static final String METADATA_BACKEND_SUMMARY = "org.microg.nlp.BACKEND_SUMMARY"; 33 | public static final String METADATA_API_VERSION = "org.microg.nlp.API_VERSION"; 34 | public static final String API_VERSION = "2"; 35 | } 36 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/GeocoderBackendService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.content.Intent; 20 | import android.location.Address; 21 | import android.os.IBinder; 22 | import android.os.RemoteException; 23 | 24 | import java.util.List; 25 | 26 | public abstract class GeocoderBackendService extends AbstractBackendService { 27 | 28 | private final Backend backend = new Backend(); 29 | private boolean connected = false; 30 | 31 | @Override 32 | protected IBinder getBackend() { 33 | return backend; 34 | } 35 | 36 | @Override 37 | public void disconnect() { 38 | if (connected) { 39 | onClose(); 40 | connected = false; 41 | } 42 | } 43 | 44 | /** 45 | * @param locale The locale, formatted as a String with underscore (eg. en_US) the resulting 46 | * address should be localized in 47 | * @see android.location.Geocoder#getFromLocation(double, double, int) 48 | */ 49 | protected abstract List

getFromLocation(double latitude, double longitude, 50 | int maxResults, String locale); 51 | 52 | /** 53 | * @param locale The locale, formatted as a String with underscore (eg. en_US) the resulting 54 | * address should be localized in 55 | * @see android.location.Geocoder#getFromLocationName(String, int, double, double, double, double) 56 | */ 57 | protected abstract List
getFromLocationName(String locationName, int maxResults, 58 | double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, 59 | double upperRightLongitude, String locale); 60 | 61 | private class Backend extends GeocoderBackend.Stub { 62 | 63 | @Override 64 | public void open() throws RemoteException { 65 | onOpen(); 66 | connected = true; 67 | } 68 | 69 | @Override 70 | public List
getFromLocation(double latitude, double longitude, int maxResults, 71 | String locale) throws RemoteException { 72 | return GeocoderBackendService.this 73 | .getFromLocation(latitude, longitude, maxResults, locale); 74 | } 75 | 76 | @Override 77 | public List
getFromLocationName(String locationName, int maxResults, 78 | double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, 79 | double upperRightLongitude, String locale) throws RemoteException { 80 | return GeocoderBackendService.this 81 | .getFromLocationName(locationName, maxResults, lowerLeftLatitude, 82 | lowerLeftLongitude, upperRightLatitude, upperRightLongitude, locale); 83 | } 84 | 85 | @Override 86 | public void close() throws RemoteException { 87 | disconnect(); 88 | } 89 | 90 | @Override 91 | public Intent getInitIntent() throws RemoteException { 92 | return GeocoderBackendService.this.getInitIntent(); 93 | } 94 | 95 | @Override 96 | public Intent getSettingsIntent() throws RemoteException { 97 | return GeocoderBackendService.this.getSettingsIntent(); 98 | } 99 | 100 | @Override 101 | public Intent getAboutIntent() throws RemoteException { 102 | return GeocoderBackendService.this.getAboutIntent(); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/HelperLocationBackendService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.content.Intent; 20 | import android.content.pm.PackageManager; 21 | import android.location.Location; 22 | import android.os.Build; 23 | import android.util.Log; 24 | 25 | import java.util.Arrays; 26 | import java.util.HashSet; 27 | import java.util.Iterator; 28 | import java.util.LinkedList; 29 | import java.util.List; 30 | import java.util.Set; 31 | 32 | public abstract class HelperLocationBackendService extends LocationBackendService { 33 | 34 | private boolean opened; 35 | private final Set helpers = new HashSet(); 36 | 37 | public synchronized void addHelper(AbstractBackendHelper helper) { 38 | helpers.add(helper); 39 | if (opened) { 40 | helper.onOpen(); 41 | } 42 | } 43 | 44 | public synchronized void removeHelpers() { 45 | if (opened) { 46 | for (AbstractBackendHelper helper : helpers) { 47 | helper.onClose(); 48 | } 49 | } 50 | helpers.clear(); 51 | } 52 | 53 | @Override 54 | protected synchronized void onOpen() { 55 | for (AbstractBackendHelper helper : helpers) { 56 | helper.onOpen(); 57 | } 58 | opened = true; 59 | } 60 | 61 | @Override 62 | protected synchronized void onClose() { 63 | for (AbstractBackendHelper helper : helpers) { 64 | helper.onClose(); 65 | } 66 | opened = false; 67 | } 68 | 69 | @Override 70 | protected synchronized Location update() { 71 | for (AbstractBackendHelper helper : helpers) { 72 | helper.onUpdate(); 73 | } 74 | return null; 75 | } 76 | 77 | @Override 78 | protected Intent getInitIntent() { 79 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 80 | // Consider permissions 81 | List perms = new LinkedList(); 82 | for (AbstractBackendHelper helper : helpers) { 83 | perms.addAll(Arrays.asList(helper.getRequiredPermissions())); 84 | } 85 | for (Iterator iterator = perms.iterator(); iterator.hasNext(); ) { 86 | String perm = iterator.next(); 87 | if (checkSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) { 88 | iterator.remove(); 89 | } 90 | } 91 | if (perms.isEmpty()) return null; 92 | Intent intent = new Intent(this, MPermissionHelperActivity.class); 93 | intent.putExtra(MPermissionHelperActivity.EXTRA_PERMISSIONS, perms.toArray(new String[perms.size()])); 94 | return intent; 95 | } 96 | return super.getInitIntent(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/LocationBackendService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.content.Intent; 20 | import android.location.Location; 21 | import android.os.IBinder; 22 | import android.os.RemoteException; 23 | 24 | public abstract class LocationBackendService extends AbstractBackendService { 25 | 26 | private final Backend backend = new Backend(); 27 | private LocationCallback callback; 28 | private Location waiting; 29 | 30 | /** 31 | * Called, whenever an app requires a location update. This can be a single or a repeated request. 32 | *

33 | * You may return null if your backend has no newer location available then the last one. 34 | * Do not send the same {@link android.location.Location} twice, if it's not based on updated/refreshed data. 35 | *

36 | * You can completely ignore this method (means returning null) if you use {@link #report(android.location.Location)}. 37 | * 38 | * @return a new {@link android.location.Location} instance or null if not available. 39 | */ 40 | protected Location update() { 41 | return null; 42 | } 43 | 44 | /** 45 | * Directly report a {@link android.location.Location} to the requesting apps. Use this if your updates are based 46 | * on environment changes (eg. cell id change). 47 | * 48 | * @param location the new {@link android.location.Location} instance to be send 49 | */ 50 | public void report(Location location) { 51 | if (callback != null) { 52 | try { 53 | callback.report(location); 54 | } catch (android.os.DeadObjectException e) { 55 | waiting = location; 56 | callback = null; 57 | } catch (RemoteException e) { 58 | waiting = location; 59 | } 60 | } else { 61 | waiting = location; 62 | } 63 | } 64 | 65 | /** 66 | * @return true if we're an actively connected backend, false if not 67 | */ 68 | public boolean isConnected() { 69 | return callback != null; 70 | } 71 | 72 | @Override 73 | protected IBinder getBackend() { 74 | return backend; 75 | } 76 | 77 | @Override 78 | public void disconnect() { 79 | if (callback != null) { 80 | onClose(); 81 | callback = null; 82 | } 83 | } 84 | 85 | private class Backend extends LocationBackend.Stub { 86 | @Override 87 | public void open(LocationCallback callback) throws RemoteException { 88 | LocationBackendService.this.callback = callback; 89 | if (waiting != null) { 90 | callback.report(waiting); 91 | waiting = null; 92 | } 93 | onOpen(); 94 | } 95 | 96 | @Override 97 | public Location update() throws RemoteException { 98 | return LocationBackendService.this.update(); 99 | } 100 | 101 | @Override 102 | public void close() throws RemoteException { 103 | disconnect(); 104 | } 105 | 106 | @Override 107 | public Intent getInitIntent() throws RemoteException { 108 | return LocationBackendService.this.getInitIntent(); 109 | } 110 | 111 | @Override 112 | public Intent getSettingsIntent() throws RemoteException { 113 | return LocationBackendService.this.getSettingsIntent(); 114 | } 115 | 116 | @Override 117 | public Intent getAboutIntent() throws RemoteException { 118 | return LocationBackendService.this.getAboutIntent(); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/LocationHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.location.Location; 20 | import android.os.Bundle; 21 | 22 | import java.util.Collection; 23 | 24 | public final class LocationHelper { 25 | public static final String EXTRA_AVERAGED_OF = "AVERAGED_OF"; 26 | public static final String EXTRA_TOTAL_WEIGHT = "org.microg.nlp.TOTAL_WEIGHT"; 27 | public static final String EXTRA_TOTAL_ALTITUDE_WEIGHT = "org.microg.nlp.TOTAL_ALTITUDE_WEIGHT"; 28 | public static final String EXTRA_WEIGHT = "org.microg.nlp.WEIGHT"; 29 | 30 | private LocationHelper() { 31 | } 32 | 33 | public static Location create(String source) { 34 | Location l = new Location(source); 35 | l.setTime(System.currentTimeMillis()); 36 | return l; 37 | } 38 | 39 | public static Location create(String source, double latitude, double longitude, float accuracy) { 40 | Location location = create(source); 41 | location.setLatitude(latitude); 42 | location.setLongitude(longitude); 43 | location.setAccuracy(accuracy); 44 | return location; 45 | } 46 | 47 | public static Location create(String source, double latitude, double longitude, float altitude, Bundle extras) { 48 | Location location = create(source, latitude, longitude, altitude); 49 | location.setExtras(extras); 50 | return location; 51 | } 52 | 53 | public static Location create(String source, double latitude, double longitude, double altitude, float accuracy) { 54 | Location location = create(source, latitude, longitude, accuracy); 55 | location.setAltitude(altitude); 56 | return location; 57 | } 58 | 59 | public static Location create(String source, double latitude, double longitude, double altitude, float accuracy, Bundle extras) { 60 | Location location = create(source, latitude, longitude, altitude, accuracy); 61 | location.setExtras(extras); 62 | return location; 63 | } 64 | 65 | public static Location create(String source, long time) { 66 | Location location = create(source); 67 | location.setTime(time); 68 | return location; 69 | } 70 | 71 | public static Location create(String source, long time, Bundle extras) { 72 | Location location = create(source, time); 73 | location.setExtras(extras); 74 | return location; 75 | } 76 | 77 | public static Location average(String source, Collection locations) { 78 | return weightedAverage(source, locations, LocationBalance.BALANCED, new Bundle()); 79 | } 80 | 81 | public static Location weightedAverage(String source, Collection locations, LocationBalance balance, Bundle extras) { 82 | if (locations == null || locations.isEmpty()) { 83 | return null; 84 | } 85 | double total = 0; 86 | double lat = 0; 87 | double lon = 0; 88 | float acc = 0; 89 | double altTotal = 0; 90 | double alt = 0; 91 | for (Location value : locations) { 92 | if (value != null) { 93 | double weight = balance.getWeight(value); 94 | total += weight; 95 | lat += value.getLatitude() * weight; 96 | lon += value.getLongitude() * weight; 97 | acc += value.getAccuracy() * weight; 98 | if (value.hasAltitude()) { 99 | alt += value.getAltitude(); 100 | altTotal += weight; 101 | } 102 | } 103 | } 104 | if (extras == null) extras = new Bundle(); 105 | extras.putInt(EXTRA_AVERAGED_OF, locations.size()); 106 | extras.putDouble(EXTRA_TOTAL_WEIGHT, total); 107 | if (altTotal > 0) { 108 | extras.putDouble(EXTRA_TOTAL_ALTITUDE_WEIGHT, altTotal); 109 | return create(source, lat / total, lon / total, alt / altTotal, (float) (acc / total), extras); 110 | } else { 111 | return create(source, lat / total, lon / total, (float) (acc / total), extras); 112 | } 113 | } 114 | 115 | public interface LocationBalance { 116 | LocationBalance BALANCED = new LocationBalance() { 117 | @Override 118 | public double getWeight(Location location) { 119 | return 1; 120 | } 121 | }; 122 | LocationBalance FROM_EXTRA = new LocationBalance() { 123 | @Override 124 | public double getWeight(Location location) { 125 | return location.getExtras() == null ? 1 : location.getExtras().getDouble(EXTRA_WEIGHT, 1); 126 | } 127 | }; 128 | 129 | double getWeight(Location location); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/MPermissionHelperActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.annotation.TargetApi; 20 | import android.app.Activity; 21 | import android.content.pm.PackageManager; 22 | import android.os.Build; 23 | import android.os.Bundle; 24 | 25 | @TargetApi(Build.VERSION_CODES.M) 26 | public class MPermissionHelperActivity extends Activity { 27 | public static final String EXTRA_PERMISSIONS = "org.microg.nlp.api.mperms"; 28 | private static final int REQUEST_CODE_PERMS = 1; 29 | 30 | @Override 31 | protected void onCreate(Bundle savedInstanceState) { 32 | super.onCreate(savedInstanceState); 33 | String[] mperms = getIntent().getStringArrayExtra(EXTRA_PERMISSIONS); 34 | if (mperms == null || mperms.length == 0) { 35 | setResult(RESULT_OK); 36 | finish(); 37 | } else { 38 | requestPermissions(mperms, REQUEST_CODE_PERMS); 39 | } 40 | } 41 | 42 | @Override 43 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 44 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 45 | boolean ok = true; 46 | for (int result : grantResults) { 47 | if (result != PackageManager.PERMISSION_GRANTED) ok = false; 48 | } 49 | setResult(ok ? RESULT_OK : RESULT_CANCELED); 50 | finish(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/NlpApiConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | /** 20 | * Use {@link Constants} instead. 21 | */ 22 | @Deprecated 23 | public class NlpApiConstants { 24 | public static final String ACTION_LOCATION_BACKEND = "org.microg.nlp.LOCATION_BACKEND"; 25 | public static final String ACTION_GEOCODER_BACKEND = "org.microg.nlp.GEOCODER_BACKEND"; 26 | public static final String ACTION_RELOAD_SETTINGS = "org.microg.nlp.RELOAD_SETTINGS"; 27 | public static final String ACTION_FORCE_LOCATION = "org.microg.nlp.FORCE_LOCATION"; 28 | public static final String PERMISSION_FORCE_LOCATION = "org.microg.permission.FORCE_COARSE_LOCATION"; 29 | public static final String INTENT_EXTRA_LOCATION = "location"; 30 | public static final String LOCATION_EXTRA_BACKEND_PROVIDER = "SERVICE_BACKEND_PROVIDER"; 31 | public static final String LOCATION_EXTRA_BACKEND_COMPONENT = "SERVICE_BACKEND_COMPONENT"; 32 | public static final String LOCATION_EXTRA_OTHER_BACKENDS = "OTHER_BACKEND_RESULTS"; 33 | public static final String METADATA_BACKEND_SETTINGS_ACTIVITY = "org.microg.nlp.BACKEND_SETTINGS_ACTIVITY"; 34 | public static final String METADATA_BACKEND_ABOUT_ACTIVITY = "org.microg.nlp.BACKEND_ABOUT_ACTIVITY"; 35 | public static final String METADATA_BACKEND_SUMMARY = "org.microg.nlp.BACKEND_SUMMARY"; 36 | } 37 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/VersionUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.content.Context; 20 | import android.content.pm.ApplicationInfo; 21 | import android.content.pm.PackageManager; 22 | import android.util.Log; 23 | 24 | public class VersionUtil { 25 | 26 | public static String getPackageApiVersion(Context context, String packageName) { 27 | PackageManager pm = context.getPackageManager(); 28 | ApplicationInfo applicationInfo; 29 | try { 30 | applicationInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); 31 | } catch (PackageManager.NameNotFoundException e) { 32 | return null; 33 | } 34 | return applicationInfo.metaData == null ? null 35 | : applicationInfo.metaData.getString(Constants.METADATA_API_VERSION); 36 | } 37 | 38 | public static String getServiceApiVersion(Context context) { 39 | String apiVersion = getPackageApiVersion(context, "com.google.android.gms"); 40 | return apiVersion != null ? apiVersion 41 | : getPackageApiVersion(context, "com.google.android.location"); 42 | } 43 | 44 | public static String getSelfApiVersion(Context context) { 45 | String apiVersion = getPackageApiVersion(context, context.getPackageName()); 46 | if (!Constants.API_VERSION.equals(apiVersion)) { 47 | Log.w("VersionUtil", "You did not specify the currently used api version in your manifest.\n" + 48 | "When using gradle + aar, this should be done automatically, if not, add the\n" + 49 | "following to your tag\n" + 50 | ""); 52 | apiVersion = Constants.API_VERSION; 53 | } 54 | return apiVersion; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/java/org/microg/nlp/api/WiFiBackendHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.microg.nlp.api; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.BroadcastReceiver; 21 | import android.content.Context; 22 | import android.content.Intent; 23 | import android.content.IntentFilter; 24 | import android.net.wifi.ScanResult; 25 | import android.net.wifi.WifiManager; 26 | import android.os.Build; 27 | 28 | import java.util.HashSet; 29 | import java.util.List; 30 | import java.util.Locale; 31 | import java.util.Set; 32 | 33 | import static android.Manifest.permission.ACCESS_COARSE_LOCATION; 34 | import static android.Manifest.permission.ACCESS_WIFI_STATE; 35 | import static android.Manifest.permission.CHANGE_WIFI_STATE; 36 | 37 | /** 38 | * Utility class to support backends that use Wi-Fis for geolocation. 39 | */ 40 | @SuppressWarnings("MissingPermission") 41 | public class WiFiBackendHelper extends AbstractBackendHelper { 42 | private final static IntentFilter wifiBroadcastFilter = 43 | new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 44 | 45 | private final Listener listener; 46 | private final WifiManager wifiManager; 47 | private final Set wiFis = new HashSet(); 48 | private final BroadcastReceiver wifiBroadcastReceiver = new BroadcastReceiver() { 49 | @Override 50 | public void onReceive(Context context, Intent intent) { 51 | onWiFisChanged(); 52 | } 53 | }; 54 | 55 | private boolean ignoreNomap = true; 56 | 57 | /** 58 | * Create a new instance of {@link WiFiBackendHelper}. Call this in 59 | * {@link LocationBackendService#onCreate()}. 60 | * 61 | * @throws IllegalArgumentException if either context or listener is null. 62 | */ 63 | public WiFiBackendHelper(Context context, Listener listener) { 64 | super(context); 65 | if (listener == null) 66 | throw new IllegalArgumentException("listener must not be null"); 67 | this.listener = listener; 68 | this.wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 69 | } 70 | 71 | /** 72 | * Sets whether to ignore the "_nomap" flag on Wi-Fi SSIDs or not. 73 | *

74 | * Usually, Wi-Fis whose SSID end with "_nomap" are ignored for geolocation. This behaviour can 75 | * be suppressed by {@code setIgnoreNomap(false)}. 76 | *

77 | * Default is {@code true}. 78 | */ 79 | public void setIgnoreNomap(boolean ignoreNomap) { 80 | this.ignoreNomap = ignoreNomap; 81 | } 82 | 83 | /** 84 | * Call this in {@link LocationBackendService#onOpen()}. 85 | */ 86 | public synchronized void onOpen() { 87 | super.onOpen(); 88 | context.registerReceiver(wifiBroadcastReceiver, wifiBroadcastFilter); 89 | } 90 | 91 | /** 92 | * Call this in {@link LocationBackendService#onClose()}. 93 | */ 94 | public synchronized void onClose() { 95 | super.onClose(); 96 | context.unregisterReceiver(wifiBroadcastReceiver); 97 | } 98 | 99 | /** 100 | * Call this in {@link LocationBackendService#update()}. 101 | */ 102 | public synchronized void onUpdate() { 103 | if (!currentDataUsed) { 104 | listener.onWiFisChanged(getWiFis()); 105 | } else { 106 | scanWiFis(); 107 | } 108 | } 109 | 110 | @Override 111 | public String[] getRequiredPermissions() { 112 | return new String[]{CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, ACCESS_COARSE_LOCATION}; 113 | } 114 | 115 | private void onWiFisChanged() { 116 | if (loadWiFis()) { 117 | listener.onWiFisChanged(getWiFis()); 118 | } 119 | } 120 | 121 | private synchronized boolean scanWiFis() { 122 | if (state == State.DISABLED) 123 | return false; 124 | if (wifiManager.isWifiEnabled() || isScanAlwaysAvailable()) { 125 | state = State.SCANNING; 126 | wifiManager.startScan(); 127 | return true; 128 | } 129 | return false; 130 | } 131 | 132 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 133 | private boolean isScanAlwaysAvailable() { 134 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 135 | && wifiManager.isScanAlwaysAvailable(); 136 | } 137 | 138 | private synchronized boolean loadWiFis() { 139 | wiFis.clear(); 140 | currentDataUsed = false; 141 | List scanResults = wifiManager.getScanResults(); 142 | for (ScanResult scanResult : scanResults) { 143 | if (ignoreNomap && scanResult.SSID.toLowerCase(Locale.US).endsWith("_nomap")) continue; 144 | wiFis.add(new WiFi(scanResult.BSSID, scanResult.level, frequencyToChannel(scanResult.frequency), scanResult.frequency)); 145 | } 146 | if (state == State.DISABLING) 147 | state = State.DISABLED; 148 | switch (state) { 149 | default: 150 | case DISABLED: 151 | return false; 152 | case SCANNING: 153 | state = State.WAITING; 154 | return true; 155 | } 156 | } 157 | 158 | @SuppressWarnings("MagicNumber") 159 | private static int frequencyToChannel(int freq) { 160 | if (freq >= 2412 && freq <= 2484) { 161 | return (freq - 2412) / 5 + 1; 162 | } else if (freq >= 5170 && freq <= 5825) { 163 | return (freq - 5170) / 5 + 34; 164 | } else { 165 | return -1; 166 | } 167 | } 168 | 169 | /** 170 | * @return the latest scan result. 171 | */ 172 | public synchronized Set getWiFis() { 173 | currentDataUsed = true; 174 | return new HashSet(wiFis); 175 | } 176 | 177 | /** 178 | * Interface to listen for Wi-Fi scan results. 179 | */ 180 | public interface Listener { 181 | /** 182 | * Called when a new set of Wi-Fi's is discovered. 183 | */ 184 | public void onWiFisChanged(Set wiFis); 185 | } 186 | 187 | /** 188 | * Represents a generic Wi-Fi scan result. 189 | *

190 | * This does contain the BSSID (mac address) and the RSSI (in dBm) of a Wi-Fi. 191 | * Additional data is not provided, but also not usable for geolocation. 192 | */ 193 | public static class WiFi { 194 | private final String bssid; 195 | private final int rssi; 196 | private final int channel; 197 | private final int frequency; 198 | 199 | public String getBssid() { 200 | return bssid; 201 | } 202 | 203 | public int getRssi() { 204 | return rssi; 205 | } 206 | 207 | public int getChannel() { 208 | return channel; 209 | } 210 | 211 | public int getFrequency() { 212 | return frequency; 213 | } 214 | 215 | public WiFi(String bssid, int rssi) { 216 | this(bssid, rssi, -1, -1); 217 | } 218 | 219 | public WiFi(String bssid, int rssi, Integer channel, Integer frequency) { 220 | this.bssid = wellFormedMac(bssid); 221 | this.rssi = rssi; 222 | this.channel = channel; 223 | this.frequency = frequency; 224 | } 225 | } 226 | 227 | /** 228 | * Bring a mac address to the form 01:23:45:AB:CD:EF 229 | * 230 | * @param mac address to be well-formed 231 | * @return well-formed mac address 232 | */ 233 | public static String wellFormedMac(String mac) { 234 | int HEX_RADIX = 16; 235 | int[] bytes = new int[6]; 236 | String[] splitAtColon = mac.split(":"); 237 | if (splitAtColon.length == 6) { 238 | for (int i = 0; i < 6; ++i) { 239 | bytes[i] = Integer.parseInt(splitAtColon[i], HEX_RADIX); 240 | } 241 | } else { 242 | String[] splitAtLine = mac.split("-"); 243 | if (splitAtLine.length == 6) { 244 | for (int i = 0; i < 6; ++i) { 245 | bytes[i] = Integer.parseInt(splitAtLine[i], HEX_RADIX); 246 | } 247 | } else if (mac.length() == 12) { 248 | for (int i = 0; i < 6; ++i) { 249 | bytes[i] = Integer.parseInt(mac.substring(i * 2, (i + 1) * 2), HEX_RADIX); 250 | } 251 | } else if (mac.length() == 17) { 252 | for (int i = 0; i < 6; ++i) { 253 | bytes[i] = Integer.parseInt(mac.substring(i * 3, (i * 3) + 2), HEX_RADIX); 254 | } 255 | } else { 256 | throw new IllegalArgumentException("Can't read this string as mac address"); 257 | 258 | } 259 | } 260 | StringBuilder sb = new StringBuilder(); 261 | for (int i = 0; i < 6; ++i) { 262 | String hex = Integer.toHexString(bytes[i]); 263 | if (hex.length() == 1) { 264 | hex = "0" + hex; 265 | } 266 | if (sb.length() != 0) 267 | sb.append(":"); 268 | sb.append(hex); 269 | } 270 | return sb.toString(); 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /unifiednlp-api/src/main/res/values/version.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 2 19 | -------------------------------------------------------------------------------- /unifiednlp-backend-sample/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013-2017 microG Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.application' 18 | 19 | dependencies { 20 | implementation project(':unifiednlp-api') 21 | } 22 | 23 | android { 24 | compileSdkVersion androidCompileSdk() 25 | buildToolsVersion "$androidBuildVersionTools" 26 | 27 | defaultConfig { 28 | minSdkVersion androidMinSdk() 29 | targetSdkVersion androidTargetSdk() 30 | } 31 | 32 | compileOptions { 33 | sourceCompatibility JavaVersion.VERSION_1_8 34 | targetCompatibility JavaVersion.VERSION_1_8 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /unifiednlp-backend-sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 23 | 24 | 28 | 29 | 34 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 46 | 47 | 50 | 51 | 52 | 56 | 57 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /unifiednlp-backend-sample/src/main/java/org/microg/nlp/api/sample/SampleBackendService.java: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api.sample; 2 | 3 | import android.location.Location; 4 | import android.util.Log; 5 | import org.microg.nlp.api.LocationBackendService; 6 | import org.microg.nlp.api.LocationHelper; 7 | 8 | public class SampleBackendService extends LocationBackendService { 9 | private static final String TAG = SampleBackendService.class.getName(); 10 | 11 | @Override 12 | protected Location update() { 13 | if (System.currentTimeMillis() % 60000 > 2000) { 14 | Log.d(TAG, "I decided not to answer now..."); 15 | return null; 16 | } 17 | Location location = LocationHelper.create("sample", 42, 42, 42); 18 | Log.d(TAG, "I was asked for location and I answer: " + location); 19 | return location; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /unifiednlp-backend-sample/src/main/java/org/microg/nlp/api/sample/SecondSampleService.java: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api.sample; 2 | 3 | import android.location.Location; 4 | import android.util.Log; 5 | import org.microg.nlp.api.LocationBackendService; 6 | import org.microg.nlp.api.LocationHelper; 7 | 8 | public class SecondSampleService extends LocationBackendService { 9 | private static final String TAG = SecondSampleService.class.getName(); 10 | 11 | @Override 12 | protected Location update() { 13 | Location location = LocationHelper.create("second-sample", 13, 13, (System.currentTimeMillis() / 1000) % 100); 14 | Log.d(TAG, "I was asked for location and I answer: " + location); 15 | return location; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /unifiednlp-backend-sample/src/main/java/org/microg/nlp/api/sample/SecondSettings.java: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api.sample; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | 6 | public class SecondSettings extends Activity { 7 | public void onCreate(Bundle savedInstanceState) { 8 | super.onCreate(savedInstanceState); 9 | } 10 | } -------------------------------------------------------------------------------- /unifiednlp-backend-sample/src/main/java/org/microg/nlp/api/sample/ThirdSampleService.java: -------------------------------------------------------------------------------- 1 | package org.microg.nlp.api.sample; 2 | 3 | import android.location.Location; 4 | import android.util.Log; 5 | import org.microg.nlp.api.LocationBackendService; 6 | import org.microg.nlp.api.LocationHelper; 7 | 8 | import java.util.Random; 9 | 10 | public class ThirdSampleService extends LocationBackendService { 11 | private static final String TAG = ThirdSampleService.class.getName(); 12 | 13 | private Thread regular; 14 | private final Random random = new Random(); 15 | 16 | @Override 17 | protected void onOpen() { 18 | super.onOpen(); 19 | regular = new Thread(new Runnable() { 20 | @Override 21 | public void run() { 22 | synchronized (regular) { 23 | while (!regular.isInterrupted()) { 24 | try { 25 | regular.wait(60000); 26 | } catch (InterruptedException e) { 27 | return; 28 | } 29 | Location location = LocationHelper.create("random", random.nextDouble() * 90, random.nextDouble() * 90, random.nextFloat() * 90); 30 | Log.d(TAG, "Just reported: " + location); 31 | report(location); 32 | } 33 | } 34 | } 35 | }); 36 | regular.start(); 37 | } 38 | 39 | @Override 40 | protected void onClose() { 41 | if (regular != null && regular.isAlive()) { 42 | regular.interrupt(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /unifiednlp-backend-sample/src/main/res/drawable/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microg/android_external_UnifiedNlpApi/434a738bf844bb379d4df2c9730ad3fda656bd2a/unifiednlp-backend-sample/src/main/res/drawable/icon.png -------------------------------------------------------------------------------- /unifiednlp-backend-sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | NetworkLocationV2-SamplePlugin 20 | 21 | --------------------------------------------------------------------------------