Skip to content

Commit 4ba7926

Browse files
committed
Add AndroidAPI
1 parent f79a4ad commit 4ba7926

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

Sources/AndroidOS/AndroidAPI.swift

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//
2+
// AndroidAPI.swift
3+
// SwiftAndroid
4+
//
5+
// Created by Alsey Coleman Miller on 6/14/25.
6+
//
7+
8+
#if os(Android)
9+
import Android
10+
import AndroidNDK
11+
#endif
12+
13+
/// Android API Level
14+
public struct AndroidAPI: RawRepresentable, Equatable, Hashable, Codable, Sendable {
15+
16+
public let rawValue: Int32
17+
18+
public init(rawValue: Int32) {
19+
assert(rawValue > 0)
20+
self.rawValue = rawValue
21+
}
22+
}
23+
24+
public extension AndroidAPI {
25+
26+
/// Available since API level 24. Returns the API level of the device we're actually running on.
27+
static var current: AndroidAPI {
28+
get throws(Throwable) {
29+
let value: CInt
30+
#if os(Android) && canImport(AndroidNDK)
31+
value = try ndkValue().get()
32+
#else
33+
value = try jniValue()
34+
#endif
35+
}
36+
}
37+
}
38+
39+
internal extension AndroidAPI {
40+
41+
/// `Build.VERSION.SDK_INT`
42+
static func jniValue() throws(Throwable) -> Int32 {
43+
let javaClass = try JavaClass<Build.VERSION>.init()
44+
return javaClass.sdk_version
45+
}
46+
47+
48+
static func ndkValue() -> Result<Int32, Exception> {
49+
#if os(Android) && canImport(AndroidNDK)
50+
let value = android_get_device_api_level()
51+
#else
52+
let value: Int32 = -1
53+
#endif
54+
guard value != -1 else {
55+
throw Exception()
56+
}
57+
return .success(value)
58+
}
59+
}
60+
61+
// MARK: - CustomStringConvertible
62+
63+
extension AndroidAPI: CustomStringConvertible {
64+
65+
public var description: String {
66+
rawValue.description
67+
}
68+
}
69+
70+
// MARK: - ExpressibleByIntegerLiteral
71+
72+
extension AndroidAPI: ExpressibleByIntegerLiteral {
73+
74+
public init(integerLiteral value: Int32) {
75+
self.init(rawValue: value)
76+
}
77+
}

0 commit comments

Comments
 (0)