Skip to content

Instantly share code, notes, and snippets.

@GabrielCzar
Last active May 12, 2018 14:33
Show Gist options
  • Save GabrielCzar/93b70ccf02d4d34f685d2b6656fb6882 to your computer and use it in GitHub Desktop.
Save GabrielCzar/93b70ccf02d4d34f685d2b6656fb6882 to your computer and use it in GitHub Desktop.
Location Service Kotlin Android With Permissions Dispatcher and RX Location Manager
<!-- Only permissions necessary -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<!-- Inside application tag -->
<service android:name=".LocationService"/>
class LocationService : Service() {
val TAG : String = "LOCATION_SERVICE"
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val rxLocationManager = RxLocationManager(this)
rxLocationManager
.requestLocation(
LocationManager.GPS_PROVIDER,
LocationTime(1, TimeUnit.MINUTES))
.subscribe({
location: Location ->
Log.d(TAG, location.toString()) // show location data
Log.d(TAG, intent?.getStringExtra("TST")) // get data pass by intent
// use data
})
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "DESTROY")
}
}
@RuntimePermissions
class MainActivity : AppCompatActivity() {
private val TAG: String = "MAIN_ACTIVITY"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_show_location.setOnClickListener {
Log.d(TAG, "CLICK START")
requestLocationWithPermissionCheck()
}
}
@NeedsPermission(ACCESS_FINE_LOCATION)
fun requestLocation() {
Log.d(TAG, "REQUEST LOCATION")
val i = Intent(this, LocationService::class.java)
i.putExtra("TST", "TEST")
startService(i) // request service to update location
stopService(i) // stop service but location is requested yet
}
@OnPermissionDenied(ACCESS_FINE_LOCATION)
fun onLocationDenied() {
Toast.makeText(this, R.string.permission_location_denied, Toast.LENGTH_SHORT).show()
}
@OnNeverAskAgain(ACCESS_FINE_LOCATION)
fun onLocationNeverAskAgain() {
Toast.makeText(this, R.string.permission_location, Toast.LENGTH_SHORT).show()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment