Как заставить службу плавающих окон оставаться на вершине всего, включая намерения, в Android Kotlin?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как заставить службу плавающих окон оставаться на вершине всего, включая намерения, в Android Kotlin?

Сообщение Anonymous »

Я пишу приложение, которое должно работать с AppInfo для запуска приложений. Когда вы нажимаете на кнопку, плавающее окно должно отображать все, что находится под ним, пока мое приложение не выполнит свою задачу (намерение AppInfo). Затем плавающее окно закрывается нажатием кнопки закрытия на нем. По какой-то причине сразу после отображения плавающего окна и запуска AppInfo Intent, AppInfo Intent отображается прямо поверх плавающего окна, когда этого не ожидается. Итак, как сделать так, чтобы плавающее окно всегда оставалось поверх всего на экране, пока вы не закроете плавающее окно, нажав кнопку закрытия?
Часть основного действия
//In MainActivity button setOnClickListener
//start overlay service
Intent(this, FloatingWindowService::class.java).also { intent ->
startService(intent)
}

for (pos in installedApps!!.indices) {
if (installedApps!![pos].isSelected()){

//Start an running app's AppInfo intent
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", installedApps!![pos].getAppPackage(), null)
intent.data = uri
startActivity(intent)
}
}
mRecyclerView?.adapter?.notifyDataSetChanged()
}

Служба плавающих окон
class FloatingWindowService : Service() {

private lateinit var windowManager: WindowManager
private lateinit var floatingView: View
private lateinit var layoutParams: WindowManager.LayoutParams
private lateinit var floatbtn: Button

companion object {
const val CHANNEL_ID = "FloatingWindowServiceChannel"
}

override fun onBind(intent: Intent): IBinder? {
return null
}

override fun onCreate() {
super.onCreate()
createNotificationChannel()

// Create a notification for the foreground service
val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Floating Window Active")
.setContentText("Your floating window service is running.")
.setSmallIcon(R.drawable.ic_launcher_foreground) // Replace with your own icon
.build()

startForeground(1, notification) // Start as foreground service

// Initialize views and window manager
windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
floatingView = LayoutInflater.from(this).inflate(R.layout.overlay_layout, null) // Replace with your layout

floatbtn = floatingView.findViewById(R.id.close_overlay_button)
floatbtn.setOnClickListener {
stopSelf()
}

// Define layout parameters for the floating window
layoutParams = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
} else {
WindowManager.LayoutParams.TYPE_PHONE // Deprecated on newer APIs
},
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
).apply {
gravity = Gravity.TOP or Gravity.START
x = 0
y = 100
}

// Add the view to the window manager
windowManager.addView(floatingView, layoutParams)

// Example: Add a click listener or drag listener to the floating view
// ... (implementation for moving/interacting with the window)
}

override fun onDestroy() {
super.onDestroy()
if (::floatingView.isInitialized) {
windowManager.removeView(floatingView)
}
}

private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
CHANNEL_ID,
"Floating Window Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(serviceChannel)
}
}
}

AndroidManifest.XML








Подробнее здесь: https://stackoverflow.com/questions/798 ... -intent-in
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»