-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathContext.kt
More file actions
79 lines (62 loc) · 2.45 KB
/
Context.kt
File metadata and controls
79 lines (62 loc) · 2.45 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package to.bitkit.ext
import android.app.Activity
import android.app.ActivityManager
import android.app.NotificationManager
import android.bluetooth.BluetoothManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.hardware.usb.UsbManager
import android.provider.Settings
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import to.bitkit.R
import java.io.InputStream
// System Services
val Context.notificationManager: NotificationManager
get() = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val Context.notificationManagerCompat: NotificationManagerCompat
get() = NotificationManagerCompat.from(this)
val Context.clipboardManager: ClipboardManager
get() = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val Context.activityManager: ActivityManager
get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val Context.usbManager: UsbManager
get() = getSystemService(Context.USB_SERVICE) as UsbManager
val Context.bluetoothManager: BluetoothManager
get() = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
// Permissions
fun Context.requiresPermission(permission: String): Boolean =
ContextCompat.checkSelfPermission(this, permission) != PERMISSION_GRANTED
// File System
fun Context.readAsset(path: String) = assets.open(path).use(InputStream::readBytes)
// Clipboard
fun Context.setClipboardText(text: String, label: String = getString(R.string.app_name)) {
this.clipboardManager.setPrimaryClip(
ClipData.newPlainText(label, text)
)
}
fun Context.getClipboardText(): String? {
return this.clipboardManager.primaryClip?.getItemAt(0)?.text?.toString()
}
// Other
fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
fun Context.startActivityAppSettings() {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
this.data = "package:$packageName".toUri()
}
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
startActivity(Intent(Settings.ACTION_SETTINGS))
}
}