├── sample ├── .gitignore ├── src │ ├── main │ │ ├── ic_launcher-web.png │ │ ├── res │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── values │ │ │ │ ├── themes.xml │ │ │ │ ├── strings.xml │ │ │ │ └── dimens.xml │ │ │ ├── values-w820dp │ │ │ │ └── dimens.xml │ │ │ ├── menu │ │ │ │ └── menu_main.xml │ │ │ └── layout │ │ │ │ └── activity_main.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── shiftconnects │ │ │ └── sample │ │ │ └── MainActivity.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── shiftconnects │ │ └── sample │ │ └── ApplicationTest.java ├── build.gradle └── proguard-rules.pro ├── location-service ├── .gitignore ├── src │ ├── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── shiftconnects │ │ │ └── android │ │ │ └── location │ │ │ ├── util │ │ │ └── LocationRequestUtils.java │ │ │ ├── MockBackgroundLocationService.java │ │ │ └── BackgroundLocationService.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── shiftconnects │ │ └── android │ │ └── location │ │ └── ApplicationTest.java └── build.gradle ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── RELEASE_NOTES.md ├── gradle.properties ├── .gitignore ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /location-service/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':location-service', ':sample' -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiftconnects/android-location-service/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /sample/src/main/ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiftconnects/android-location-service/HEAD/sample/src/main/ic_launcher-web.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiftconnects/android-location-service/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiftconnects/android-location-service/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /RELEASE_NOTES.md: -------------------------------------------------------------------------------- 1 | v1.3.1 2 | Updated gradle build files for automatic upload to jCenter. 3 | 4 | v1.3.0 5 | This is the initial public release of android-location-services. -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiftconnects/android-location-service/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiftconnects/android-location-service/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiftconnects/android-location-service/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /location-service/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Sample 3 | 4 | Hello world! 5 | Settings 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 10 15:27:10 PDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 5 | 9 | 10 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 21 5 | buildToolsVersion "21.1.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 16 9 | targetSdkVersion 21 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | compile project(":location-service") 24 | compile 'com.android.support:appcompat-v7:21.0.3' 25 | } 26 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/mattruno/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /sample/src/androidTest/java/com/shiftconnects/sample/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright (C) 2015 P100 OG, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package com.shiftconnects.sample; 19 | 20 | import android.app.Application; 21 | import android.test.ApplicationTestCase; 22 | 23 | /** 24 | * Testing Fundamentals 25 | */ 26 | public class ApplicationTest extends ApplicationTestCase { 27 | public ApplicationTest() { 28 | super(Application.class); 29 | } 30 | } -------------------------------------------------------------------------------- /location-service/src/androidTest/java/com/shiftconnects/android/location/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 P100 OG, Inc. 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 com.shiftconnects.android.location; 18 | 19 | import android.app.Application; 20 | import android.test.ApplicationTestCase; 21 | 22 | /** 23 | * Testing Fundamentals 24 | */ 25 | public class ApplicationTest extends ApplicationTestCase { 26 | public ApplicationTest() { 27 | super(Application.class); 28 | } 29 | } -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 26 | 27 | 28 | 29 | 30 | 31 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | 8 | ### Android template 9 | # Built application files 10 | *.apk 11 | *.ap_ 12 | 13 | # Files for the Dalvik VM 14 | *.dex 15 | 16 | # Java class files 17 | *.class 18 | 19 | # Generated files 20 | bin/ 21 | gen/ 22 | 23 | # Gradle files 24 | .gradle/ 25 | build/ 26 | /*/build/ 27 | 28 | # Local configuration file (sdk path, etc) 29 | local.properties 30 | bintray.properties 31 | 32 | # Proguard folder generated by Eclipse 33 | proguard/ 34 | 35 | # Log Files 36 | *.log 37 | 38 | 39 | ### JetBrains template 40 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 41 | 42 | *.iml 43 | 44 | ## Directory-based project format: 45 | .idea/ 46 | # if you remove the above rule, at least ignore the following: 47 | 48 | # User-specific stuff: 49 | # .idea/workspace.xml 50 | # .idea/tasks.xml 51 | # .idea/dictionaries 52 | 53 | # Sensitive or high-churn files: 54 | # .idea/dataSources.ids 55 | # .idea/dataSources.xml 56 | # .idea/sqlDataSources.xml 57 | # .idea/dynamic.xml 58 | # .idea/uiDesigner.xml 59 | 60 | # Gradle: 61 | # .idea/gradle.xml 62 | # .idea/libraries 63 | 64 | # Mongo Explorer plugin: 65 | # .idea/mongoSettings.xml 66 | 67 | ## File-based project format: 68 | *.ipr 69 | *.iws 70 | 71 | ## Plugin-specific files: 72 | 73 | # IntelliJ 74 | out/ 75 | 76 | # mpeltonen/sbt-idea plugin 77 | .idea_modules/ 78 | 79 | # JIRA plugin 80 | atlassian-ide-plugin.xml 81 | 82 | # Crashlytics plugin (for Android Studio and IntelliJ) 83 | com_crashlytics_export_strings.xml 84 | crashlytics.properties 85 | crashlytics-build.properties 86 | 87 | -------------------------------------------------------------------------------- /location-service/src/main/java/com/shiftconnects/android/location/util/LocationRequestUtils.java: -------------------------------------------------------------------------------- 1 | package com.shiftconnects.android.location.util; 2 | 3 | import android.text.format.DateUtils; 4 | 5 | import com.google.android.gms.location.LocationRequest; 6 | 7 | /** 8 | * Various utils to build {@link com.google.android.gms.location.LocationRequest}s 9 | */ 10 | public class LocationRequestUtils { 11 | 12 | public static final float MILES_PER_HOUR_TO_METERS_PER_SECOND = 0.44704f; 13 | 14 | public static LocationRequest byMilesPerHour(float mph, int intervalInSeconds) { 15 | 16 | // convert mph to mps 17 | final float metersPerSecond = MILES_PER_HOUR_TO_METERS_PER_SECOND * mph; 18 | 19 | // convert to requested interval 20 | final float metersPerInterval = metersPerSecond * intervalInSeconds; 21 | 22 | // convert seconds to milliseconds 23 | final long intervalInMillis = intervalInSeconds * DateUtils.SECOND_IN_MILLIS; 24 | 25 | // create the request 26 | return LocationRequest.create() 27 | .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 28 | .setInterval(intervalInMillis) 29 | .setFastestInterval(intervalInMillis) 30 | .setSmallestDisplacement(metersPerInterval); 31 | } 32 | 33 | public static LocationRequest byDisplacement(float smallestDisplacement, long intervalMillis) { 34 | return LocationRequest.create() 35 | .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 36 | .setInterval(intervalMillis) 37 | .setFastestInterval(intervalMillis) 38 | .setSmallestDisplacement(smallestDisplacement); 39 | } 40 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A basic base activity and service for managing location in an Android app. 2 | 3 | Using android-location-activity is as easy as including and starting the background service in the library. 4 | 5 | The ```BackgroundLocationService``` provides a whole suite of useful methods (via callbacks). 6 | 7 | [ ![Download](https://api.bintray.com/packages/inktomi/maven/com.shiftconnects.android.location/images/download.svg) ](https://bintray.com/inktomi/maven/com.shiftconnects.android.location/_latestVersion) 8 | 9 | # To Use / Dependencies 10 | compile('com.shiftconnects.android.location:location-service:1.3.0'){ 11 | transitive=true 12 | } 13 | If you do not wish to pull in our version of the Play Services, feel free to ignore the transitive=true flag. If you do this, you will need to provide your own versions of the play services dependencies... 14 | 15 | compile 'com.google.android.gms:play-services-location:6.5.87' 16 | compile 'com.google.android.gms:play-services-base:6.5.87' 17 | 18 | 19 | # Background services 20 | android-location-activity a background service so that you can continue to update locations in a single location while users move around your app. To use this, ensure you have the service defined in your ApplicationManifest as such: 21 | 22 | 24 | 25 | 26 | 27 | 28 | 29 | # Getting Location Data 30 | In order to retrieve location data, several callbacks exist on the service class. You will set these up after starting the service. 31 | 32 | bindService(new Intent(this, BackgroundLocationService.class), mLocationManagerConnection, Context.BIND_AUTO_CREATE); 33 | 34 | Inside your ```ServiceConnection``` object, you'll have access to the service in order to set callbacks. 35 | 36 | private BackgroundLocationService mBackgroundLocationService; 37 | private ServiceConnection mLocationManagerConnection = new ServiceConnection() { 38 | @Override 39 | public void onServiceConnected(ComponentName name, IBinder service) { 40 | Log.i(TAG, "Background location services connected"); 41 | mBackgroundLocationService = ((BackgroundLocationService.LocalBinder)service).getBackgroundLocationService(); 42 | mBackgroundLocationService.addConnectionCallbacks(LocationActivity.this); 43 | mBackgroundLocationService.addLocationCallbacks(LocationActivity.this); 44 | } 45 | 46 | @Override 47 | public void onServiceDisconnected(ComponentName name) { 48 | mBackgroundLocationService = null; 49 | } 50 | }; 51 | 52 | Once you're notified via ```onLocationServicesConnectionSuccessful``` that the play services are connected in the connection callbacks, you can request location updates on the service by calling ```requestUpdates()``` and passing in your ```LocationRequest```. Updated locations will arrive in ```onNewLocation()```. 53 | # Required Permissions 54 | Since we are using the location, one or both of the location permissions must be declared in your manifest. Choose which one you like, or include both. 55 | 56 | 57 | -------------------------------------------------------------------------------- /location-service/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | apply plugin: 'com.jfrog.bintray' 4 | 5 | version = "1.4.1" 6 | 7 | def siteUrl = 'https://github.com/shiftconnects/android-location-service' // Homepage URL of the library 8 | def gitUrl = 'https://github.com/shiftconnects/android-location-service.git' // Git repository URL 9 | def projectDesc = 'A background service that can be used to gather location data for your Android app.' 10 | group = "com.shiftconnects.android.location" // Maven Group ID for the artifact 11 | 12 | Properties properties = new Properties() 13 | properties.load(project.rootProject.file('bintray.properties').newDataInputStream()) 14 | 15 | android { 16 | compileSdkVersion 21 17 | buildToolsVersion "21.1.2" 18 | 19 | defaultConfig { 20 | minSdkVersion 16 21 | targetSdkVersion 21 22 | versionCode 1 23 | versionName version 24 | } 25 | buildTypes {} 26 | } 27 | 28 | bintray { 29 | user = properties.getProperty("bintray.user") 30 | key = properties.getProperty("bintray.apikey") 31 | def gpgPhrase = properties.getProperty("bintray.gpg.passphrase") 32 | 33 | configurations = ['archives'] 34 | pkg { 35 | repo = "maven" 36 | name = "com.shiftconnects.android.location" 37 | desc = projectDesc 38 | websiteUrl = siteUrl 39 | vcsUrl = gitUrl 40 | licenses = ["Apache-2.0"] 41 | publish = true 42 | 43 | version { 44 | vcsTag = version 45 | gpg { 46 | sign = true 47 | passphrase = gpgPhrase 48 | } 49 | mavenCentralSync { 50 | sync = true 51 | user = properties.getProperty("oss.userToken") 52 | password = properties.getProperty("oss.userTokenValue") 53 | close = '1' 54 | } 55 | } 56 | } 57 | } 58 | 59 | install { 60 | repositories.mavenInstaller { 61 | // This generates POM.xml with proper parameters 62 | pom { 63 | project { 64 | packaging 'aar' 65 | 66 | // Add your description here 67 | description projectDesc 68 | name "Android Location Services" 69 | url siteUrl 70 | 71 | // Set your license 72 | licenses { 73 | license { 74 | name 'The Apache Software License, Version 2.0' 75 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 76 | } 77 | } 78 | developers { 79 | developer { 80 | id 'inktomi' 81 | name 'Matthew Runo' 82 | email 'matt.runo@shiftconnects.com' 83 | } 84 | } 85 | scm { 86 | connection gitUrl 87 | developerConnection gitUrl 88 | url siteUrl 89 | 90 | } 91 | } 92 | } 93 | } 94 | } 95 | 96 | dependencies { 97 | compile 'com.google.android.gms:play-services-location:6.5.87' 98 | compile 'com.google.android.gms:play-services-base:6.5.87' 99 | compile 'com.google.maps.android:android-maps-utils:0.3.4' 100 | } 101 | 102 | task sourcesJar(type: Jar) { 103 | from android.sourceSets.main.java.srcDirs 104 | classifier = 'sources' 105 | } 106 | 107 | task javadoc(type: Javadoc) { 108 | source = android.sourceSets.main.java.srcDirs 109 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 110 | } 111 | 112 | task javadocJar(type: Jar, dependsOn: javadoc) { 113 | classifier = 'javadoc' 114 | from javadoc.destinationDir 115 | } 116 | 117 | artifacts { 118 | archives javadocJar 119 | archives sourcesJar 120 | } 121 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /location-service/src/main/java/com/shiftconnects/android/location/MockBackgroundLocationService.java: -------------------------------------------------------------------------------- 1 | package com.shiftconnects.android.location; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Service; 5 | import android.content.Intent; 6 | import android.location.Location; 7 | import android.os.Binder; 8 | import android.os.Build; 9 | import android.os.Handler; 10 | import android.os.HandlerThread; 11 | import android.os.IBinder; 12 | import android.os.Looper; 13 | import android.os.Message; 14 | import android.os.SystemClock; 15 | import android.support.annotation.Nullable; 16 | import android.util.Log; 17 | 18 | import com.google.android.gms.common.ConnectionResult; 19 | import com.google.android.gms.location.LocationServices; 20 | import com.google.android.gms.maps.model.LatLng; 21 | import com.google.maps.android.SphericalUtil; 22 | 23 | /** 24 | * Created by mattruno on 3/3/15. 25 | */ 26 | public class MockBackgroundLocationService extends BackgroundLocationService implements BackgroundLocationService.ConnectionCallbacks { 27 | 28 | private static final String TAG = MockBackgroundLocationService.class.getSimpleName(); 29 | 30 | private static final long DEFAULT_SEND_INTERVAL = 1000l; // 1 second 31 | 32 | private final IBinder mBinder = new LocalBinder(); 33 | 34 | private HandlerThread mWorkThread; 35 | private Looper mUpdateLooper; 36 | private UpdateHandler mUpdateHandler; 37 | 38 | private long mSendInterval = DEFAULT_SEND_INTERVAL; 39 | private float mAccuracy; 40 | private boolean mTestStarted; 41 | 42 | @Override public void onCreate() { 43 | super.onCreate(); 44 | Log.d(TAG, "Service created."); 45 | mWorkThread = new HandlerThread("UpdateThread", android.os.Process.THREAD_PRIORITY_BACKGROUND); 46 | mWorkThread.start(); 47 | mUpdateLooper = mWorkThread.getLooper(); 48 | mUpdateHandler = new UpdateHandler(mUpdateLooper); 49 | mTestStarted = false; 50 | 51 | addConnectionCallbacks(this); 52 | } 53 | 54 | @Override public int onStartCommand(Intent intent, int flags, int startId) { 55 | Log.d(TAG, "Service started."); 56 | return Service.START_STICKY; 57 | } 58 | 59 | @Override public void onDestroy() { 60 | super.onDestroy(); 61 | if (getGoogleApiClient() != null && getGoogleApiClient().isConnected()) { 62 | LocationServices.FusedLocationApi.setMockMode(getGoogleApiClient(), false); 63 | } 64 | } 65 | 66 | @Nullable 67 | @Override 68 | public IBinder onBind(Intent intent) { 69 | return mBinder; 70 | } 71 | 72 | public void mockLocations(long sendInterval, float accuracy, LatLng... locations) { 73 | mSendInterval = sendInterval; 74 | mAccuracy = accuracy; 75 | Message msg = mUpdateHandler.obtainMessage(); 76 | msg.obj = locations; 77 | mUpdateHandler.sendMessage(msg); 78 | } 79 | 80 | public void setAccuracy(float accuracy) { 81 | mAccuracy = accuracy; 82 | } 83 | 84 | public void setSendInterval(long sendInterval) { 85 | mSendInterval = sendInterval; 86 | } 87 | 88 | @Override 89 | public void onLocationServicesConnectionSuccessful() { 90 | mUpdateLooper = mWorkThread.getLooper(); 91 | mUpdateHandler = new UpdateHandler(mUpdateLooper); 92 | LocationServices.FusedLocationApi.setMockMode(getGoogleApiClient(), true); 93 | } 94 | 95 | @Override 96 | public void onLocationServicesConnectionFailed(ConnectionResult connectionResult) { 97 | 98 | } 99 | 100 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) 101 | public class UpdateHandler extends Handler { 102 | 103 | public UpdateHandler(Looper looper) { 104 | super(looper); 105 | } 106 | 107 | @Override public void handleMessage(Message msg) { 108 | if (!mTestStarted) { 109 | mTestStarted = true; 110 | long elapsedTimeNanos; 111 | long currentTime; 112 | LatLng[] mockLocations = (LatLng[]) msg.obj; 113 | if (mockLocations != null && mockLocations.length > 0) { 114 | Location mockLocation = new Location("fused"); 115 | LatLng lastLocation = null; 116 | for (LatLng latLng : mockLocations) { 117 | if (getGoogleApiClient() == null || !getGoogleApiClient().isConnected()) { 118 | break; 119 | } 120 | currentTime = System.currentTimeMillis(); 121 | if (Build.VERSION.SDK_INT >= 17) { 122 | elapsedTimeNanos = SystemClock.elapsedRealtimeNanos(); 123 | mockLocation.setElapsedRealtimeNanos(elapsedTimeNanos); 124 | } 125 | mockLocation.setTime(currentTime); 126 | mockLocation.setAccuracy(mAccuracy); 127 | mockLocation.setLatitude(latLng.latitude); 128 | mockLocation.setLongitude(latLng.longitude); 129 | if (lastLocation != null) { 130 | mockLocation.setBearing((float) SphericalUtil.computeHeading(lastLocation, latLng)); 131 | } 132 | lastLocation = latLng; 133 | LocationServices.FusedLocationApi.setMockLocation(getGoogleApiClient(), mockLocation); 134 | 135 | // wait the specified interval 136 | try { 137 | Thread.sleep(mSendInterval); 138 | } catch (InterruptedException e) { 139 | break; 140 | } 141 | } 142 | } 143 | mTestStarted = false; 144 | } 145 | } 146 | } 147 | 148 | public class LocalBinder extends Binder { 149 | public MockBackgroundLocationService getService() { 150 | // Return this instance of LocalService so clients can call public methods 151 | return MockBackgroundLocationService.this; 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /sample/src/main/java/com/shiftconnects/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright (C) 2015 P100 OG, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package com.shiftconnects.sample; 19 | 20 | import android.content.ComponentName; 21 | import android.content.Context; 22 | import android.content.DialogInterface; 23 | import android.content.Intent; 24 | import android.content.IntentSender; 25 | import android.content.ServiceConnection; 26 | import android.location.GpsStatus; 27 | import android.location.Location; 28 | import android.location.LocationManager; 29 | import android.os.Bundle; 30 | import android.os.IBinder; 31 | import android.support.v7.app.ActionBarActivity; 32 | import android.util.Log; 33 | import android.view.Menu; 34 | import android.view.MenuItem; 35 | import android.widget.Toast; 36 | 37 | import com.google.android.gms.common.ConnectionResult; 38 | import com.google.android.gms.common.GooglePlayServicesUtil; 39 | import com.google.android.gms.location.LocationRequest; 40 | import com.shiftconnects.android.location.BackgroundLocationService; 41 | 42 | 43 | public class MainActivity extends ActionBarActivity implements GpsStatus.Listener, BackgroundLocationService.ConnectionCallbacks, BackgroundLocationService.LocationCallbacks { 44 | private static final String TAG = MainActivity.class.getName(); 45 | 46 | // Google play services stuff.. 47 | private boolean mIsInResolution; 48 | private boolean mShouldRetryConnecting; 49 | 50 | // Request code for auto Google Play Services error resolution. 51 | protected static final int REQUEST_CODE_RESOLUTION = 1; 52 | 53 | // Use the location manger to track if location is enabled or not. 54 | private LocationManager mLocationManager; 55 | private boolean mLocationEnabled; 56 | 57 | // Our background service, and the callback setup. 58 | private BackgroundLocationService mBackgroundLocationService; 59 | private ServiceConnection mLocationManagerConnection = new ServiceConnection() { 60 | @Override 61 | public void onServiceConnected(ComponentName name, IBinder service) { 62 | Log.i(TAG, "Background location services connected"); 63 | mBackgroundLocationService = ((BackgroundLocationService.LocalBinder)service).getBackgroundLocationService(); 64 | mBackgroundLocationService.addConnectionCallbacks(MainActivity.this); 65 | mBackgroundLocationService.addLocationCallbacks(MainActivity.this); 66 | } 67 | 68 | @Override 69 | public void onServiceDisconnected(ComponentName name) { 70 | mBackgroundLocationService = null; 71 | } 72 | }; 73 | 74 | @Override 75 | protected void onCreate(Bundle savedInstanceState) { 76 | super.onCreate(savedInstanceState); 77 | setContentView(R.layout.activity_main); 78 | 79 | mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 80 | } 81 | 82 | @Override 83 | protected void onResume() { 84 | super.onResume(); 85 | checkLocationEnabled(); 86 | 87 | if( mLocationEnabled ){ 88 | bindService(new Intent(this, BackgroundLocationService.class), mLocationManagerConnection, Context.BIND_AUTO_CREATE); 89 | } else { 90 | Toast.makeText(this, "Location is disabled :(", Toast.LENGTH_SHORT).show(); 91 | } 92 | } 93 | 94 | private void checkLocationEnabled() { 95 | mLocationEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 96 | } 97 | 98 | @Override 99 | public void onLocationChanged(Location location) { 100 | Toast.makeText(this, "New location! " + location.toString(), Toast.LENGTH_SHORT).show(); 101 | } 102 | 103 | @Override 104 | public boolean onCreateOptionsMenu(Menu menu) { 105 | // Inflate the menu; this adds items to the action bar if it is present. 106 | getMenuInflater().inflate(R.menu.menu_main, menu); 107 | return true; 108 | } 109 | 110 | @Override 111 | public boolean onOptionsItemSelected(MenuItem item) { 112 | // Handle action bar item clicks here. The action bar will 113 | // automatically handle clicks on the Home/Up button, so long 114 | // as you specify a parent activity in AndroidManifest.xml. 115 | int id = item.getItemId(); 116 | 117 | //noinspection SimplifiableIfStatement 118 | if (id == R.id.action_settings) { 119 | return true; 120 | } 121 | 122 | return super.onOptionsItemSelected(item); 123 | } 124 | 125 | @Override 126 | protected void onPause() { 127 | // When you're done with locations, be sure you remember to remove the service! 128 | if (mBackgroundLocationService != null) { 129 | mBackgroundLocationService.removeLocationUpdates(); 130 | mBackgroundLocationService.removeConnectionCallbacks(this); 131 | mBackgroundLocationService.removeLocationCallbacks(this); 132 | unbindService(mLocationManagerConnection); 133 | mBackgroundLocationService = null; 134 | } 135 | 136 | super.onPause(); 137 | } 138 | 139 | @Override 140 | protected void onDestroy() { 141 | super.onDestroy(); 142 | mLocationManager.removeGpsStatusListener(this); 143 | } 144 | 145 | @Override 146 | public final void onConnectionSuspended(int i) { 147 | Log.w(TAG, "Connection to Google Play Services suspended!"); 148 | } 149 | 150 | @Override 151 | public void onLocationServicesConnectionSuccessful() { 152 | LocationRequest request = LocationRequest.create(); 153 | request.setInterval(5000); // Five seconds 154 | 155 | mBackgroundLocationService.requestUpdates(request); 156 | } 157 | 158 | @Override 159 | public void onLocationServicesConnectionFailed(ConnectionResult result) { 160 | Log.i(TAG, "GoogleApiClient connection failed: " + result.toString()); 161 | if (!result.hasResolution()) { 162 | mShouldRetryConnecting = true; 163 | // Show a localized error dialog. 164 | GooglePlayServicesUtil.getErrorDialog( 165 | result.getErrorCode(), this, 0, new DialogInterface.OnCancelListener() { 166 | @Override 167 | public void onCancel(DialogInterface dialog) { 168 | retryConnecting(); 169 | } 170 | }).show(); 171 | return; 172 | } 173 | // If there is an existing resolution error being displayed or a resolution 174 | // activity has started before, do nothing and wait for resolution 175 | // progress to be completed. 176 | if (mIsInResolution) { 177 | return; 178 | } 179 | mIsInResolution = true; 180 | try { 181 | result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION); 182 | } catch (IntentSender.SendIntentException e) { 183 | Log.e(TAG, "Exception while starting resolution activity", e); 184 | retryConnecting(); 185 | } 186 | } 187 | 188 | @Override 189 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 190 | super.onActivityResult(requestCode, resultCode, data); 191 | if (mShouldRetryConnecting) { 192 | retryConnecting(); 193 | } else { 194 | switch (requestCode) { 195 | case REQUEST_CODE_RESOLUTION: 196 | retryConnecting(); 197 | break; 198 | } 199 | } 200 | } 201 | 202 | private void retryConnecting() { 203 | mIsInResolution = false; 204 | mShouldRetryConnecting = false; 205 | if (mBackgroundLocationService != null) { 206 | mBackgroundLocationService.onConnectionResolved(); 207 | } 208 | } 209 | 210 | @Override public void onGpsStatusChanged(int event) { 211 | switch (event) { 212 | case GpsStatus.GPS_EVENT_STARTED: 213 | Log.d(TAG, "GPS has started."); 214 | break; 215 | case GpsStatus.GPS_EVENT_STOPPED: 216 | Log.d(TAG, "GPS has stopped."); 217 | checkLocationEnabled(); 218 | if (mBackgroundLocationService.getGoogleApiClient().isConnected() && !mLocationEnabled) { 219 | Log.d(TAG, "Disconnecting location client"); 220 | Toast.makeText(this, "Location disabled.", Toast.LENGTH_SHORT).show(); 221 | } 222 | break; 223 | } 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /location-service/src/main/java/com/shiftconnects/android/location/BackgroundLocationService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 P100 OG, Inc. 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 com.shiftconnects.android.location; 18 | 19 | import android.app.PendingIntent; 20 | import android.app.Service; 21 | import android.content.Intent; 22 | import android.location.Location; 23 | import android.os.Binder; 24 | import android.os.Bundle; 25 | import android.os.IBinder; 26 | import android.text.TextUtils; 27 | import android.util.Log; 28 | 29 | import com.google.android.gms.common.ConnectionResult; 30 | import com.google.android.gms.common.api.GoogleApiClient; 31 | import com.google.android.gms.common.api.ResultCallback; 32 | import com.google.android.gms.common.api.Status; 33 | import com.google.android.gms.location.Geofence; 34 | import com.google.android.gms.location.GeofencingEvent; 35 | import com.google.android.gms.location.LocationListener; 36 | import com.google.android.gms.location.LocationRequest; 37 | import com.google.android.gms.location.LocationServices; 38 | 39 | import java.util.ArrayList; 40 | import java.util.List; 41 | 42 | /** 43 | * Sets up a location service with callbacks for interested parties. 44 | * 45 | * To use, simply place the following into your ApplicationManifest somewhere in the tag. 46 | * 47 | * 49 | * 50 | * 51 | * 52 | * 53 | * 54 | * 55 | */ 56 | public class BackgroundLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, 57 | GoogleApiClient.OnConnectionFailedListener, LocationListener { 58 | 59 | private static final String ACTION_GEOFENCE_TRANSITION = "com.shiftconnects.android.ACTION_GEOFENCE_TRANSITION"; 60 | 61 | private final IBinder mBinder = new LocalBinder(); 62 | 63 | public static interface LocationCallbacks { 64 | void onLocationChanged(Location location); 65 | } 66 | 67 | public static interface ConnectionCallbacks { 68 | void onConnectionSuspended(int flag); 69 | void onLocationServicesConnectionSuccessful(); 70 | void onLocationServicesConnectionFailed(ConnectionResult connectionResult); 71 | } 72 | 73 | public static interface GeofenceCallbacks { 74 | void onGeofenceEntered(String geofenceId); 75 | void onGeofenceDwelled(String geofenceId); 76 | void onGeofenceExited(String geofenceId); 77 | void onGeofenceError(GeofencingEvent event); 78 | void onGeofencesSetupSuccessful(); 79 | void onGeofencesSetupUnsuccessful(Status status); 80 | } 81 | 82 | private static final String TAG = BackgroundLocationService.class.getSimpleName(); 83 | 84 | private static final boolean DEBUG = false; 85 | 86 | private GoogleApiClient mGoogleApiClient; 87 | 88 | private List mLocationCallbacks; 89 | private List mConnectionCallbacks; 90 | private List mGeofenceCallbacks; 91 | 92 | private Location mLastLocation; 93 | private ConnectionResult mFailedConnectionResult; 94 | 95 | @Override public void onCreate() { 96 | if( DEBUG ) { 97 | Log.d(TAG, "Service created."); 98 | } 99 | super.onCreate(); 100 | mLocationCallbacks = new ArrayList<>(); 101 | mGeofenceCallbacks = new ArrayList<>(); 102 | mConnectionCallbacks = new ArrayList<>(); 103 | if (mGoogleApiClient == null) { 104 | mGoogleApiClient = new GoogleApiClient.Builder(this) 105 | .addApi(LocationServices.API) 106 | .addConnectionCallbacks(this) 107 | .addOnConnectionFailedListener(this) 108 | .build(); 109 | } 110 | mGoogleApiClient.connect(); 111 | } 112 | 113 | @Override 114 | public int onStartCommand(Intent intent, int flags, int startId) { 115 | handleCommand(intent); 116 | return START_NOT_STICKY; 117 | } 118 | 119 | private void handleCommand(Intent intent) { 120 | if (intent != null) { 121 | final String action = intent.getAction(); 122 | if( DEBUG ) { 123 | Log.d(TAG, "Received an intent with action [" + action + "]"); 124 | } 125 | if (TextUtils.equals(ACTION_GEOFENCE_TRANSITION, action)) { 126 | GeofencingEvent event = GeofencingEvent.fromIntent(intent); 127 | if (event.hasError()) { 128 | if( DEBUG ) { 129 | Log.w(TAG, "Received a geofence event with an error!"); 130 | } 131 | if( null != mGeofenceCallbacks ){ 132 | for( GeofenceCallbacks cb : mGeofenceCallbacks ) { 133 | cb.onGeofenceError(event); 134 | } 135 | } 136 | } else { 137 | switch (event.getGeofenceTransition()) { 138 | case Geofence.GEOFENCE_TRANSITION_ENTER: 139 | if( DEBUG ) { 140 | Log.d(TAG, "Received a geofence ENTER event"); 141 | } 142 | for (Geofence geofence : event.getTriggeringGeofences()) { 143 | notifyCallbacksOnGeofenceEntered(geofence.getRequestId()); 144 | } 145 | break; 146 | case Geofence.GEOFENCE_TRANSITION_DWELL: 147 | if( DEBUG ) { 148 | Log.d(TAG, "Received a geofence DWELL event"); 149 | } 150 | for (Geofence geofence : event.getTriggeringGeofences()) { 151 | notifyCallbacksOnGeofenceDwelled(geofence.getRequestId()); 152 | } 153 | break; 154 | case Geofence.GEOFENCE_TRANSITION_EXIT: 155 | if( DEBUG ) { 156 | Log.d(TAG, "Received a geofence EXIT event"); 157 | } 158 | for (Geofence geofence : event.getTriggeringGeofences()) { 159 | notifyCallbacksOnGeofenceExited(geofence.getRequestId()); 160 | } 161 | break; 162 | } 163 | } 164 | } 165 | } 166 | } 167 | 168 | @Override public void onDestroy() { 169 | if( DEBUG ) { 170 | Log.d(TAG, "Service destroyed."); 171 | } 172 | super.onDestroy(); 173 | if (mGoogleApiClient != null) { 174 | mGoogleApiClient.disconnect(); 175 | } 176 | } 177 | 178 | // region callbacks 179 | 180 | public boolean addLocationCallbacks(LocationCallbacks callbacks) { 181 | if (mLastLocation != null) { 182 | callbacks.onLocationChanged(mLastLocation); 183 | } 184 | return mLocationCallbacks.add(callbacks); 185 | } 186 | 187 | public boolean removeLocationCallbacks(LocationCallbacks callbacks) { 188 | return mLocationCallbacks.remove(callbacks); 189 | } 190 | 191 | public boolean addGeofenceCallbacks(GeofenceCallbacks callbacks) { 192 | return mGeofenceCallbacks.add(callbacks); 193 | } 194 | 195 | public boolean removeGeofenceCallbacks(GeofenceCallbacks callbacks) { 196 | return mGeofenceCallbacks.remove(callbacks); 197 | } 198 | 199 | public boolean addConnectionCallbacks(ConnectionCallbacks callbacks) { 200 | if (mFailedConnectionResult != null) { 201 | callbacks.onLocationServicesConnectionFailed(mFailedConnectionResult); 202 | } else if (isLocationServicesConnected()) { 203 | callbacks.onLocationServicesConnectionSuccessful(); 204 | } 205 | return mConnectionCallbacks.add(callbacks); 206 | } 207 | 208 | public boolean removeConnectionCallbacks(ConnectionCallbacks callbacks) { 209 | return mConnectionCallbacks.remove(callbacks); 210 | } 211 | 212 | private void notifyCallbacksOnGeofenceEntered(String geofenceId) { 213 | for (GeofenceCallbacks callbacks : mGeofenceCallbacks) { 214 | callbacks.onGeofenceEntered(geofenceId); 215 | } 216 | } 217 | 218 | private void notifyCallbacksOnGeofenceDwelled(String geofenceId) { 219 | for (GeofenceCallbacks callbacks : mGeofenceCallbacks) { 220 | callbacks.onGeofenceDwelled(geofenceId); 221 | } 222 | } 223 | 224 | private void notifyCallbacksOnGeofenceExited(String geofenceId) { 225 | for (GeofenceCallbacks callbacks : mGeofenceCallbacks) { 226 | callbacks.onGeofenceExited(geofenceId); 227 | } 228 | } 229 | 230 | private void notifyCallbacksOnLocationChanged() { 231 | for (LocationCallbacks callbacks : mLocationCallbacks) { 232 | callbacks.onLocationChanged(mLastLocation); 233 | } 234 | } 235 | 236 | private void notifyCallbacksOnConnectionFailed(ConnectionResult connectionResult) { 237 | for (ConnectionCallbacks callbacks : mConnectionCallbacks) { 238 | callbacks.onLocationServicesConnectionFailed(connectionResult); 239 | } 240 | } 241 | 242 | private void notifyCallbacksOnConnectionSuccessful() { 243 | for (ConnectionCallbacks callbacks : mConnectionCallbacks) { 244 | callbacks.onLocationServicesConnectionSuccessful(); 245 | } 246 | } 247 | 248 | // endregion 249 | 250 | public void setupGeofences(List geofences) { 251 | if (isLocationServicesConnected()) { 252 | if( DEBUG ) { 253 | Log.d(TAG, "Setting up geofences [" + geofences + "]..."); 254 | } 255 | LocationServices.GeofencingApi.addGeofences( 256 | getGoogleApiClient(), 257 | geofences, 258 | getGeofencePendingIntent() 259 | ).setResultCallback(new ResultCallback() { 260 | @Override 261 | public void onResult(Status status) { 262 | if (status.isSuccess()) { 263 | if( DEBUG ) { 264 | Log.d(TAG, "Successfully setup geofences."); 265 | } 266 | if( null != mGeofenceCallbacks ){ 267 | for( GeofenceCallbacks cb : mGeofenceCallbacks ) { 268 | cb.onGeofencesSetupSuccessful(); 269 | } 270 | } 271 | } else { 272 | if( null != mGeofenceCallbacks ){ 273 | for( GeofenceCallbacks cb : mGeofenceCallbacks ) { 274 | cb.onGeofencesSetupUnsuccessful(status); 275 | } 276 | } 277 | } 278 | } 279 | }); 280 | } 281 | } 282 | 283 | public void removeGeofences() { 284 | if (isLocationServicesConnected()) { 285 | if( DEBUG ) { 286 | Log.d(TAG, "Removing all geofences..."); 287 | } 288 | 289 | // remove from geofencing api 290 | LocationServices.GeofencingApi.removeGeofences(getGoogleApiClient(), getGeofencePendingIntent()); 291 | } 292 | } 293 | 294 | @Override 295 | public void onConnected(Bundle bundle) { 296 | if( DEBUG ) { 297 | Log.d(TAG, "Connected."); 298 | } 299 | mFailedConnectionResult = null; 300 | notifyCallbacksOnConnectionSuccessful(); 301 | } 302 | 303 | public void requestUpdates(LocationRequest locationRequest) { 304 | if (isLocationServicesConnected()) { 305 | if( DEBUG ) { 306 | Log.d(TAG, "Requesting updates for [" + locationRequest + "]"); 307 | } 308 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this); 309 | Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 310 | if (location != null) { 311 | onLocationChanged(location); 312 | } 313 | } 314 | } 315 | 316 | public void removeLocationUpdates() { 317 | if (isLocationServicesConnected()) { 318 | if( DEBUG ) { 319 | Log.d(TAG, "Removing location updates."); 320 | } 321 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 322 | } 323 | } 324 | 325 | public void onConnectionResolved() { 326 | if (mGoogleApiClient != null && !mGoogleApiClient.isConnecting()) { 327 | mGoogleApiClient.connect(); 328 | } 329 | } 330 | 331 | @Override 332 | public final void onLocationChanged(Location location) { 333 | if( DEBUG ) { 334 | Log.d(TAG, "onLocationChanged [" + location + "]"); 335 | } 336 | mLastLocation = location; 337 | notifyCallbacksOnLocationChanged(); 338 | if( null != mLocationCallbacks ){ 339 | for( LocationCallbacks cb : mLocationCallbacks ) { 340 | cb.onLocationChanged(location); 341 | } 342 | } 343 | } 344 | 345 | @Override 346 | public final void onConnectionSuspended(int i) { 347 | if( DEBUG ) { 348 | Log.w(TAG, "Connection to Google Play Services suspended!"); 349 | } 350 | if( null != mConnectionCallbacks ){ 351 | for( ConnectionCallbacks cb : mConnectionCallbacks ) { 352 | cb.onConnectionSuspended(i); 353 | } 354 | } 355 | } 356 | 357 | @Override 358 | public final void onConnectionFailed(ConnectionResult connectionResult) { 359 | mFailedConnectionResult = connectionResult; 360 | if( DEBUG ) { 361 | Log.w(TAG, "Connection to Google Play Services failed!"); 362 | } 363 | notifyCallbacksOnConnectionFailed(connectionResult); 364 | if( null != mConnectionCallbacks ){ 365 | for( ConnectionCallbacks cb : mConnectionCallbacks ) { 366 | cb.onLocationServicesConnectionFailed(connectionResult); 367 | } 368 | } 369 | } 370 | 371 | private PendingIntent getGeofencePendingIntent() { 372 | return PendingIntent.getService( 373 | this, 374 | 0, 375 | new Intent(ACTION_GEOFENCE_TRANSITION), 376 | PendingIntent.FLAG_UPDATE_CURRENT 377 | ); 378 | } 379 | 380 | public GoogleApiClient getGoogleApiClient() { 381 | return mGoogleApiClient; 382 | } 383 | 384 | public boolean isLocationServicesConnected() { 385 | return mGoogleApiClient != null && mGoogleApiClient.isConnected(); 386 | } 387 | 388 | @Override public IBinder onBind(Intent intent) { 389 | return mBinder; 390 | } 391 | 392 | public class LocalBinder extends Binder { 393 | public BackgroundLocationService getBackgroundLocationService() { 394 | return BackgroundLocationService.this; 395 | } 396 | } 397 | } 398 | --------------------------------------------------------------------------------