-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathLottieSplashScreen.kt
360 lines (326 loc) · 13.3 KB
/
LottieSplashScreen.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package de.dustplanet.cordova.lottie
import android.R.style
import android.animation.Animator
import android.app.Dialog
import android.content.Context
import android.content.res.Configuration
import android.graphics.drawable.ColorDrawable
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.ImageView
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieCompositionFactory
import com.airbnb.lottie.LottieDrawable
import com.airbnb.lottie.LottieTask
import com.airbnb.lottie.RenderMode
import org.apache.cordova.CallbackContext
import org.apache.cordova.CordovaArgs
import org.apache.cordova.CordovaPlugin
import java.util.Locale
class LottieSplashScreen : CordovaPlugin() {
private lateinit var splashDialog: Dialog
private lateinit var animationView: LottieAnimationView
private var animationEnded = false
override fun pluginInitialize() {
super.initialize(cordova, webView)
try {
createView()
} catch (e: Exception) {
Log.e(LOG_TAG, e.message!!)
e.printStackTrace()
}
}
override fun onMessage(id: String?, data: Any?): Any? {
if ("onPageFinished" == id) {
val autoHide = preferences.getBoolean("LottieAutoHideSplashScreen", false)
if (autoHide) {
destroyView()
}
}
return null
}
override fun execute(action: String, args: CordovaArgs, callbackContext: CallbackContext): Boolean {
when (action) {
"hide" ->
return try {
destroyView(callbackContext)
true
} catch (e: Exception) {
callbackContext.error(e.message)
false
}
"show" ->
return try {
createView(
if (args.isNull(0)) null else args.getString(0),
if (args.isNull(1)) null else args.getBoolean(1),
if (args.isNull(2)) null else args.getDouble(2),
if (args.isNull(3)) null else args.getDouble(3),
callbackContext
)
true
} catch (e: Exception) {
callbackContext.error(e.message)
false
}
"initialAnimationEnded" -> {
callbackContext.success(animationEnded.toString())
return true
}
else -> return false
}
}
private fun destroyView(callbackContext: CallbackContext? = null) {
cordova.activity.runOnUiThread {
animationView.cancelAnimation()
if (::splashDialog.isInitialized) {
dismissDialog(callbackContext)
}
}
}
private fun createView(
location: String? = null,
remote: Boolean? = null,
width: Double? = null,
height: Double? = null,
callbackContext: CallbackContext? = null
) {
if (::splashDialog.isInitialized && splashDialog.isShowing) {
throw LottieSplashScreenAnimationAlreadyPlayingException("An animation is already playing, please first hide the current one")
}
cordova.activity.runOnUiThread {
if (cordova.activity.isFinishing.not()) {
val context = webView.context
animationView = LottieAnimationView(context)
val useHardwareAcceleration = remote
?: preferences.getBoolean("LottieEnableHardwareAcceleration", false)
if (useHardwareAcceleration) {
animationView.setRenderMode(RenderMode.HARDWARE)
}
val remoteEnabled = remote ?: preferences.getBoolean("LottieRemoteEnabled", false)
val animationLocation = getAnimationLocation(location)
if (animationLocation.isBlank()) {
Log.e(LOG_TAG, "LottieAnimationLocation has to be configured!")
this.destroyView()
val invalidURLException = LottieSplashScreenInvalidURLException("The provided animation is invalid")
if (callbackContext != null) {
callbackContext.error(invalidURLException.message)
return@runOnUiThread
} else {
throw invalidURLException
}
}
createLottieComposition(remoteEnabled, context, animationLocation, callbackContext)
configureAnimationView(context)
calculateAnimationSize(width, height)
splashDialog.show()
addAnimationListeners()
animationView.playAnimation()
animationEnded = false
val delay = preferences.getInteger("LottieHideTimeout", 0)
if (delay > 0) {
val handler = Handler(Looper.getMainLooper())
handler.postDelayed({ dismissDialog() }, delay.toLong())
}
}
}
}
private fun getAnimationLocation(location: String?): String {
var animationLocation = location
if (animationLocation.isNullOrBlank()) {
animationLocation = getUIModeDependentPreference("LottieAnimationLocation")
}
return animationLocation
}
private fun createLottieComposition(
remoteEnabled: Boolean,
context: Context?,
animationLocation: String,
callbackContext: CallbackContext?
) {
val comp: LottieTask<LottieComposition>
val cacheDisabled = preferences.getBoolean("LottieCacheDisabled", false)
when {
remoteEnabled -> {
comp = LottieCompositionFactory.fromUrl(
context,
animationLocation,
when {
cacheDisabled -> null
else -> "url_$animationLocation"
}
)
}
else -> {
comp = LottieCompositionFactory.fromAsset(
context,
animationLocation,
when {
cacheDisabled -> null
else -> "asset_$animationLocation"
}
)
animationView.imageAssetsFolder = preferences.getString(
"LottieImagesLocation",
animationLocation.substring(
0,
animationLocation.lastIndexOf('/')
)
)
}
}
comp.addListener { animationView.setComposition(it) }.addFailureListener {
Log.e(LOG_TAG, "Animation not loadable!")
Log.e(LOG_TAG, Log.getStackTraceString(it))
this.destroyView()
if (callbackContext != null) {
val invalidURLException = LottieSplashScreenInvalidURLException("The provided animation is invalid")
callbackContext.error(invalidURLException.message)
}
}
}
private fun configureAnimationView(context: Context) {
animationView.enableMergePathsForKitKatAndAbove(true)
if (preferences.getBoolean("LottieLoopAnimation", false)) {
animationView.repeatCount = LottieDrawable.INFINITE
}
animationView.scaleType = ImageView.ScaleType.valueOf(
preferences.getString(
"LottieScaleType",
"FIT_CENTER"
).toUpperCase(Locale.ENGLISH)
)
val color = ColorHelper.parseColor(
getUIModeDependentPreference(
"LottieBackgroundColor",
"#ffffff"
)
)
animationView.setBackgroundColor(color)
val fullScreen = preferences.getBoolean("LottieFullScreen", false)
splashDialog = Dialog(
context,
when {
fullScreen -> style.Theme_NoTitleBar_Fullscreen
else -> style.Theme_Translucent_NoTitleBar
}
)
splashDialog.window?.setBackgroundDrawable(ColorDrawable(color))
splashDialog.setContentView(animationView)
splashDialog.setCancelable(false)
}
private fun calculateAnimationSize(width: Double? = null, height: Double? = null) {
val fullScreen = preferences.getBoolean("LottieFullScreen", false)
if (!fullScreen) {
val relativeSize = preferences.getBoolean("LottieRelativeSize", false)
if (relativeSize) {
val metrics = webView.context.resources.displayMetrics
val animationHeight = (
metrics.heightPixels * (
width
?: preferences.getDouble("LottieWidth", 0.2)
)
).toInt()
val animationWidth = (
metrics.widthPixels * (
height
?: preferences.getDouble("LottieHeight", 0.2)
)
).toInt()
splashDialog.window?.setLayout(animationHeight, animationWidth)
} else {
splashDialog.window?.setLayout(
convertPixelsToDp(
width
?: preferences.getDouble("LottieWidth", 200.0)
),
convertPixelsToDp(
height
?: preferences.getDouble("LottieHeight", 200.0)
)
)
}
}
}
private fun addAnimationListeners() {
animationView.addAnimatorListener(
object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
webView.engine.evaluateJavascript("document.dispatchEvent(new Event('lottieAnimationStart'))") { }
}
override fun onAnimationEnd(animation: Animator) {
webView.engine.evaluateJavascript("document.dispatchEvent(new Event('lottieAnimationEnd'))") { }
val hideAfterAnimationDone = preferences.getBoolean(
"LottieHideAfterAnimationEnd",
false
)
when {
hideAfterAnimationDone -> dismissDialog()
}
animationEnded = true
}
override fun onAnimationCancel(animation: Animator) {
webView.engine.evaluateJavascript("document.dispatchEvent(new Event('lottieAnimationCancel'))") { }
}
override fun onAnimationRepeat(animation: Animator) {
webView.engine.evaluateJavascript("document.dispatchEvent(new Event('lottieAnimationRepeat'))") { }
}
}
)
animationView.setOnClickListener {
val cancelOnTap = preferences.getBoolean("LottieCancelOnTap", false)
if (cancelOnTap) {
animationView.cancelAnimation()
dismissDialog()
}
}
}
private fun convertPixelsToDp(px: Double): Int {
return (px * webView.context.resources.displayMetrics.density).toInt()
}
private fun dismissDialog(callbackContext: CallbackContext? = null) {
val fadeDuration = preferences.getInteger("LottieFadeOutDuration", 0)
when {
fadeDuration > 0 -> {
val fadeOut = AlphaAnimation(1f, 0f)
fadeOut.duration = fadeDuration.toLong()
animationView.animation = fadeOut
animationView.startAnimation(fadeOut)
fadeOut.setAnimationListener(
object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) {
splashDialog.dismiss()
callbackContext?.success()
}
override fun onAnimationRepeat(animation: Animation?) {}
}
)
}
else -> {
splashDialog.dismiss()
callbackContext?.success()
}
}
}
private fun getUIModeDependentPreference(preferenceBaseName: String, defaultValue: String? = ""): String {
val nightMode: Boolean = cordova.context.resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
var preferenceValue: String
preferenceValue = when {
nightMode -> preferences.getString("""${preferenceBaseName}Dark""", defaultValue)
else -> preferences.getString("""${preferenceBaseName}Light""", defaultValue)
}
if (preferenceValue.isBlank()) {
preferenceValue = preferences.getString(preferenceBaseName, defaultValue)
}
return preferenceValue
}
companion object {
private const val LOG_TAG = "LottieSplashScreen"
}
}