Explorar o código

Some cleaning up...

Thomas Chef %!s(int64=3) %!d(string=hai) anos
pai
achega
293ef28ffd

+ 1 - 1
app/build.gradle

@@ -10,7 +10,7 @@ android {
 
     defaultConfig {
         applicationId "com.flacksta.chef.journeygpstracker"
-        minSdk 29
+        minSdk 31
         targetSdk 32
         versionCode 1
         versionName "1.0"

+ 0 - 9
app/src/main/java/com/flacksta/chef/journeygpstracker/MainActivity.kt

@@ -9,9 +9,7 @@ import androidx.activity.result.contract.ActivityResultContracts
 import androidx.appcompat.app.AppCompatActivity
 import androidx.core.content.ContextCompat
 import androidx.fragment.app.Fragment
-import com.flacksta.chef.journeygpstracker.backend.BackendClient
 import com.flacksta.chef.journeygpstracker.databinding.ActivityMainScreenBinding
-import com.google.android.gms.location.*
 
 class MainActivity : AppCompatActivity() {
 
@@ -22,19 +20,12 @@ class MainActivity : AppCompatActivity() {
 
     private val mTag: String = "MainActivity"
 
-    private lateinit var mFusedLocationClient: FusedLocationProviderClient
-
-    //private val noteDatabase by lazy { GpsPosRoomDatabase.getDatabase(this) }
-
-
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         binding = ActivityMainScreenBinding.inflate(layoutInflater)
 
         setContentView(binding.root)
 
-        val trackApp : JourneyGpsTrackerApplication = JourneyGpsTrackerApplication()
-
         binding.bottomNavigationView.setOnItemSelectedListener {
             val fragment = when (it.itemId) {
                 R.id.map -> {

+ 20 - 18
app/src/main/java/com/flacksta/chef/journeygpstracker/TrackingService.kt

@@ -2,15 +2,18 @@ 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
 import android.graphics.BitmapFactory
 import android.location.Location
+import android.os.Build
 import android.os.IBinder
 import android.os.Looper
 import android.util.Log
+import androidx.annotation.RequiresApi
 import androidx.core.app.ActivityCompat
 import androidx.core.app.NotificationCompat
 import androidx.core.content.ContextCompat
@@ -18,10 +21,7 @@ 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.GlobalScope
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.*
 
 class TrackingService : Service() {
 
@@ -39,20 +39,14 @@ class TrackingService : Service() {
         Log.i(mTag,"onCreate()")
         generateForegroundNotification()
         trackApp = JourneyGpsTrackerApplication()
-        startForeground(mNotificationId, notification)
+        startForeground(mNotificationId, generateForegroundNotification() )
 
         // Start background upload functions...
-        val bec: BackendClient = BackendClient()
+        BackendClient()
 
         Log.i(mTag,"Requested foreground service...")
     }
 
-    private fun insertPos(pos: Location) = GlobalScope.launch {
-        var d = GpsData(0, pos.time, pos.latitude, pos.longitude, pos.accuracy, false)
-        val repo: GpsPosRepository = trackApp.repository
-        repo.insert(d)
-    }
-
     private fun requestLocationUpdates() {
 
         mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
@@ -70,7 +64,9 @@ class TrackingService : Service() {
                     counter += 1
                     val acc = location.accuracy
                     Log.i(mTag, "Got location: $counter  $acc")
-                    insertPos(location)
+                    CoroutineScope(Dispatchers.Default).launch {
+                        insertPos(location)
+                    }
                 }
             }
         }
@@ -83,6 +79,12 @@ class TrackingService : Service() {
         }
     }
 
+    private suspend fun insertPos(pos: Location) {
+        val d = GpsData(0, pos.time, pos.latitude, pos.longitude, pos.accuracy, false)
+        val repo: GpsPosRepository = trackApp.repository
+        repo.insert(d)
+    }
+
     override fun onBind(intent: Intent): IBinder? {
         Log.i(mTag,"onBind()")
         return null
@@ -96,11 +98,10 @@ class TrackingService : Service() {
     }
 
     private var iconNotification: Bitmap? = null
-    private var notification: Notification? = null
     private var mNotificationManager: NotificationManager? = null
     private val mNotificationId = 123
 
-    private fun generateForegroundNotification() {
+    private fun generateForegroundNotification() : Notification {
         val intentMainLanding = Intent(this, MainActivity::class.java)
         val pendingIntent =
                 PendingIntent.getActivity(this, 0, intentMainLanding, PendingIntent.FLAG_IMMUTABLE)
@@ -122,20 +123,21 @@ class TrackingService : Service() {
 
         val builder = NotificationCompat.Builder(this, "service_channel")
 
-        builder.setContentTitle(StringBuilder(resources.getString(R.string.app_name)).append(" service is running").toString())
+        builder.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") //                    , swipe down for more options.
+                .setContentText("Touch to open the App") //                    , swipe down for more options.
                 .setSmallIcon(R.drawable.ic_baseline_map_24)
                 .setPriority(NotificationCompat.PRIORITY_LOW)
                 .setWhen(0)
                 .setOnlyAlertOnce(true)
                 .setContentIntent(pendingIntent)
                 .setOngoing(true)
+                .setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE)
         if (iconNotification != null) {
             builder.setLargeIcon(Bitmap.createScaledBitmap(iconNotification!!, 128, 128, false))
         }
         builder.color = ContextCompat.getColor(this, R.color.purple_200)
-        builder.build().also { notification = it }
+        return builder.build()
     }
 
     override fun onDestroy() {

+ 18 - 22
app/src/main/java/com/flacksta/chef/journeygpstracker/backend/BackendClient.kt

@@ -1,5 +1,6 @@
 package com.flacksta.chef.journeygpstracker.backend
 
+import android.annotation.SuppressLint
 import android.util.Log
 import com.flacksta.chef.journeygpstracker.JourneyGpsTrackerApplication
 import com.flacksta.chef.journeygpstracker.database.GpsData
@@ -21,44 +22,42 @@ import kotlin.concurrent.fixedRateTimer
 
 class BackendClient {
 
-    private lateinit var trackApp : JourneyGpsTrackerApplication
+    private var trackApp : JourneyGpsTrackerApplication = JourneyGpsTrackerApplication()
 
     init {
-        trackApp = JourneyGpsTrackerApplication()
         startTimer()
     }
 
-    fun startTimer() {
-        val fixedRateTimer = fixedRateTimer(name = "hello-timer",
+    private fun startTimer() {
+        fixedRateTimer(name = "hello-timer",
                 initialDelay = 10000, period = 30000) {
 
             val  dao :GpsDataDao = trackApp.database.gpsDataDao()
 
             Log.i("Thc","Sending data....")
             val pos : List<GpsData> = dao.getUnsentGpsPositions()
-            val rawJson:String = convertPosListToRawJson(pos)
-            Log.i("Thc","Count:" + rawJson)
-            Log.i("Thc","Thread A:"+Thread.currentThread())
-            val retVal:Boolean = sendGpsPosDataToBackendServer(rawJson)
-            Log.i("Thc","retVal post: $retVal")
-            if( retVal == true ) {
-                // Delete the successful ones
-                val first: Long = pos.get(0).ts
-                val last: Long = pos.get(pos.size - 1).ts
-                dao.setAsUploaded(first,last)
+            if( pos.isNotEmpty() ) {
+                val rawJson: String = convertPosListToRawJson(pos)
+                val retVal: Boolean = sendGpsPosDataToBackendServer(rawJson)
+                Log.i("Thc", "retVal post: $retVal")
+                if (retVal) {
+                    // Delete the successful ones
+                    val first: Long = pos[0].ts
+                    val last: Long = pos[pos.size - 1].ts
+                    dao.setAsUploaded(first, last)
+                }
             }
         }
     }
 
+    @SuppressLint("SimpleDateFormat")
     fun convertPosListToRawJson(pos:List<GpsData>) : String {
 
         val ja = JSONArray()
-
         val simpleDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
 
         for (p in pos) {
-            Log.i("Thc","Acc:" + p.accuracy)
-            var jo = JSONObject()
+            val jo = JSONObject()
             jo.put("latitude", p.latitude.toString())
             jo.put("longitude", p.longitude.toString())
             jo.put("ts", simpleDate.format(p.ts))
@@ -68,9 +67,8 @@ class BackendClient {
         return ja.toString()
     }
 
-    fun sendGpsPosDataToBackendServer(jsonObjectString: String): Boolean = runBlocking() {
+    private fun sendGpsPosDataToBackendServer(jsonObjectString: String): Boolean = runBlocking {
 
-        Log.i("Thc", "main runBlocking      : I'm working in thread ${Thread.currentThread().name}")
         // Create Retrofit
         val retrofit = Retrofit.Builder()
                 .baseUrl("http://chef.maya.se/gpsapi/") //registerGPSlocation.php")
@@ -82,11 +80,10 @@ class BackendClient {
         // Create RequestBody ( We're not using any converter, like GsonConverter, MoshiConverter e.t.c, that's why we use RequestBody )
         val requestBody = jsonObjectString.toRequestBody("application/json".toMediaTypeOrNull())
 
-        var retVal: Boolean = false
+        var retVal = false
 
         // Do the POST request and get response
         val response = service.uploadGPSPositions(requestBody)
-        Log.i("Thc", "Thread C:" + Thread.currentThread())
 
         if (response.isSuccessful) {
 
@@ -99,7 +96,6 @@ class BackendClient {
                     )
             )
             Log.i("Thc", "HTTP Reply: $prettyJson")
-            Log.i("Thc", "Thread B:" + Thread.currentThread())
             retVal = true
         } else {
             Log.e("Thc", "RETROFIT_ERROR:" + response.code().toString())

+ 2 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/database/GpsPosRepository.kt

@@ -1,6 +1,8 @@
 package com.flacksta.chef.journeygpstracker.database
 
+import android.util.Log
 import androidx.annotation.WorkerThread
+import kotlinx.coroutines.delay
 import kotlinx.coroutines.flow.Flow
 
 

+ 6 - 6
build.gradle

@@ -24,12 +24,12 @@ task clean(type: Delete) {
 }
 
 ext {
-    activityVersion = '1.4.0'
-    appCompatVersion = '1.4.1'
-    constraintLayoutVersion = '2.1.3'
+    activityVersion = '1.5.0'
+    appCompatVersion = '1.4.2'
+    constraintLayoutVersion = '2.1.4'
     coreTestingVersion = '2.1.0'
     coroutines = '1.6.3'
-    lifecycleVersion = '2.4.0'
-    materialVersion = '1.5.0'
-    roomVersion = '2.4.1'
+    lifecycleVersion = '2.5.0'
+    materialVersion = '1.6.1'
+    roomVersion = '2.4.2'
 }