I try to connect to the service but I can not I can start the service it lansa the notification but does not bind when I call bindservice
I already added the request foregraud service and already moved the startSevice to oncreate I took as a basis the documentation of android I presiso learn how to solve this because the conponent is indicated in cases as music players and I believe thatThis will almetar my knowledge obs: as it is only a study I am not using the ViewModel
main activity
package com.example.soccer
import android.Manifest
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.IBinder
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.soccer.ui.theme.SoccerTheme
import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.soccer.servics.Servic
class MainActivity : ComponentActivity() {
lateinit var sev: Servic
var sevicoIniciado:Boolean =false
var conStat:Boolean =false
val con = object:ServiceConnection {
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
val bind = p1 as Servic.MBinder
sev = bind.getS()
conStat = true
}
override fun onServiceDisconnected(p0: ComponentName?) {
conStat=false
}
override fun onBindingDied(name: ComponentName?) {
Toast.makeText(applicationContext,"acesso bloqueado",Toast.LENGTH_LONG).show()
super.onBindingDied(name)
}
override fun onNullBinding(name: ComponentName?) {
Toast.makeText(applicationContext,"nulll",Toast.LENGTH_LONG).show()
super.onNullBinding(name)
}
}
override fun onStart() {
super.onStart()
Intent(this,Servic::class.java).also {
bindService(it,con,Context.BIND_AUTO_CREATE)
}
}
override fun onStop() {
super.onStop()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(sevicoIniciado==false) {Intent(this,Servic::class.java).also { startForegroundService(it) }
sevicoIniciado=true}
/* */
setContent {
SoccerTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Column(horizontalAlignment = Alignment.CenterHorizontally,modifier=Modifier.fillMaxSize()) {
Greeting("Android")
Spacer(modifier = Modifier.padding(40.dp))
if(!conStat){
valores(string = "nao conectado")
}else {
if(::sev.isInitialized){
var a = sev.contagem().collectAsState(initial = "")
valores( string = a.value)
}
else valores(string = "nao inicializado")
}
Button(onClick = {
this@MainActivity.bindService(Intent(this@MainActivity,Servic::class.java),con,0)
}) {
}
}
}
}
}
}
}
@Composable
fun Greeting(name: String) {
Text(
text = "Hello $name!",
)
}
@Composable
fun valores(string:String){
Text(text = string)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
SoccerTheme {
Greeting("Android")
}
}
servic
package com.example.soccer.servics
import android.Manifest
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.os.IInterface
import android.os.Parcel
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.io.FileDescriptor
import com.example.soccer.R
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class Servic :Service(){
val mb = MBinder()
@SuppressLint("MissingPermission")
fun notificacao(){
val name="aprendendo sobre sevicos"
val desc= "aprendendo sobre services"
val imp=NotificationManager.IMPORTANCE_HIGH
val can =NotificationChannel("soccer",name,imp).apply { description=desc }
val not:NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
not.createNotificationChannel(can)
val bui:NotificationCompat.Builder = NotificationCompat.Builder(this,"soccer")
.setSmallIcon(androidx.core.R.drawable.notification_bg)
.setContentText("servico iniciado")
.setContentTitle("serviço")
.setPriority(NotificationCompat.PRIORITY_HIGH)
with(receiver = NotificationManagerCompat.from(this)){
notify(1,bui.build())
}
}
fun contagem():Flow<String> = flow {
var l:Long =0
while (true){
l++
emit( l.toString())
}
}
override fun onBind(p0: Intent?): IBinder? {
return mb
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
notificacao()
Toast.makeText(applicationContext,"servico iniciado",Toast.LENGTH_LONG).show()
return START_STICKY
}
inner class MBinder:Binder(){
fun getS():Servic = this@Servic
}
override fun onDestroy() {
Toast.makeText(applicationContext,"servico morto",Toast.LENGTH_LONG).show()
super.onDestroy()
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"></uses-permission>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Soccer"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Soccer">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.soccer.servics.Servic"
android:exported="true"
android:enabled="true"
android:foregroundServiceType="mediaPlayback"
android:description="@string/app_name"
android:visibleToInstantApps="true"
>
</service>
</application>
<queries>
<package android:name="com.example.soccer.servics.Servic"/>
</queries>
</manifest>