StatusFragment.kt
8.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package ai.lemon.phoneuse
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityManager
import android.widget.Button
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import ai.lemon.phoneuse.service.AgentRuntimeService
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class StatusFragment : Fragment() {
private lateinit var tvUptime: TextView
private lateinit var tvRuntimeStatus: TextView
private lateinit var btnToggleRuntime: Button
private lateinit var btnOpenSettings: Button
private lateinit var tvEventLog: TextView
private lateinit var cardAccessibility: CardView
private lateinit var cardNotification: CardView
private lateinit var cardRoot: CardView
private lateinit var cardMcp: CardView
private val handler = Handler(Looper.getMainLooper())
private val logLines = ArrayDeque<String>(10)
private var startTime = System.currentTimeMillis()
private var runtimeRunning = false
private val eventReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
MainActivity.ACTION_RUNTIME_STARTED -> onRuntimeStarted()
MainActivity.ACTION_RUNTIME_STOPPED -> onRuntimeStopped()
MainActivity.ACTION_EVENT_LOG -> {
val msg = intent.getStringExtra(MainActivity.EXTRA_LOG_MESSAGE) ?: return
appendLog(msg)
}
}
}
}
private val tickRunnable = object : Runnable {
override fun run() {
if (isAdded) refreshStatus()
handler.postDelayed(this, TICK_MS)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.fragment_status, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tvUptime = view.findViewById(R.id.tvUptime)
tvRuntimeStatus = view.findViewById(R.id.tvRuntimeStatus)
btnToggleRuntime = view.findViewById(R.id.btnToggleRuntime)
btnOpenSettings = view.findViewById(R.id.btnOpenSettings)
tvEventLog = view.findViewById(R.id.tvEventLog)
cardAccessibility = view.findViewById(R.id.cardAccessibility)
cardNotification = view.findViewById(R.id.cardNotification)
cardRoot = view.findViewById(R.id.cardRoot)
cardMcp = view.findViewById(R.id.cardMcp)
setupCard(cardAccessibility, "Accessibility", "UI event capture")
setupCard(cardNotification, "Notifications", "Message listener")
setupCard(cardRoot, "Root Access", "Shell executor")
setupCard(cardMcp, "MCP Server", "Semantic tools")
btnToggleRuntime.setOnClickListener { toggleRuntime() }
btnOpenSettings.setOnClickListener {
startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
}
appendLog("Runtime initialised")
appendLog("Device: ${Build.MODEL} (API ${Build.VERSION.SDK_INT})")
}
override fun onResume() {
super.onResume()
val filter = IntentFilter().apply {
addAction(MainActivity.ACTION_RUNTIME_STARTED)
addAction(MainActivity.ACTION_RUNTIME_STOPPED)
addAction(MainActivity.ACTION_EVENT_LOG)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requireContext().registerReceiver(eventReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("UnspecifiedRegisterReceiverFlag")
requireContext().registerReceiver(eventReceiver, filter)
}
handler.post(tickRunnable)
}
override fun onPause() {
super.onPause()
requireContext().unregisterReceiver(eventReceiver)
handler.removeCallbacks(tickRunnable)
}
// -------------------------------------------------------------------------
private fun toggleRuntime() {
if (runtimeRunning) {
requireContext().stopService(Intent(requireContext(), AgentRuntimeService::class.java))
} else {
requireContext().startForegroundService(Intent(requireContext(), AgentRuntimeService::class.java))
}
}
private fun onRuntimeStarted() {
runtimeRunning = true
startTime = System.currentTimeMillis()
tvRuntimeStatus.text = "Running"
tvRuntimeStatus.setTextColor(0xFF55FF7A.toInt())
btnToggleRuntime.text = "Stop"
appendLog("Runtime service started")
}
private fun onRuntimeStopped() {
runtimeRunning = false
tvRuntimeStatus.text = "Stopped"
tvRuntimeStatus.setTextColor(0xFFFF5555.toInt())
btnToggleRuntime.text = "Start"
appendLog("Runtime service stopped")
}
private fun refreshStatus() {
val elapsedSec = (System.currentTimeMillis() - startTime) / 1000
val h = elapsedSec / 3600
val m = (elapsedSec % 3600) / 60
val s = elapsedSec % 60
tvUptime.text = if (runtimeRunning) "Uptime %02d:%02d:%02d".format(h, m, s)
else "Last run: —"
val accessEnabled = isAccessibilityServiceEnabled()
updateCard(cardAccessibility, accessEnabled, if (accessEnabled) "Active" else "Disabled")
val notifEnabled = isNotificationListenerEnabled()
updateCard(cardNotification, notifEnabled, if (notifEnabled) "Active" else "Disabled")
val rootAvail = isRootAvailable()
updateCard(cardRoot, rootAvail, if (rootAvail) "Available" else "Not found")
updateCard(cardMcp, runtimeRunning, if (runtimeRunning) "Listening :8765" else "Stopped")
}
private fun appendLog(msg: String) {
val ts = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
logLines.addFirst("$ts $msg")
if (logLines.size > MAX_LOG_LINES) logLines.removeLast()
tvEventLog.text = logLines.joinToString("\n")
}
// -------------------------------------------------------------------------
private fun setupCard(card: CardView, title: String, subtitle: String) {
card.findViewById<TextView>(R.id.tvCardTitle).text = title
card.findViewById<TextView>(R.id.tvCardStatus).text = subtitle
}
private fun updateCard(card: CardView, active: Boolean, statusText: String) {
val dot = card.findViewById<View>(R.id.statusDot)
val tv = card.findViewById<TextView>(R.id.tvCardStatus)
dot.backgroundTintList = android.content.res.ColorStateList.valueOf(
if (active) 0xFF55FF7A.toInt() else 0xFFFF5555.toInt()
)
tv.text = statusText
tv.setTextColor(if (active) 0xFF55FF7A.toInt() else 0xFF888888.toInt())
}
// -------------------------------------------------------------------------
private fun isAccessibilityServiceEnabled(): Boolean {
val am = requireContext().getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
val enabledServices = am.getEnabledAccessibilityServiceList(
AccessibilityServiceInfo.FEEDBACK_ALL_MASK
)
val target = ComponentName(requireContext(), "ai.lemon.phoneuse.service.AgentAccessibilityService")
return enabledServices.any {
it.resolveInfo.serviceInfo.packageName == target.packageName &&
it.resolveInfo.serviceInfo.name == target.className
}
}
private fun isNotificationListenerEnabled(): Boolean {
val flat = Settings.Secure.getString(requireContext().contentResolver, "enabled_notification_listeners")
?: return false
return flat.contains(requireContext().packageName)
}
private fun isRootAvailable(): Boolean {
return try {
listOf("/sbin/su", "/system/bin/su", "/system/xbin/su",
"/data/local/xbin/su", "/data/local/bin/su", "/data/local/su")
.any { File(it).exists() }
} catch (_: Exception) { false }
}
companion object {
private const val TICK_MS = 1_000L
private const val MAX_LOG_LINES = 8
}
}