Thomas Chef 3 лет назад
Родитель
Сommit
a3eca430c0

+ 72 - 24
app/src/main/java/com/flacksta/chef/journeygpstracker/TrackingService.kt

@@ -3,7 +3,6 @@ package com.flacksta.chef.journeygpstracker
 import android.Manifest
 import android.app.*
 import android.app.Notification.FOREGROUND_SERVICE_IMMEDIATE
-import android.content.Context
 import android.content.Intent
 import android.content.pm.PackageManager
 import android.graphics.Bitmap
@@ -20,32 +19,41 @@ import com.flacksta.chef.journeygpstracker.backend.BackendClient
 import com.flacksta.chef.journeygpstracker.database.GpsData
 import com.flacksta.chef.journeygpstracker.database.GpsPosRepository
 import com.google.android.gms.location.*
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
+import kotlinx.coroutines.*
 
 class TrackingService : Service() {
 
     private val mTag: String = "TrackingService"
 
-    var counter = 0
     private lateinit var mFusedLocationClient: FusedLocationProviderClient
     private lateinit var mLocationRequest: LocationRequest
     private lateinit var mLocationCallback: LocationCallback
     private lateinit var trackApp : JourneyGpsTrackerApplication
+    private lateinit var mNotificationManager: NotificationManager
+    private lateinit var mNotifyBuilder : NotificationCompat.Builder
+
     private val mNotificationId = 123
+    private val CHANNEL_ID = "JourneyGPSTracker_Notifications"
     private var isServiceStarted = false
 
+    private var locRxCounter = 0
+    private var totalDist : Double = 0.0
+
+
     override fun onCreate() {
         super.onCreate()
         Log.i(mTag,"onCreate()")
         trackApp = JourneyGpsTrackerApplication()
-        startForeground(mNotificationId, generateForegroundNotification() )
+        getNotificationManager()
+        createChannel()
+        buildNotification() // Sets mNotifyBuilder
+        startForeground(mNotificationId, mNotifyBuilder.build() )
     }
 
     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
         super.onStartCommand(intent, flags, startId)
         Log.i(mTag,"onStartCommand()")
+
         if (intent != null) {
             val action = intent.action
             Log.i(mTag, "onStartCommand() action $action")
@@ -86,13 +94,24 @@ class TrackingService : Service() {
             priority = LocationRequest.PRIORITY_HIGH_ACCURACY
         }
 
+        var lastLocation : Location = Location("Stockholm")
+        var lastLocInitialized : Boolean = false
+
         mLocationCallback = object : LocationCallback() {
             override fun onLocationResult(locationResult: LocationResult?) {
                 locationResult ?: return
+
                 for (location in locationResult.locations){
-                    counter += 1
-                    val acc = location.accuracy
-                    Log.i(mTag, "Got location: $counter  $acc")
+                    locRxCounter += 1
+                    if( !lastLocInitialized ) {
+                        lastLocation = location
+                        lastLocInitialized = true
+                    }
+                    val dist : Float = location.distanceTo(lastLocation)
+
+                    Log.i(mTag, "Got location: $locRxCounter  Dist:$dist")
+                    totalDist += dist
+
                     CoroutineScope(Dispatchers.Default).launch {
                         insertPos(location)
                     }
@@ -114,6 +133,13 @@ class TrackingService : Service() {
         repo.insert(d)
     }
 
+    fun startNotificationUpdateTimer() = GlobalScope.launch {
+        while (true) {
+            updateNotification()
+            delay(1000)
+        }
+    }
+
     private fun startService() {
         if(isServiceStarted) return
         Log.i(mTag,"startService()")
@@ -122,6 +148,7 @@ class TrackingService : Service() {
         setServiceState(this, ServiceState.STARTED)
         requestLocationUpdates()
         BackendClient()
+        startNotificationUpdateTimer()
     }
 
     private fun stopService() {
@@ -137,28 +164,43 @@ class TrackingService : Service() {
         setServiceState(this, ServiceState.STOPPED)
     }
 
-    private fun generateForegroundNotification() : Notification {
+    private fun getNotificationManager() {
+        mNotificationManager = ContextCompat.getSystemService(
+                this,
+                NotificationManager::class.java
+        ) as NotificationManager
+    }
 
-        val mNotificationManager: NotificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
-        val iconNotification: Bitmap? = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
-        val intentMainLanding = Intent(this, MainActivity::class.java)
-        val pendingIntent = PendingIntent.getActivity(this, 0, intentMainLanding, PendingIntent.FLAG_IMMUTABLE)
+    private fun createChannel() {
 
         mNotificationManager.createNotificationChannelGroup(
                 NotificationChannelGroup("chats_group", "Chats")
         )
-        val notificationChannel =
-                NotificationChannel("service_channel", "Service Notifications",
-                        NotificationManager.IMPORTANCE_MIN)
+
+        val notificationChannel = NotificationChannel(
+                CHANNEL_ID,
+                "GPSTracker",
+                NotificationManager.IMPORTANCE_MIN
+        )
+        notificationChannel.setSound(null, null)
         notificationChannel.enableLights(false)
+        notificationChannel.setShowBadge(true)
         notificationChannel.lockscreenVisibility = Notification.VISIBILITY_SECRET
         mNotificationManager.createNotificationChannel(notificationChannel)
+    }
+
+
+    private fun buildNotification() {
 
-        val builder = NotificationCompat.Builder(this, "service_channel")
+        val iconNotification: Bitmap? = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
+        val intentMainLanding = Intent(this, MainActivity::class.java)
+        val pendingIntent = PendingIntent.getActivity(this, 0, intentMainLanding, PendingIntent.FLAG_IMMUTABLE)
+
+        mNotifyBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
 
-        builder.setContentTitle(StringBuilder(resources.getString(R.string.app_name)).append(" is tracking your journey.").toString())
+        mNotifyBuilder.setContentTitle(StringBuilder(resources.getString(R.string.app_name)).append(" is tracking your journey.").toString())
                 .setTicker(StringBuilder(resources.getString(R.string.app_name)).append("service is running").toString())
-                .setContentText("Touch to open the App") //                    , swipe down for more options.
+                .setContentText("Touch to open the App. Cnt:$locRxCounter")
                 .setSmallIcon(R.drawable.ic_baseline_map_24)
                 .setPriority(NotificationCompat.PRIORITY_LOW)
                 .setWhen(0)
@@ -167,11 +209,17 @@ class TrackingService : Service() {
                 .setOngoing(true)
                 .setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE)
         if (iconNotification != null) {
-            builder.setLargeIcon(Bitmap.createScaledBitmap(iconNotification, 128, 128, false))
+            mNotifyBuilder.setLargeIcon(Bitmap.createScaledBitmap(iconNotification, 128, 128, false))
         }
-        builder.color = ContextCompat.getColor(this, R.color.purple_200)
-        return builder.build()
+        mNotifyBuilder.color = ContextCompat.getColor(this, R.color.purple_200)
     }
 
-
+    private fun updateNotification() {
+        val d:String = String.format("%.1f", totalDist / 1000)
+        mNotifyBuilder.setContentText(resources.getString(R.string.notification_desc) +d + "km")
+        mNotificationManager.notify(
+                mNotificationId,
+                mNotifyBuilder.build(),
+        )
+    }
 }

+ 2 - 0
app/src/main/res/values/strings.xml

@@ -4,4 +4,6 @@
     <string name="hello_blank_fragment">Hello blank fragment</string>
 
     <string name="tracking_service_desc">GPS Journey tracking service.</string>
+
+    <string name="notification_desc">Touch to open the App. Dist:</string>
 </resources>