我有一个在授予权限时触发的服务类(AccessibilityService)。我检查在 onAccessibilityEvent() 方法中所做的窗口更改并将包名称发送到视图模型,然后我尝试在 MainActivity 中观察我的 LiveData 对象以在 UI 中显示它,但我无法进入观察功能
class ServiceAccess : AccessibilityService() {
private val TAG = "ServiceAccess"
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
Log.d(TAG, "AccesibilityEvent gerçekleşti")
val packageName: String = event?.packageName.toString()
val packageManager = applicationContext.packageManager
val viewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(PackageViewModel::class.java)
val applicationInfo: ApplicationInfo = packageManager.getApplicationInfo(packageName, 0)
val applicationLabel = packageManager.getApplicationLabel(applicationInfo)
Log.d(TAG, "app name :$applicationLabel")
if (event != null) {
if (AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED == event.eventType) {
if (event.packageName != null && event.className != null) {
viewModel.setRunningPackageNames(event)
Log.d(TAG, "runn app: " + event.packageName.toString())
}
}
}
}
override fun onInterrupt() {
Log.d(TAG, "error!!")
}
override fun onServiceConnected() {
super.onServiceConnected()
val info = AccessibilityServiceInfo()
info.apply {
eventTypes =
AccessibilityEvent.TYPE_VIEW_CLICKED or AccessibilityEvent.TYPE_VIEW_FOCUSED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN
notificationTimeout = 100
}
this.serviceInfo = info
Log.d(TAG, "connection")
}
}
class PackageViewModel : ViewModel() {
private val TAG = "PackageViewModel"
private val _currentPackageName =MutableLiveData<NamePackage>()
val currentPackageName: LiveData<NamePackage>
get() = _currentPackageName
fun setRunningPackageNames(event: AccessibilityEvent) {
val eventData = NamePackage(currentPackageName = event.packageName.toString())
_currentPackageName.value = eventData
Log.d(TAG, "viewModel :${currentPackageName.value}")
}
}
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var packageViewModel: PackageViewModel
private val TAG = "MainActivityObserve"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val accessibilityManager =
getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
val isAccessibilityEnabled = accessibilityManager.isEnabled
packageViewModel = ViewModelProvider(this).get(PackageViewModel::class.java)
if (!isAccessibilityEnabled) {
openAccessibilitySettings()
}
packageViewModel.currentPackageName.observe(this, Observer { packageName ->
Log.d(TAG, "mainActivty: $packageName")
})
}
private fun openAccessibilitySettings() {
val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
startActivity(intent)
}
}