1+ package com.aistra.hail.utils
2+
3+ import android.app.Activity
4+ import android.app.PendingIntent
5+ import android.content.BroadcastReceiver
6+ import android.content.Context
7+ import android.content.Intent
8+ import android.content.pm.PackageManager
9+ import android.net.Uri
10+ import android.os.Handler
11+ import android.os.HandlerThread
12+ import androidx.core.content.ContextCompat
13+ import com.aistra.hail.HailApp.Companion.app
14+ import kotlinx.coroutines.CompletableDeferred
15+ import kotlinx.coroutines.runBlocking
16+ import kotlinx.coroutines.withTimeout
17+
18+ object HIsland {
19+ const val PERMISSION_FREEZE_PACKAGE = " com.oasisfeng.island.permission.FREEZE_PACKAGE"
20+ const val PERMISSION_SUSPEND_PACKAGE = " com.oasisfeng.island.permission.SUSPEND_PACKAGE"
21+ private const val ACTION_SUSPEND = " com.oasisfeng.island.action.SUSPEND"
22+ private const val ACTION_UNSUSPEND = " com.oasisfeng.island.action.UNSUSPEND"
23+ private const val ACTION_FREEZE = " com.oasisfeng.island.action.FREEZE"
24+ private const val ACTION_UNFREEZE = " com.oasisfeng.island.action.UNFREEZE"
25+ private const val EXTRA_CALLER_ID = " caller"
26+
27+ private val thread by lazy { HandlerThread (" HIsland" ).apply { start() } }
28+ private val handler by lazy { Handler (thread.looper) }
29+
30+ fun freezePermissionGranted (): Boolean {
31+ return ContextCompat .checkSelfPermission(
32+ app, PERMISSION_FREEZE_PACKAGE
33+ ) == PackageManager .PERMISSION_GRANTED
34+ }
35+
36+ fun suspendPermissionGranted (): Boolean {
37+ return ContextCompat .checkSelfPermission(
38+ app, PERMISSION_SUSPEND_PACKAGE
39+ ) == PackageManager .PERMISSION_GRANTED
40+ }
41+
42+ private fun setAppFrozen (packageName : String , action : String ): Boolean {
43+ val intent = Intent (action).apply {
44+ data = Uri .fromParts(" package" , packageName, null )
45+ setPackage(" com.oasisfeng.island" )
46+ addFlags(Intent .FLAG_RECEIVER_FOREGROUND )
47+ putExtra(
48+ EXTRA_CALLER_ID ,
49+ PendingIntent .getActivity(app, 0 , Intent (), PendingIntent .FLAG_IMMUTABLE )
50+ )
51+ }
52+ val result = CompletableDeferred <Boolean >()
53+ app.sendOrderedBroadcast(
54+ intent, null , object : BroadcastReceiver () {
55+ override fun onReceive (context : Context , intent : Intent ) {
56+ if (resultCode != Activity .RESULT_OK ) {
57+ HLog .i(" HIsland" , resultData)
58+ }
59+ result.complete(resultCode == Activity .RESULT_OK )
60+ }
61+ }, handler, Activity .RESULT_OK , null , null
62+ )
63+ return runBlocking {
64+ runCatching {
65+ withTimeout(500L ) {
66+ result.await()
67+ }
68+ }.getOrElse { false }
69+ }
70+ }
71+
72+ fun setAppHidden (packageName : String , hidden : Boolean ): Boolean =
73+ HTarget .N && setAppFrozen(packageName, if (hidden) ACTION_FREEZE else ACTION_UNFREEZE )
74+
75+ fun setAppSuspended (packageName : String , suspended : Boolean ): Boolean =
76+ HTarget .N && setAppFrozen(packageName, if (suspended) ACTION_SUSPEND else ACTION_UNSUSPEND )
77+ }
0 commit comments