Every 30 min. tracking in android studio kotlin
Every 30 min. tracking in android studio kotlin
__________________________________________________
__________________________________________________
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.IBinder
import android.provider.Settings
import java.io.IOException
* Created by JeeteshSurana.
class GPSTracker(private val mContext: Context) : Service(), LocationListener {
internal var isGPSEnabled = false
// flag for network status
internal var isNetworkEnabled = false
// flag for GPS Tracking is enabled
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
var isGPSTrackingEnabled = false
internal var location: Location? = null
internal var latitude: Double = 0.toDouble()
internal var longitude: Double = 0.toDouble()
// How many Geocoder should return our GPSTracker
internal var geocoderMaxResults = 1
// Declaring a Location Manager
protected var locationManager: LocationManager? = null
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private var provider_info: String? = null
* Try to get my current location by GPS or Network Provider
@SuppressLint("MissingPermission")
locationManager = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
isGPSEnabled = locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER)
isNetworkEnabled = locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
// Try to get location if you GPS Service is enabled
this.isGPSTrackingEnabled = true
Log.d(TAG, "Application use GPS Service")
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
provider_info = LocationManager.GPS_PROVIDER
} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true
Log.d(TAG, "Application use Network State to get GPS coordinates")
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
provider_info = LocationManager.NETWORK_PROVIDER
// Application can use GPS or Network Provider
if (!provider_info!!.isEmpty()) {
locationManager!!.requestLocationUpdates(
MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(),
if (locationManager != null) {
location = locationManager!!.getLastKnownLocation(provider_info)
Log.e(TAG, "Impossible to connect to LocationManager", e)
* Update GPSTracker latitude and longitude
fun updateGPSCoordinates() {
latitude = location!!.latitude
longitude = location!!.longitude
* GPSTracker latitude getter and setter
fun getLatitude(): Double {
latitude = location!!.latitude
* GPSTracker longitude getter and setter
fun getLongitude(): Double {
longitude = location!!.longitude
* Stop using GPS listener
* Calling this method will stop using GPS in your app
if (locationManager != null) {
locationManager!!.removeUpdates(this@GPSTracker)
* Function to show settings alert dialog
fun showSettingsAlert() {
val alertDialog = AlertDialog.Builder(mContext)
alertDialog.setTitle("Title")
alertDialog.setMessage("Dialog")
//On Pressing Setting button
alertDialog.setPositiveButton("Yes") { dialog, which ->
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
mContext.startActivity(intent)
//On pressing cancel button
alertDialog.setNegativeButton("Cancel") { dialog, which -> dialog.cancel() }
* Get list of address by latitude and longitude
* @return null or List<Address>
fun getGeocoderAddress(context: Context): List<Address>? {
val geocode = Geocoder(context, Locale.ENGLISH)
return geocode.getFromLocation(latitude, longitude, geocoderMaxResults)
} catch (e: IOException) {
Log.e(TAG, "Impossible to connect to Geocoder", e)
* @return null or addressLine
fun getAddressLine(context: Context): String? {
val addresses = getGeocoderAddress(context)
if (addresses != null && addresses.isNotEmpty()) {
val address = addresses[0]
return address.getAddressLine(0)
* @return null or locality
fun getLocality(context: Context): String? {
val addresses = getGeocoderAddress(context)
if (addresses != null && addresses.isNotEmpty()) {
val address = addresses[0]
* @return null or postalCode
fun getPostalCode(context: Context): String? {
val addresses = getGeocoderAddress(context)
if (addresses != null && addresses.isNotEmpty()) {
val address = addresses[0]
return address.postalCode
* @return null or postalCode
fun getCountryName(context: Context): String? {
val addresses = getGeocoderAddress(context)
if (addresses != null && addresses.size > 0) {
val address = addresses[0]
return address.countryName
override fun onLocationChanged(location: Location) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
override fun onBind(intent: Intent): IBinder? {
private val TAG = GPSTracker::class.java.name
// The minimum distance to change updates in meters
private val MIN_DISTANCE_CHANGE_FOR_UPDATES: Long = 10 // 10 meters
// The minimum time between updates in milliseconds
private val MIN_TIME_BW_UPDATES = (1000 * 60 * 1).toLong() // 1 minute
__________________________________________________
__________________________________________________
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.justcodenow.reportingapp.util.Constant
* Created by JeeteshSurana.
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent!!.action == "android.intent.action.BOOT_COMPLETED") {
cancelHourlyAlarm(context!!)
} else if (intent.action == "android.intent.action.MY_PACKAGE_REPLACED") {
cancelHourlyAlarm(context!!)
private fun setHourlyAlarm(context: Context) {
val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AlarmReceiver::class.java)
intent.putExtra(Constant.IntentKeys().ALARM_REQ_CODE, Constant.HOURLY_ALARM_REQ_CODE)
intent.action = AlarmReceiver.ACTION_ALARM_RECEIVER
val alarmIntent = PendingIntent.getBroadcast(context, Constant.HOURLY_ALARM_REQ_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT)
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,Constant.triggerAtMillis ,Constant.interValTime, alarmIntent)
// alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 1000, 5 * 60 * 1000, alarmIntent);
private fun isHourlyAlarmRunning(context: Context): Boolean {
val intent = Intent(context, AlarmReceiver::class.java)
intent.action = AlarmReceiver.ACTION_ALARM_RECEIVER
val isWorking = PendingIntent.getBroadcast(context, Constant.HOURLY_ALARM_REQ_CODE, intent, PendingIntent.FLAG_NO_CREATE) != null
Log.d("Tag", "alarm is " + (if (isWorking) "" else "not") + " working...")
private fun cancelHourlyAlarm(context: Context) {
if (isHourlyAlarmRunning(context)) {
val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AlarmReceiver::class.java)
val pIntent = PendingIntent.getBroadcast(context, Constant.HOURLY_ALARM_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT)
if (pIntent != null) alarmMgr.cancel(pIntent)
__________________________________________________
__________________________________________________
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.text.TextUtils
import androidx.core.app.ActivityCompat
import com.justcodenow.reportingapp.data.local.PreferenceManager
import com.justcodenow.reportingapp.service.GpsIntentService
import com.justcodenow.reportingapp.util.Constant
* Created by JeeteshSurana.
class AlarmReceiver : BroadcastReceiver() {
const val ACTION_ALARM_RECEIVER = "ACTION_ALARM_RECEIVER"
var mPreferenceManager: PreferenceManager? = null
var roleID: String? = null
private var manager: LocationManager? = null
override fun onReceive(context: Context?, intent: Intent?) {
val prefs = context!!.applicationContext.getSharedPreferences(Constant.MyPrefsFile, Context.MODE_PRIVATE)
mPreferenceManager = PreferenceManager(prefs)
manager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
roleID = mPreferenceManager!!.getValue(Constant.roleId, "")!!
if (roleID == Constant.manager || roleID == Constant.salesPerson) {
if (checkPermission(context)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, GpsIntentService::class.java))
context.startService(Intent(context, GpsIntentService::class.java))
private fun isUserLoggedIn(): Boolean {
return !TextUtils.isEmpty(mPreferenceManager!!.getValue(Constant.sharedLogin, ""))
private fun checkPermission(context: Context): Boolean {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
__________________________________________________
__________________________________________________
<receiver android:name=".receiver.BootReceiver">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
<receiver android:name=".receiver.AlarmReceiver"/>
android:name=".service.GpsIntentService"
__________________________________________________
implementation fun callService
__________________________________________________
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(Intent(this, GpsIntentService::class.java))
startService(Intent(this, GpsIntentService::class.java))
if (!isHourlyAlarmRunning(this)) setHourlyAlarm(this)
private fun setHourlyAlarm(context: Context) {
val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AlarmReceiver::class.java)
intent.putExtra(Constant.IntentKeys().ALARM_REQ_CODE, Constant.HOURLY_ALARM_REQ_CODE)
intent.action = AlarmReceiver.ACTION_ALARM_RECEIVER
val alarmIntent = PendingIntent.getBroadcast(context, Constant.HOURLY_ALARM_REQ_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT)
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, Constant.triggerAtMillis, Constant.interValTime, alarmIntent)
private fun isHourlyAlarmRunning(context: Context): Boolean {
val intent = Intent(context, AlarmReceiver::class.java)
intent.action = AlarmReceiver.ACTION_ALARM_RECEIVER
val isWorking = PendingIntent.getBroadcast(context, Constant.HOURLY_ALARM_REQ_CODE, intent, PendingIntent.FLAG_NO_CREATE) != null
Log.d("Tag", "alarm is " + (if (isWorking) "" else "not") + " working...")
via Blogger http://bit.ly/2J0ibSU