权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>长按按钮先同意悬浮窗权限,然后点击它,会出现一个通过WindowManager创建的悬浮按钮。悬浮按钮点击的时候会有Toast信息,但是到应用外部,比如说返回到桌面,再点悬浮按钮,Toast不显示。
| package com.example.test | |
| import android.content.Context | |
| import android.content.Intent | |
| import android.graphics.PixelFormat | |
| import android.net.Uri | |
| import android.os.Bundle | |
| import android.provider.Settings | |
| import android.view.WindowManager | |
| import android.view.WindowManager.LayoutParams.* | |
| import android.widget.Button | |
| import android.widget.Toast | |
| import androidx.activity.result.contract.ActivityResultContract | |
| import androidx.appcompat.app.AppCompatActivity | |
| class OverlaySettingContract : ActivityResultContract<String, Unit>() { | |
| override fun createIntent(context: Context, input: String): Intent { | |
| return Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$input")) | |
| } | |
| override fun parseResult(resultCode: Int, intent: Intent?) { | |
| } | |
| } | |
| class MainActivity : AppCompatActivity() { | |
| private val overlaySettingLauncher = registerForActivityResult(OverlaySettingContract()) {} | |
| override fun onCreate(savedInstanceState: Bundle?) { | |
| super.onCreate(savedInstanceState) | |
| setContentView(R.layout.activity_main) | |
| val button = findViewById<Button>(R.id.button) | |
| button.setOnClickListener { | |
| createFloatingWindow() | |
| } | |
| button.setOnLongClickListener { | |
| overlaySettingLauncher.launch(this.packageName) | |
| return@setOnLongClickListener true | |
| } | |
| } | |
| private fun createFloatingWindow() { | |
| val wm = applicationContext.getSystemService(WindowManager::class.java)!! | |
| val lp = WindowManager.LayoutParams() | |
| lp.apply { | |
| type = TYPE_APPLICATION_OVERLAY | |
| format = PixelFormat.RGBA_8888 | |
| flags = FLAG_NOT_FOCUSABLE | |
| width = WRAP_CONTENT | |
| height = WRAP_CONTENT | |
| } | |
| val button = Button(this) | |
| wm.addView(button, lp) | |
| button.setOnClickListener { | |
| /*val handler = Handler(Looper.getMainLooper()) | |
| handler.post { | |
| Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show() | |
| }*/ | |
| Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show() | |
| } | |
| } | |
| } |