Вот код, отвечающий за обеспечение безопасного поиска:
Код: Выделить всё
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
if (!isActive || event == null) return //Logic for toggling the service on or off
val packageName = event.packageName?.toString() ?: return
if (packageName in supportedBrowsers) {
//Get the current URL from the node
val nodeInfo = event.source ?: return
val currentUrl = extractUrlFromNodeInfo(nodeInfo) //Code to extract URL is pasted lower in my post
if (currentUrl != null) {
Log.d(TAG, "onAccessibilityEvent: Current URL = $currentUrl")
//Check if the current URL is one of the homepages to ignore
if (isHomePage(currentUrl)) {
Log.d(TAG, "onAccessibilityEvent: URL is a homepage, ignoring.")
}
else {
//Check if the current URL is already a safe search url
val safeSearchKey = safeSearchKeys[packageName] ?: return
if (isSafeSearchActive(currentUrl, safeSearchKey)) {
Log.d(TAG, "onAccessibilityEvent: Safe search is already active. No modification needed.")
}
//If the url is not a safe search url
else {
//Apply safe search and redirect
val safeUrl = applySafeSearch(currentUrl, safeSearchKey)
Log.d(TAG, "onAccessibilityEvent: Redirecting to safe URL = $safeUrl")
openUrlInSameBrowser(packageName, safeUrl)
}
}
}
else {
Log.d(TAG, "onAccessibilityEvent: No URL found during tab change")
}
}
else {
Log.d(TAG, "onAccessibilityEvent: Browser not supported")
}
}
Код: Выделить всё
private fun extractUrlFromNodeInfo(nodeInfo: AccessibilityNodeInfo): String? {
//Check if the current node is an EditText to extract URL
if (nodeInfo.className == "android.widget.EditText") {
val text = nodeInfo.text?.toString()
if (text != null && (text.contains("www.") || text.contains(".com") || text.contains(".net") || text.contains(".org"))) {
return if (text.startsWith("http://") || text.startsWith("https://")) {
text
}
else {
"https://$text"
}
}
}
//Traverse child nodes to find a URL
for (i in 0 until nodeInfo.childCount) {
val child = nodeInfo.getChild(i)
if (child != null) {
val result = extractUrlFromNodeInfo(child)
if (result != null) {
Log.d(TAG, "extractUrlFromNodeInfo: URL found in child = $result")
return result
}
}
}
return null
}
Код: Выделить всё
private val safeSearchKeys = mapOf(
"com.android.chrome" to "&safe=active",
"com.brave.browser" to "safesearch.brave.com"
)
private fun isSafeSearchActive(url: String, safeSearchKey: String): Boolean {
return url.contains(safeSearchKey)
}
Код: Выделить всё
private fun openUrlInSameBrowser(packageName: String, safeUrl: String) {
Log.d(TAG, "openUrlInSameBrowser: Opening safe URL in browser = $safeUrl")
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(safeUrl)).apply {
setPackage(packageName)
flags = Intent.FLAG_ACTIVITY_NEW_TASK // Start new task
}
startActivity(intent)
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... on-android