Skip to content

Instantly share code, notes, and snippets.

@hwd6190128
Last active May 22, 2019 06:41
Show Gist options
  • Save hwd6190128/629e88fd30243dab07a569d1939f2f02 to your computer and use it in GitHub Desktop.
Save hwd6190128/629e88fd30243dab07a569d1939f2f02 to your computer and use it in GitHub Desktop.
fun Activity.hasOverlayPermission(): Boolean =
if (Build.VERSION.SDK_INT >= 23) Settings.canDrawOverlays(this) else true
fun Activity.requestOverlayPermission(requestCode: Int) {
if (Build.VERSION.SDK_INT >= 23) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))
startActivityForResult(intent, requestCode)
}
}
<!-- Build.VERSION.SDK_INT < 23 -->
<!-- 顯示系統窗口權限 -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<!-- 在最頂部顯示 -->
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
private val REQUEST_OVERLAY_PERMISSION = 77
fun checkOverlayPermission() {
if (hasOverlayPermission()) {
showSystemDialog()
} else {
requestOverlayPermission(REQUEST_OVERLAY_PERMISSION)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode) {
REQUEST_OVERLAY_PERMISSION -> showSystemDialog()
}
}
}
fun showSystemDialog() {
val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(this)
val dialog: AlertDialog = dialogBuilder
.setIcon(R.drawable.ic_launcher_background)
.setTitle(R.string.app_name)
.setMessage("msg")
.setPositiveButton("ok", object : DialogInterface.OnClickListener {
override fun onClick(p0: DialogInterface?, p1: Int) {
p0?.dismiss()
}
}).create()
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
dialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
} else {
dialog.window?.setType(WindowManager.LayoutParams.TYPE_PHONE)
}
dialog.window?.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
)
dialog.show()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment