-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycle.go
More file actions
104 lines (95 loc) · 2.48 KB
/
lifecycle.go
File metadata and controls
104 lines (95 loc) · 2.48 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//go:build android
package android
import (
"unsafe"
"github.com/AndroidGoLab/ndk/activity"
"github.com/AndroidGoLab/ndk/input"
)
// Handlers defines callbacks for Android lifecycle events and input.
// All callbacks receive the App instance for accessing platform APIs.
type Handlers struct {
OnCreate func(app *App)
OnResume func(app *App)
OnPause func(app *App)
OnDestroy func(app *App)
OnWindowCreated func(app *App)
OnWindowDestroyed func(app *App)
OnWindowFocusChanged func(app *App, hasFocus bool)
OnInputEvent func(app *App, event *input.Event) bool
}
// Run sets up NativeActivity lifecycle callbacks and manages the App instance.
// Call this from an init() function in your main package.
func Run(handlers Handlers) {
app := &App{}
activity.SetLifecycleCallbacks(activity.LifecycleCallbacks{
OnCreate: func(act *activity.Activity) {
app.setActivity(act)
if handlers.OnCreate != nil {
handlers.OnCreate(app)
}
},
OnNativeWindowCreated: func(act *activity.Activity, win unsafe.Pointer) {
app.setActivity(act)
app.setWindow(win)
if handlers.OnWindowCreated != nil {
handlers.OnWindowCreated(app)
}
},
OnResume: func(act *activity.Activity) {
app.setActivity(act)
if handlers.OnResume != nil {
handlers.OnResume(app)
}
},
OnPause: func(act *activity.Activity) {
if handlers.OnPause != nil {
handlers.OnPause(app)
}
},
OnWindowFocusChanged: func(_ *activity.Activity, hasFocus int32) {
if handlers.OnWindowFocusChanged != nil {
handlers.OnWindowFocusChanged(app, hasFocus != 0)
}
},
OnNativeWindowDestroyed: func(_ *activity.Activity, _ unsafe.Pointer) {
if handlers.OnWindowDestroyed != nil {
handlers.OnWindowDestroyed(app)
}
app.setWindow(nil)
},
OnInputQueueCreated: func(_ *activity.Activity, queuePtr unsafe.Pointer) {
if handlers.OnInputEvent != nil {
q := input.NewQueueFromPointer(queuePtr)
go drainInput(app, q, handlers.OnInputEvent)
}
},
OnDestroy: func(_ *activity.Activity) {
if handlers.OnDestroy != nil {
handlers.OnDestroy(app)
}
app.setActivity(nil)
app.setWindow(nil)
},
})
}
func drainInput(
app *App,
q *input.Queue,
handler func(app *App, event *input.Event) bool,
) {
for {
ev := q.GetEvent()
if ev == nil {
return
}
if q.PreDispatchEvent(ev) {
continue
}
handled := handler(app, ev)
var result int32
if handled {
result = 1
}
q.FinishEvent(ev, result)
}
}