Livebeat is now able to send, store and show beats

This commit is contained in:
2020-10-23 00:39:36 +02:00
parent f722ee9595
commit 13f8437f29
52 changed files with 1948 additions and 442 deletions

View File

@@ -0,0 +1,143 @@
package de.nicolasklier.livebeat
import android.Manifest
import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Color
import android.location.LocationManager
import android.os.BatteryManager
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import com.rabbitmq.client.Channel
import com.rabbitmq.client.Connection
import com.rabbitmq.client.ConnectionFactory
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.util.concurrent.TimeoutException
class TrackerService : Service() {
val conn = arrayOfNulls<Connection>(1)
val channel = arrayOfNulls<Channel>(1)
override fun onBind(intent: Intent): IBinder? {
return null
}
private fun connectWithBroker() {
// This thread only connects to RabbitMQ
val connectionThread = Thread(Runnable {
val client = OkHttpClient()
val req = Request.Builder()
.url(MainActivity.API_URL)
.get()
.build()
val factory = ConnectionFactory()
factory.username = "lineage"
factory.password = "ZSo\$X97GQ547JXL7nGq"
factory.virtualHost = "/"
factory.host = "nk-home.ddns.net"
factory.port = 5672
factory.isAutomaticRecoveryEnabled = true
try {
conn[0] = factory.newConnection()
channel[0] = conn[0]?.createChannel()
val intent = Intent("de.nicolasklier.livebeat")
val bundle = Bundle()
bundle.putBoolean("statusRabbit", true)
bundle.putInt("statusHttp", client.newCall(req).execute().code)
intent.putExtras(bundle)
this.sendBroadcast(intent)
channel[0]?.queueDeclare("tracker", true, false, false, null)
//channel[0]?.basicPublish("", "Tracker", null, "Test message".toByteArray())
Log.i("RabbitMQ", "run: Published test message")
} catch (e: IOException) {
e.printStackTrace()
} catch (e: TimeoutException) {
e.printStackTrace()
}
})
connectionThread.start()
}
@SuppressLint("HardwareIds")
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
// Android id as unique identifier
val androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates("gps", 5000, 0f
) { location ->
Log.i("Location", "Location is: " + location.latitude + " | " + location.longitude)
/* Get battery */
val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
this@TrackerService.registerReceiver(null, ifilter)
}
val batteryPct: Float? = batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
level * 100 / scale.toFloat()
}
val beat = Beat(androidId, arrayOf(location.latitude, location.longitude, location.accuracy.toDouble(), location.speed.toDouble()), batteryPct?.toInt(), location.time)
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonAdapter: JsonAdapter<Beat> = moshi.adapter(Beat::class.java)
Thread(Runnable {
channel[0]?.basicPublish("", "tracker", null, jsonAdapter.toJson(beat).toByteArray())
}).start()
}
}
connectWithBroker()
startForeground()
return super.onStartCommand(intent, flags, startId)
}
private fun startForeground() {
val noticicationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, noticicationIntent, 0)
val chan = NotificationChannel(
NOTIF_CHANNEL_ID,
"Tracker",
NotificationManager.IMPORTANCE_LOW)
chan.lightColor = Color.BLACK
chan.lockscreenVisibility = Notification.VISIBILITY_SECRET
val manager = (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
manager.createNotificationChannel(chan)
startForeground(NOTIF_ID, NotificationCompat.Builder(this, NOTIF_CHANNEL_ID)
.setOngoing(true)
.setContentTitle("Livebeat")
.setContentText("Tracker is running")
.setContentIntent(pendingIntent)
.setCategory(Notification.CATEGORY_SERVICE)
.setPriority(NotificationManager.IMPORTANCE_LOW)
.setChannelId(NOTIF_CHANNEL_ID)
.setColorized(true)
.setColor(Color.BLACK)
.build())
}
companion object {
private const val NOTIF_ID = 1
private const val NOTIF_CHANNEL_ID = "LiveTracker"
}
}