├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── strings.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── wahibhaq
│ │ │ │ └── locationservicelivedata
│ │ │ │ ├── LocationListener.kt
│ │ │ │ ├── MainApplication.kt
│ │ │ │ ├── LocationServiceListener.kt
│ │ │ │ ├── MainViewModel.kt
│ │ │ │ ├── PermissionStatusListener.kt
│ │ │ │ ├── Utils.kt
│ │ │ │ ├── GpsStatusListener.kt
│ │ │ │ ├── NotificationUtil.kt
│ │ │ │ ├── LocationService.kt
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── wahibhaq
│ │ │ └── locationservicelivedata
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── wahibhaq
│ │ └── locationservicelivedata
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── LICENSE
├── gradlew.bat
├── README.md
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KI-labs/gps-permission-checks-livedata/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/LocationListener.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 |
4 | interface LocationListener {
5 | fun subscribeToLocationUpdates()
6 |
7 | fun unsubscribeFromLocationUpdates()
8 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun May 27 16:48:51 CEST 2018
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-4.6-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/MainApplication.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.app.Application
4 | import timber.log.Timber
5 |
6 | class MainApplication : Application() {
7 |
8 | override fun onCreate() {
9 | super.onCreate()
10 | if (BuildConfig.DEBUG) {
11 | Timber.plant(Timber.DebugTree())
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/wahibhaq/locationservicelivedata/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | #Android generated
3 | bin
4 | gen
5 | *.ap_
6 | .apt_generated/
7 | app/schemas
8 |
9 | #IntelliJ IDEA
10 | .idea
11 | *.iml
12 | *.ipr
13 | *.iws
14 | classes
15 | gen-external-apklibs
16 |
17 | #Maven
18 | target
19 | release.properties
20 | pom.xml.*
21 |
22 | #Ant
23 | build.xml
24 | ant.properties
25 | local.properties
26 | proguard.cfg
27 |
28 | #Gradle
29 | .gradle
30 | build
31 | gradle.properties
32 |
33 | #Other
34 | .DS_Store
35 | tmp
36 | *.swp
37 | *.tmp
38 | *.bak
39 | *.swp
40 | *.launch
41 | captures
42 | *.apk
43 |
44 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/wahibhaq/locationservicelivedata/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("com.wahibhaq.locationservicelivedata", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/LocationServiceListener.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.annotation.TargetApi
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.os.Build
7 | import timber.log.Timber
8 |
9 |
10 | class LocationServiceListener(
11 | private val context: Context,
12 | private val serviceIntent: Intent
13 | ) : LocationListener {
14 |
15 | @TargetApi(Build.VERSION_CODES.O)
16 | override fun subscribeToLocationUpdates() {
17 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
18 | Timber.d("Running on Android O")
19 | context.startForegroundService(serviceIntent)
20 | } else {
21 | Timber.d("Running on Android N or lower")
22 | context.startService(serviceIntent)
23 | }
24 | }
25 |
26 | override fun unsubscribeFromLocationUpdates() {
27 | context.stopService(serviceIntent)
28 | }
29 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Wahib Ul Haq
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/MainViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.Manifest
4 | import android.app.Application
5 | import android.app.NotificationManager
6 | import android.arch.lifecycle.AndroidViewModel
7 | import android.content.Context
8 | import android.content.Intent
9 |
10 |
11 | class MainViewModel(application: Application) : AndroidViewModel(application) {
12 |
13 | private val locationServiceListener = LocationServiceListener(application, Intent(application,
14 | LocationService::class.java))
15 |
16 | private val notificationsUtil = NotificationsUtil(application,
17 | application.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
18 |
19 | val gpsStatusLiveData = GpsStatusListener(application)
20 |
21 | val locationPermissionStatusLiveData = PermissionStatusListener(application,
22 | Manifest.permission.ACCESS_FINE_LOCATION)
23 |
24 | fun startLocationTracking() = locationServiceListener.subscribeToLocationUpdates()
25 |
26 | fun stopLocationTracking() {
27 | locationServiceListener.unsubscribeFromLocationUpdates()
28 | notificationsUtil.cancelAlertNotification()
29 | }
30 |
31 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/PermissionStatusListener.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.arch.lifecycle.LiveData
4 | import android.content.Context
5 | import android.content.pm.PackageManager
6 | import android.support.v4.app.ActivityCompat
7 |
8 | /**
9 | * Listens to Runtime Permission Status of provided [permissionToListen] which comes under the
10 | * category of "Dangerous" and then responds with appropriate state specified in {@link PermissionStatus}
11 | */
12 | class PermissionStatusListener(private val context: Context,
13 | private val permissionToListen: String) : LiveData() {
14 |
15 | override fun onActive() = handlePermissionCheck()
16 |
17 | private fun handlePermissionCheck() {
18 | val isPermissionGranted = ActivityCompat.checkSelfPermission(context,
19 | permissionToListen) == PackageManager.PERMISSION_GRANTED
20 |
21 | if (isPermissionGranted)
22 | postValue(PermissionStatus.Granted())
23 | else
24 | postValue(PermissionStatus.Denied())
25 | }
26 | }
27 |
28 | sealed class PermissionStatus {
29 | data class Granted(val message: Int = R.string.permission_status_granted) : PermissionStatus()
30 | data class Denied(val message: Int = R.string.permission_status_denied) : PermissionStatus()
31 | data class Blocked(val message: Int = R.string.permission_status_blocked) : PermissionStatus()
32 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | GPS and Permission Checks
3 | Start Tracking
4 | End Tracking
5 | Settings
6 | Location Permission is Granted
7 | Location Permission is Denied
8 | Location Permission is Blocked
9 | "Location permission not granted. " +
10 | "Show a notification to alert user"
11 | "GPS is Enabled"
12 | "GPS is Disabled"
13 | In Progress…
14 | GPS Required
15 | Location Permission Required
16 | Enable GPS otherwise location tracking won\'t work
17 | Location Tracking
18 | Allow otherwise location tracking won\'t work
19 | Location Permission has been set not to ask again! Please provide it from Settings.
20 | Waiting for GPS to be enabled…
21 | Simulate Notification(s)
22 | (click to retry)
23 |
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/Utils.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.arch.lifecycle.LiveData
4 | import android.arch.lifecycle.MediatorLiveData
5 | import android.arch.lifecycle.MutableLiveData
6 |
7 | /**
8 | * This function creates a [LiveData] of a [Pair] of the two types provided. The resulting LiveData is updated whenever either input LiveData updates and both LiveData have updated at least once before.
9 | *
10 | * If the combination of A and B is C, and A and B are updated in this pattern: `AABA`, C would be updated twice (once with the second A value and first B value, and once with the third A value and first B value).
11 | *
12 | * @param a the first LiveData
13 | * @param b the second LiveData
14 | * @author Mitchell Skaggs https://gist.github.com/magneticflux-/044c9d7a3cea431aa0e4f4f4950a2898
15 | */
16 | fun combineLatest(a: LiveData, b: LiveData): MutableLiveData> {
17 | return MediatorLiveData>().apply {
18 | var lastA: A? = null
19 | var lastB: B? = null
20 |
21 | fun update() {
22 | val localLastA = lastA
23 | val localLastB = lastB
24 | if (localLastA != null && localLastB != null)
25 | this.value = Pair(localLastA, localLastB)
26 | }
27 |
28 | addSource(a) {
29 | lastA = it
30 | update()
31 | }
32 | addSource(b) {
33 | lastB = it
34 | update()
35 | }
36 | }
37 | }
38 |
39 | /**
40 | * This is merely an extension function for [combineLatest].
41 | *
42 | * @see combineLatest
43 | * @author Mitchell Skaggs
44 | */
45 | fun LiveData.combineLatestWith(b: LiveData): LiveData> = combineLatest(this, b)
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | apply plugin: 'kotlin-kapt'
8 |
9 | android {
10 | compileSdkVersion 28
11 | defaultConfig {
12 | applicationId "com.wahibhaq.locationservicelivedata"
13 | minSdkVersion 21
14 | targetSdkVersion 28
15 | versionCode 1
16 | versionName "1.0"
17 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
18 | }
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: 'libs', include: ['*.jar'])
29 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
30 | implementation "com.android.support:support-v4:$supportlib"
31 | implementation "com.android.support:appcompat-v7:$supportlib"
32 | implementation "com.android.support.constraint:constraint-layout:$constraint_layout"
33 | implementation "android.arch.lifecycle:extensions:$aac_lifecycle"
34 | kapt "android.arch.lifecycle:compiler:$aac_lifecycle"
35 | implementation "android.arch.lifecycle:runtime:$aac_lifecycle"
36 | debugImplementation "com.jakewharton.timber:timber:$timber"
37 | implementation "com.google.android.gms:play-services-location:$play_services"
38 | implementation "com.nabinbhandari.android:permissions:$permissions"
39 |
40 | testImplementation "junit:junit:$junit"
41 | androidTestImplementation "com.android.support.test:runner:$test_runner"
42 | androidTestImplementation "com.android.support.test.espresso:espresso-core:$test_espresso_core"
43 | }
44 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/GpsStatusListener.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.arch.lifecycle.LiveData
4 | import android.content.BroadcastReceiver
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.content.IntentFilter
8 | import android.location.LocationManager
9 | import android.os.Build
10 | import android.provider.Settings
11 | import android.provider.Settings.Secure.*
12 | import timber.log.Timber
13 |
14 | /**
15 | * Listens to Gps (location service) which is highly important for tracking to work and then
16 | * responds with appropriate state specified in {@link GpsStatus}
17 | */
18 | class GpsStatusListener(private val context: Context) : LiveData() {
19 |
20 | private val gpsSwitchStateReceiver = object : BroadcastReceiver() {
21 | override fun onReceive(context: Context, intent: Intent) = checkGpsAndReact()
22 | }
23 |
24 | override fun onInactive() = unregisterReceiver()
25 |
26 | override fun onActive() {
27 | registerReceiver()
28 | checkGpsAndReact()
29 | }
30 |
31 | private fun checkGpsAndReact() = if (isLocationEnabled()) {
32 | postValue(GpsStatus.Enabled())
33 | } else {
34 | postValue(GpsStatus.Disabled())
35 | }
36 |
37 | private fun isLocationEnabled() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
38 | context.getSystemService(LocationManager::class.java)
39 | .isProviderEnabled(LocationManager.GPS_PROVIDER)
40 | } else {
41 | try {
42 | getInt(context.contentResolver, LOCATION_MODE) != LOCATION_MODE_OFF
43 | } catch (e: Settings.SettingNotFoundException) {
44 | Timber.e(e)
45 | false
46 | }
47 | }
48 |
49 | /**
50 | * Broadcast receiver to listen the Location button toggle state in Android.
51 | */
52 | private fun registerReceiver() = context.registerReceiver(gpsSwitchStateReceiver,
53 | IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION))
54 |
55 | private fun unregisterReceiver() = context.unregisterReceiver(gpsSwitchStateReceiver)
56 | }
57 |
58 | sealed class GpsStatus {
59 | data class Enabled(val message: Int = R.string.gps_status_enabled) : GpsStatus()
60 | data class Disabled(val message: Int = R.string.gps_status_disabled) : GpsStatus()
61 | }
62 |
--------------------------------------------------------------------------------
/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 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
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 Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
21 |
22 |
37 |
38 |
49 |
50 |
62 |
63 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Monitoring GPS and Location Permission checks using LiveData
2 |
3 | ## Background:
4 |
5 | In Android apps, users need to allow specific permissions so that app can use that particular resource. All location tracking apps need “GPS to be enabled” and want users to allow “Location Permission” so that app can start receiving location coordinates. For our usecase, it was critically needed to ensure both of these requirements are fulfilled. If not, user should be alerted and informed on UI level during or after *Onboarding* and also when Location Tracking is started/running in background.
6 |
7 | This is a sample app to demonstrate the usecase.
8 |
9 | ## Motivation to publish my solution:
10 |
11 | There are already native android ways to implement both of these checks but we tried to do it using LiveData which is a newly introduced API from Android to handle asynchronous operations using Subscribe/Publish mechanism. We faced our fair share of challenges and there was limited help available as not many have tried for this usecase. Solutions which are challenging are the best candidate to be shared with public because it means many others out there will face the same problems and it could save their time. At the end of the day, it’s basically giving back to the community.
12 |
13 | ## What is this project about:
14 |
15 | 1) UI (app is active): Checking for both elements, displaying state and showing dialogs for user to react accordingly
16 |
17 | Medium Article: [Read Here](https://medium.com/ki-labs-engineering/monitoring-gps-and-location-permission-checks-using-livedata-part-1-278907344b77)
18 |
19 | 2) Background (app is not active): Check for both elements as part of Service whenever it is started by System and inform user via notification so that user can enable them for us. Otherwise, location tracking won’t succeed at all.
20 |
21 | Medium Article: [Read Here](https://medium.com/ki-labs-engineering/monitoring-gps-and-location-permission-checks-using-livedata-part-2-d8822ab951a6)
22 |
23 | ## How sample app looks like or behaves
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/NotificationUtil.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.app.NotificationChannel
4 | import android.app.NotificationManager
5 | import android.app.PendingIntent
6 | import android.app.Service
7 | import android.content.Context
8 | import android.os.Build
9 | import android.support.v4.app.NotificationCompat
10 |
11 | const val ONGOING_NOTIFICATION_ID = 1
12 | const val ALERT_PERMISSION_NOTIFICATION_ID = 2
13 | const val ALERT_GPS_NOTIFICATION_ID = 3
14 | const val NOTIFICATION_CHANNEL_NAME = "All"
15 | const val NOTIFICATION_CHANNEL_ONGOING_ID = "com.wahibhaq.locationservicelivedata.ongoing"
16 | const val NOTIFICATION_CHANNEL_ALERTS_ID = "com.wahibhaq.locationservicelivedata.alerts"
17 |
18 | class NotificationsUtil(
19 | private val context: Context,
20 | private val notificationManager: NotificationManager
21 | ) {
22 |
23 | init {
24 | cancelAlertNotification() //to clear if there were any notifications
25 | }
26 |
27 | private val vibrationFlow = longArrayOf(0, 400, 200, 400)
28 |
29 | fun createOngoingNotification(
30 | service: Service,
31 | title: String,
32 | text: String,
33 | pendingIntent: PendingIntent?
34 | ) {
35 | createOngoingNotificationChannel()
36 | service.startForeground(
37 | ONGOING_NOTIFICATION_ID,
38 | NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ONGOING_ID)
39 | .setContentTitle(title)
40 | .setOngoing(true)
41 | .setContentText(text)
42 | .setSmallIcon(R.mipmap.ic_launcher_round)
43 | .setContentIntent(pendingIntent)
44 | .setPriority(NotificationCompat.PRIORITY_DEFAULT)
45 | .setStyle(NotificationCompat.DecoratedCustomViewStyle())
46 | .build()
47 | )
48 | }
49 |
50 | fun createAlertNotification(id: Int, title: String, text: String,
51 | pendingIntent: PendingIntent? = null) {
52 | val notificationBuilder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ALERTS_ID)
53 | .setContentTitle(title)
54 | .setAutoCancel(true)
55 | .setContentText(text)
56 | .setSmallIcon(R.mipmap.ic_launcher_round)
57 | .setContentIntent(pendingIntent)
58 | .setOnlyAlertOnce(true)
59 |
60 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
61 | NotificationChannel(
62 | NOTIFICATION_CHANNEL_ALERTS_ID,
63 | NOTIFICATION_CHANNEL_NAME,
64 | NotificationManager.IMPORTANCE_HIGH)
65 | .apply { vibrationPattern = vibrationFlow }
66 | .let { notificationManager.createNotificationChannel(it) }
67 | } else {
68 | notificationBuilder
69 | .setPriority(NotificationCompat.PRIORITY_HIGH)
70 | .setVibrate(vibrationFlow)
71 | }
72 |
73 | notificationManager.notify(id, notificationBuilder.build())
74 | }
75 |
76 | private fun createOngoingNotificationChannel() {
77 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
78 | NotificationChannel(
79 | NOTIFICATION_CHANNEL_ONGOING_ID, NOTIFICATION_CHANNEL_NAME,
80 | NotificationManager.IMPORTANCE_MIN)
81 | .let { channel ->
82 | notificationManager.createNotificationChannel(channel)
83 | }
84 | }
85 | }
86 |
87 | fun cancelAlertNotification() {
88 | notificationManager.cancel(ALERT_GPS_NOTIFICATION_ID)
89 | notificationManager.cancel(ALERT_PERMISSION_NOTIFICATION_ID)
90 | }
91 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
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 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/LocationService.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.Manifest
4 | import android.app.NotificationManager
5 | import android.app.PendingIntent
6 | import android.app.Service
7 | import android.arch.lifecycle.LifecycleService
8 | import android.arch.lifecycle.LiveData
9 | import android.arch.lifecycle.Observer
10 | import android.content.Context
11 | import android.content.Intent
12 | import android.net.Uri
13 | import android.os.IBinder
14 | import android.os.Looper
15 | import android.provider.Settings
16 | import android.text.format.DateUtils
17 | import com.google.android.gms.location.*
18 | import timber.log.Timber
19 |
20 | /**
21 | * Ideally this Service should be started/stopped based on [ActivityTransitionEvent] received in
22 | * Custom Broadcast Receiver in response to any activity which is specified like [DetectedActivity.RUNNING]
23 | */
24 | class LocationService : LifecycleService() {
25 |
26 | private lateinit var notificationsUtil: NotificationsUtil
27 |
28 | private lateinit var fusedLocationClient: FusedLocationProviderClient
29 |
30 | private lateinit var locationRequest: LocationRequest
31 |
32 | private var gpsIsEnabled = false
33 |
34 | private var permissionIsGranted = false
35 |
36 | private lateinit var gpsAndPermissionStatusLiveData: LiveData>
37 |
38 | private val locationPermission = Manifest.permission.ACCESS_FINE_LOCATION
39 |
40 | private val locationCallback = object : LocationCallback() {
41 | override fun onLocationResult(locationResult: com.google.android.gms.location.LocationResult) {
42 | //Decide how to use/store location coordinates
43 | Timber.d("New Coordinates Received: %s", locationResult.locations.toString())
44 | }
45 | }
46 |
47 | private val pairObserver = Observer> { pair ->
48 | pair?.let {
49 | Timber.i("Pairobserver received with %s and %s", pair.first, pair.second)
50 | handlePermissionStatus(pair.first)
51 | handleGpsStatus(pair.second)
52 | stopServiceIfNeeded()
53 | }
54 | }
55 |
56 | private fun handlePermissionStatus(status: PermissionStatus) {
57 | when (status) {
58 | is PermissionStatus.Granted -> {
59 | Timber.i("Service - Permission: %s", status.message)
60 | permissionIsGranted = true
61 | registerForLocationTracking()
62 | }
63 |
64 | is PermissionStatus.Denied -> {
65 | Timber.w("Service - Permission: %s", status.message)
66 | permissionIsGranted = false
67 | showPermissionIsMissingNotification()
68 | }
69 | }
70 | }
71 |
72 | private fun handleGpsStatus(status: GpsStatus) {
73 | when (status) {
74 | is GpsStatus.Enabled -> {
75 | Timber.i("Service - GPS: %s", status.message)
76 | gpsIsEnabled = true
77 | registerForLocationTracking()
78 | }
79 |
80 | is GpsStatus.Disabled -> {
81 | Timber.w("Service - GPS: %s", status.message)
82 | gpsIsEnabled = false
83 | showGpsIsDisabledNotification()
84 | }
85 | }
86 | }
87 |
88 | override fun onCreate() {
89 | super.onCreate()
90 | notificationsUtil = NotificationsUtil(applicationContext,
91 | applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
92 |
93 | fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
94 |
95 | locationRequest = LocationRequest.create().apply {
96 | interval = 5 * DateUtils.SECOND_IN_MILLIS
97 | priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
98 | }
99 |
100 | gpsAndPermissionStatusLiveData = with(application) {
101 | PermissionStatusListener(this, locationPermission)
102 | .combineLatestWith(GpsStatusListener(this))
103 | }
104 | }
105 |
106 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
107 | super.onStartCommand(intent, flags, startId)
108 | Timber.i("Tracking service getting started")
109 | showOnGoingNotification()
110 | startObservingGpsAndPermissionStatus()
111 | //Mainly because we want Service to restart if user revokes permission and to notify him
112 | return Service.START_STICKY
113 | }
114 |
115 | private fun startObservingGpsAndPermissionStatus() = gpsAndPermissionStatusLiveData
116 | .observe(this, pairObserver)
117 |
118 | private fun eitherPermissionOrGpsIsDisabled() = gpsIsEnabled.not() || permissionIsGranted.not()
119 |
120 | /**
121 | * We only start listening when Gps and Location Permission are enabled
122 | */
123 | private fun registerForLocationTracking() {
124 | if (permissionIsGranted && gpsIsEnabled) {
125 | Timber.i("Registering location update listener")
126 | isTrackingRunning = try {
127 | fusedLocationClient.requestLocationUpdates(
128 | locationRequest, locationCallback,
129 | Looper.myLooper())
130 | true
131 | } catch (unlikely: SecurityException) {
132 | Timber.e("Error when registerLocationUpdates()")
133 | error("Error when registerLocationUpdates()")
134 | }
135 | }
136 | }
137 |
138 | private fun unregisterFromLocationTracking() {
139 | Timber.i("Unregistering location update listener")
140 | try {
141 | fusedLocationClient.removeLocationUpdates(locationCallback)
142 | } catch (unlikely: SecurityException) {
143 | Timber.e("Error when unregisterLocationUpdated()")
144 | error("Error when unregisterLocationUpdated()")
145 | }
146 | }
147 |
148 | private fun showPermissionIsMissingNotification() {
149 | // Clicking notification will taker user to enable location setting screen
150 | val resultIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
151 | Uri.fromParts("package", packageName, null))
152 | val pendingIntent = PendingIntent.getActivity(
153 | applicationContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
154 |
155 | notificationsUtil.createAlertNotification(ALERT_PERMISSION_NOTIFICATION_ID,
156 | getString(R.string.permission_required_title),
157 | getString(R.string.permission_required_body),
158 | pendingIntent)
159 | }
160 |
161 | private fun showGpsIsDisabledNotification() {
162 | // Clicking notification will taker user to enable location setting screen
163 | val resultIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
164 | val pendingIntent = PendingIntent.getActivity(
165 | applicationContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
166 |
167 | notificationsUtil.createAlertNotification(
168 | ALERT_GPS_NOTIFICATION_ID,
169 | getString(R.string.gps_required_title),
170 | getString(R.string.gps_required_body),
171 | pendingIntent)
172 | }
173 |
174 | private fun showOnGoingNotification() {
175 | Timber.i("showing showing ongoing notification")
176 | notificationsUtil.cancelAlertNotification() //remove existing alert notifs if any
177 | isServiceRunning = true
178 | Intent(this, MainActivity::class.java)
179 | .let { PendingIntent.getActivity(this, 0, it, 0) }
180 | .let { pendingIntent ->
181 | notificationsUtil.createOngoingNotification(this,
182 | getString(R.string.notif_location_tracking_title), getString(R.string.notif_in_progress),
183 | pendingIntent)
184 | }
185 | }
186 |
187 | override fun onBind(intent: Intent): IBinder {
188 | super.onBind(intent)
189 | throw UnsupportedOperationException("Not yet implemented")
190 | }
191 |
192 | override fun onDestroy() {
193 | super.onDestroy()
194 | Timber.i("Service is destroyed now")
195 | isTrackingRunning = false
196 | isServiceRunning = false
197 |
198 | //Only attempt to stop tracking when you know startTracking() was already called
199 | if (eitherPermissionOrGpsIsDisabled().not()) unregisterFromLocationTracking()
200 | }
201 |
202 | /**
203 | * This is to handle case when GPS or Permission wasn't enabled but start of activity via
204 | * [ActivityTransition.ACTIVITY_TRANSITION_ENTER] got detected.
205 | * Once Notifications are shown, there's no need to continue tracking because app won't be able
206 | * to receive location coordinates.
207 | */
208 | private fun stopServiceIfNeeded() {
209 | if (eitherPermissionOrGpsIsDisabled()) {
210 | //Maybe you would like to store last coordinate before killing the service
211 | stopSelf()
212 | }
213 | }
214 |
215 | companion object {
216 | //Refers to when this service is running and foreground notification is being displayed
217 | var isServiceRunning: Boolean = false
218 | private set
219 |
220 | //Refers to when app is listening to location updates
221 | var isTrackingRunning: Boolean = false
222 | private set
223 | }
224 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/wahibhaq/locationservicelivedata/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.wahibhaq.locationservicelivedata
2 |
3 | import android.Manifest
4 | import android.arch.lifecycle.Observer
5 | import android.arch.lifecycle.ViewModelProviders
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.graphics.Color
9 | import android.os.Build
10 | import android.os.Bundle
11 | import android.os.Handler
12 | import android.provider.Settings
13 | import android.support.v7.app.AlertDialog
14 | import android.support.v7.app.AppCompatActivity
15 | import android.view.View
16 | import com.nabinbhandari.android.permissions.PermissionHandler
17 | import com.nabinbhandari.android.permissions.Permissions
18 | import com.wahibhaq.locationservicelivedata.LocationService.Companion.isServiceRunning
19 | import com.wahibhaq.locationservicelivedata.LocationService.Companion.isTrackingRunning
20 | import kotlinx.android.synthetic.main.activity_main.*
21 | import timber.log.Timber
22 | import java.util.*
23 |
24 | class MainActivity : AppCompatActivity() {
25 |
26 | private lateinit var viewModel: MainViewModel
27 |
28 | private var alertDialog: AlertDialog? = null
29 |
30 | private val gpsObserver = Observer { status ->
31 | status?.let {
32 | updateGpsCheckUI(status)
33 | }
34 | }
35 |
36 | private val permissionObserver = Observer { status ->
37 | status?.let {
38 | updatePermissionCheckUI(status)
39 | when (status) {
40 | is PermissionStatus.Granted -> handleGpsAlertDialog()
41 | is PermissionStatus.Denied -> showLocationPermissionNeededDialog()
42 | }
43 | }
44 | }
45 |
46 | private val permissionHandler = object : PermissionHandler() {
47 | override fun onGranted() {
48 | Timber.i("Activity: %s", R.string.permission_status_granted)
49 | updatePermissionCheckUI(PermissionStatus.Granted())
50 | handleGpsAlertDialog()
51 | }
52 |
53 | override fun onDenied(context: Context?, deniedPermissions: ArrayList?) {
54 | Timber.w("Activity: %s", R.string.permission_status_denied)
55 | updatePermissionCheckUI(PermissionStatus.Denied())
56 | }
57 |
58 | override fun onJustBlocked(
59 | context: Context?,
60 | justBlockedList: ArrayList?,
61 | deniedPermissions: ArrayList?
62 | ) {
63 | Timber.w("Activity: %s", R.string.permission_status_blocked)
64 | updatePermissionCheckUI(PermissionStatus.Blocked())
65 | }
66 | }
67 |
68 | private fun updateGpsCheckUI(status: GpsStatus) {
69 | when (status) {
70 | is GpsStatus.Enabled -> {
71 | gpsStatusDisplay.isEnabled = false
72 | gpsStatusDisplay.apply {
73 | text = getString(status.message)
74 | setTextColor(Color.BLUE)
75 | }
76 |
77 | handleGpsAlertDialog(GpsStatus.Enabled())
78 | }
79 |
80 | is GpsStatus.Disabled -> {
81 | gpsStatusDisplay.isEnabled = true
82 | gpsStatusDisplay.apply {
83 | text = getString(status.message).plus(getString(R.string.click_to_retry))
84 | setTextColor(Color.RED)
85 | }
86 | }
87 | }
88 |
89 | toggleButtonClickableState()
90 | }
91 |
92 | private fun updatePermissionCheckUI(status: PermissionStatus) {
93 | when (status) {
94 | is PermissionStatus.Granted -> {
95 | permissionStatusDisplay.isEnabled = false
96 | permissionStatusDisplay.apply {
97 | text = getString(status.message)
98 | setTextColor(Color.BLUE)
99 | }
100 | }
101 |
102 | is PermissionStatus.Denied -> {
103 | permissionStatusDisplay.isEnabled = true
104 | permissionStatusDisplay.apply {
105 | text = getString(status.message).plus(getString(R.string.click_to_retry))
106 | setTextColor(Color.RED)
107 | }
108 | }
109 |
110 | is PermissionStatus.Blocked -> {
111 | permissionStatusDisplay.isEnabled = true
112 | permissionStatusDisplay.apply {
113 | text = getString(status.message).plus(getString(R.string.click_to_retry))
114 | setTextColor(Color.RED)
115 | }
116 | }
117 | }
118 |
119 | toggleButtonClickableState()
120 | }
121 |
122 | private fun isTrackingRunningAlready() = isTrackingRunning && isServiceRunning
123 |
124 | private fun setupUI() {
125 |
126 | //Start Tracking Only if there is a need and it's valid to start tracking
127 | if (isTrackingRunningAlready()) btnControlTracking.text = getString(R.string.button_text_end)
128 | btnControlTracking.setOnClickListener {
129 | if (isTrackingRunningAlready().not())
130 | startTracking()
131 | else
132 | stopTracking()
133 | }
134 |
135 | /**
136 | * This is to simulate how user is alerted via notifications when activity start is detected
137 | * in background by [LocationService]
138 | */
139 | btnSimulateNotification.setOnClickListener {
140 | Handler().apply {
141 | postDelayed({ viewModel.startLocationTracking() }, 3000)
142 | }
143 | }
144 |
145 | gpsStatusDisplay.setOnClickListener { handleGpsAlertDialog() }
146 |
147 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
148 | permissionStatusDisplay.visibility = View.VISIBLE
149 | permissionStatusDisplay.setOnClickListener { showLocationPermissionNeededDialog() }
150 | }
151 | }
152 |
153 | private fun toggleButtonClickableState() {
154 | btnControlTracking.isEnabled = gpsStatusDisplay.isEnabled.not() && permissionStatusDisplay.isEnabled.not()
155 | btnSimulateNotification.isEnabled = btnControlTracking.isEnabled.not()
156 | }
157 |
158 | override fun onCreate(savedInstanceState: Bundle?) {
159 | super.onCreate(savedInstanceState)
160 | setContentView(R.layout.activity_main)
161 |
162 | viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
163 |
164 | subscribeToGpsListener()
165 | subscribeToLocationPermissionListener()
166 | }
167 |
168 | private fun subscribeToGpsListener() = viewModel.gpsStatusLiveData
169 | .observe(this, gpsObserver)
170 |
171 | private fun subscribeToLocationPermissionListener() =
172 | viewModel.locationPermissionStatusLiveData.observe(this, permissionObserver)
173 |
174 | private fun startTracking() {
175 | Timber.i("Tracking start triggered from Button on Activity")
176 | viewModel.startLocationTracking()
177 | btnControlTracking.text = getString(R.string.button_text_end)
178 | }
179 |
180 | private fun stopTracking() {
181 | Timber.i("Tracking stop triggered from Activity")
182 | viewModel.stopLocationTracking()
183 | btnControlTracking.text = getString(R.string.button_text_start)
184 | }
185 |
186 | override fun onResume() {
187 | super.onResume()
188 | setupUI()
189 | }
190 |
191 | /**
192 | * Using current value of [GpsStatusListener] livedata as default
193 | */
194 | private fun handleGpsAlertDialog(status: GpsStatus = viewModel.gpsStatusLiveData.value as GpsStatus) {
195 | when (status) {
196 | is GpsStatus.Enabled -> hideGpsNotEnabledDialog()
197 | is GpsStatus.Disabled -> showGpsNotEnabledDialog()
198 | }
199 | }
200 |
201 | private fun showGpsNotEnabledDialog() {
202 | if (alertDialog?.isShowing == true) {
203 | return // null or already being shown
204 | }
205 |
206 | alertDialog = AlertDialog.Builder(this)
207 | .setTitle(R.string.gps_required_title)
208 | .setMessage(R.string.gps_required_body)
209 | .setPositiveButton(R.string.action_settings) { _, _ ->
210 | // Open app's settings.
211 | val intent = Intent().apply {
212 | action = Settings.ACTION_LOCATION_SOURCE_SETTINGS
213 | }
214 | startActivity(intent)
215 | }
216 | .setNegativeButton(android.R.string.cancel, null)
217 | .show()
218 | }
219 |
220 | private fun hideGpsNotEnabledDialog() {
221 | if (alertDialog?.isShowing == true) alertDialog?.dismiss()
222 | }
223 |
224 | private fun showLocationPermissionNeededDialog() {
225 | if (alertDialog?.isShowing == true) {
226 | return // null or dialog already being shown
227 | }
228 |
229 | alertDialog = AlertDialog.Builder(this)
230 | .setTitle(R.string.permission_required_title)
231 | .setMessage(R.string.permission_required_body)
232 | .setPositiveButton(android.R.string.ok) { _, _ ->
233 | //Using 3rd party lib *Permissions* for showing dialogs and handling response
234 | Permissions.check(this,
235 | Manifest.permission.ACCESS_FINE_LOCATION,
236 | null,
237 | permissionHandler)
238 | }
239 | .setCancelable(false) //to disable outside click for cancel
240 | .create()
241 |
242 | alertDialog?.apply {
243 | show()
244 | }
245 | }
246 | }
247 |
--------------------------------------------------------------------------------