I want to make an Android app in Android Studio which keeps running in the background and collects all data from accessibilty service. It works when the app is visible but not when i press the home button. These are the codes i have implemented below :-
MainActivity.kt
package com.example.tvtracker
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.material3.Surface
import com.example.tvtracker.ui.theme.TVtrackerTheme
import android.view.accessibility.AccessibilityManager
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Start ForegroundService
startForegroundService(Intent(this, ForegroundService::class.java))
// Check and prompt for Accessibility Service
if (!isAccessibilityServiceEnabled()) {
Toast.makeText(
this,
"Please enable the TVAccessibilityService in settings.",
Toast.LENGTH_LONG
).show()
// Open Accessibility settings
startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
}
setContent {
TVtrackerTheme {
Surface(
modifier = Modifier.fillMaxSize(),
shape = RectangleShape
) {
Greeting("Android")
}
}
}
}
// Function to check if Accessibility Service is enabled
private fun isAccessibilityServiceEnabled(): Boolean {
val am = getSystemService(ACCESSIBILITY_SERVICE) as AccessibilityManager
val enabledServices = Settings.Secure.getString(
contentResolver,
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
)
// Split the enabledServices string by colon (':') which is a common delimiter
val colonSplitter = enabledServices.split(':')
for (componentName in colonSplitter) {
if (componentName.contains(TVAccessibilityService::class.java.name)) {
return true
}
}
return false
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
TVtrackerTheme {
Greeting("Android")
}
}
TVAccessibilityService.kt
package com.example.tvtracker
import android.accessibilityservice.AccessibilityService
import android.view.accessibility.AccessibilityEvent
import android.util.Log
class TVAccessibilityService : AccessibilityService() {
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
Log.d("TVAccessibilityService", "Event received: ${event?.eventType}")
Log.d("TVAccessibilityService", "Event content: ${event?.text}")
}
override fun onInterrupt() {
Log.d("TVAccessibilityService", "Accessibility Service Interrupted")
}
}
ForegroundService.kt
package com.example.tvtracker
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 android.util.Log
import androidx.core.app.NotificationCompat
import android.content.Context
class ForegroundService : Service() {
companion object {
private const val CHANNEL_ID = "foreground_service_channel"
}
override fun onCreate() {
super.onCreate()
Log.d("ForegroundService", "Service Created")
// Create a notification channel for Android O and above
createNotificationChannel()
// Create a notification and start foreground service
val notification = createNotification()
startForeground(1, notification)
}
private fun createNotification(): Notification {
val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("Service is running")
.setSmallIcon(R.drawable.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_LOW)
return notificationBuilder.build()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
}
/res/xml/accessibility_service_config.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowStateChanged|typeViewScrolled|typeViewTextChanged"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:accessibilityFlags="flagRequestFilterKeyEvents"
android:packageNames="com.example.tvtracker" />
have some changes in app and project level build gradle and manifest as well.
Please help me resolve this issue!
Try-
I ran the app on my TV emualator with android 11 and got logs of whats happening in the app
Expecting :-
logs of all the events happening in the background as well