/
MainActivity.kt
58 lines (51 loc) · 2.08 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.example.overlaysample
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.ToggleButton
import androidx.appcompat.app.AppCompatActivity
/**
* オーバーレイ表示を開始/終了するためのトグルボタンを表示します。
*/
class MainActivity : AppCompatActivity() {
companion object {
/** ID for the runtime permission dialog */
private const val OVERLAY_PERMISSION_REQUEST_CODE = 1
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
requestOverlayPermission()
// Show/hide overlay view with a toggle button.
findViewById<ToggleButton>(R.id.toggle_button).apply {
isChecked = OverlayService.isActive
setOnCheckedChangeListener { _, isChecked ->
if (isChecked) OverlayService.start(this@MainActivity)
else OverlayService.stop(this@MainActivity)
}
}
}
/** Requests an overlay permission to the user if needed. */
private fun requestOverlayPermission() {
if (isOverlayGranted()) return
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:$packageName")
)
startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE)
}
/** Terminates the app if the user does not accept an overlay. */
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
if (!isOverlayGranted()) {
finish() // Cannot continue if not granted
}
}
}
/** Checks if the overlay is permitted. */
private fun isOverlayGranted() =
Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(this)
}