Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
6.0 kB
7
Indexable
Never
package com.example.servisilab.services

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.example.servisilab.R
import com.example.servisilab.ServiceApplication
import com.example.servisilab.data.entities.Log
import com.example.servisilab.data.repositories.LogRepository
import kotlinx.coroutines.*
import java.util.Date

class LoggingService : Service() {

    private lateinit var app: ServiceApplication
    private lateinit var repo: LogRepository
    private lateinit var job: Job
    private var shouldWriteLogs = false

    companion object {
        const val CHANNEL_ID = "LoggingServiceChannel"
        const val NOTIFICATION_ID = 1
    }

    override fun onBind(intent: Intent?): IBinder? {
        // This is a started service, not a bound service, so return null.
        return null
    }

    override fun onCreate() {
        super.onCreate()
        app = application as ServiceApplication
        repo = app.repository
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        start()
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        stop()
    }

    private fun start() {
        shouldWriteLogs = true
        job = doWork()
    }

    private fun stop() {
        shouldWriteLogs = false
        job.cancel()
    }

    private fun doWork(): Job {
        return CoroutineScope(Dispatchers.IO).launch {
            while (shouldWriteLogs) {
                delay(10000L)
                repo.insert(Log(0, Date().toString(), "Service logging while active."))
            }
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                CHANNEL_ID,
                "Logging Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager?.createNotificationChannel(serviceChannel)
        }
    }

    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Logging Service")
            .setContentText("Service is running...")
            // Use an appropriate icon
            .build()
    }
}



MAIN AKTIVITI


package com.example.servisilab

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.servisilab.data.entities.Log
import com.example.servisilab.services.LoggingService
import com.example.servisilab.ui.theme.ServisiLabTheme

class MainActivity : ComponentActivity() {

    private val viewModel: AppViewModel by viewModels {
        AppViewModelFactory((application as ServiceApplication).repository)
    }

    private fun startLoggingService() {
        // Start the service
        val intent = Intent(this, LoggingService::class.java)
        startService(intent)

        // Log "Service started." to the database
        viewModel.addLog("Service started.")
    }

    private fun stopLoggingService() {
        // Stop the service
        val intent = Intent(this, LoggingService::class.java)
        stopService(intent)

        // Log "Service stopped." to the database
        viewModel.addLog("Service stopped.")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ServisiLabTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    MainScreen(viewModel, { startLoggingService() }, { stopLoggingService() })
                }
            }
        }
    }
}

@Composable
fun MainScreen(viewModel: AppViewModel, startFn: () -> Unit, stopFn: () -> Unit) {
    val logs = viewModel.logs.collectAsState(initial = listOf())
    Column {
        Row {
            Button(onClick = startFn, modifier = Modifier.padding(24.dp)) {
                Text(text = "Start service")
            }
            Spacer(modifier = Modifier.weight(1.0f))
            Button(onClick = stopFn, modifier = Modifier.padding(24.dp)) {
                Text(text = "Stop service")
            }
        }
        LazyColumn {
            items(logs.value) { log ->
                LogItem(l = log)
            }
        }
    }
}

@Composable
fun LogItem(l: Log) {
    Card(modifier = Modifier
        .padding(6.dp)
        .fillMaxWidth()) {
        Column(modifier = Modifier.padding(12.dp)) {
            Text(text = l.timestamp, fontStyle = FontStyle.Italic)
            Text(text = l.message, fontWeight = FontWeight.Bold )
        }
    }
}





ANDROID MANIFEST

<service android:name=".services.LoggingService" android:foregroundServiceType="dataSync"/>
Leave a Comment