aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/kotlin/ca/allanwang/kau/utils/ActivityUtils.kt
blob: 21141f1f6bf8e5435ebb802f3ec35e1ad5e7dec1 (plain)
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
/*
 * Copyright 2018 Allan Wang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
@file:Suppress("NOTHING_TO_INLINE")

package ca.allanwang.kau.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.annotation.RequiresApi
import androidx.annotation.StringRes
import ca.allanwang.kau.R
import com.google.android.material.snackbar.Snackbar
import com.mikepenz.iconics.typeface.IIcon

/**
 * Created by Allan Wang on 2017-06-21.
 */

@DslMarker
@Target(AnnotationTarget.CLASS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
annotation class KauActivity

/**
 * Helper class to launch an activity for result
 * Counterpart of [Activity.startActivityForResult]
 * For starting activities without result, see [startActivity]
 */
@Suppress("DEPRECATION")
inline fun <reified T : Activity> Activity.startActivityForResult(
    requestCode: Int,
    bundleBuilder: Bundle.() -> Unit = {},
    intentBuilder: Intent.() -> Unit = {}
) = startActivityForResult(T::class.java, requestCode, bundleBuilder, intentBuilder)

@Deprecated(
    "Use reified generic instead of passing class",
    ReplaceWith("startActivityForResult<T>(requestCode, bundleBuilder, intentBuilder)"),
    DeprecationLevel.WARNING
)
inline fun <T : Activity> Activity.startActivityForResult(
    clazz: Class<T>,
    requestCode: Int,
    bundleBuilder: Bundle.() -> Unit = {},
    intentBuilder: Intent.() -> Unit = {}
) {
    val intent = Intent(this, clazz)
    intent.intentBuilder()
    val bundle = Bundle()
    bundle.bundleBuilder()
    startActivityForResult(intent, requestCode, if (bundle.isEmpty) null else bundle)
}

/**
 * Restarts an activity from itself with a fade animation
 * Keeps its existing extra bundles and has a intentBuilder to accept other parameters
 */
inline fun Activity.restart(intentBuilder: Intent.() -> Unit = {}) {
    val i = Intent(this, this::class.java)
    val oldExtras = intent.extras
    if (oldExtras != null)
        i.putExtras(oldExtras)
    i.intentBuilder()
    startActivity(i)
    overridePendingTransition(R.anim.kau_fade_in, R.anim.kau_fade_out) //No transitions
    finish()
    overridePendingTransition(R.anim.kau_fade_in, R.anim.kau_fade_out)
}

/**
 * Force restart an entire application
 */
@RequiresApi(Build.VERSION_CODES.M)
inline fun Activity.restartApplication() {
    val intent = packageManager.getLaunchIntentForPackage(packageName)!!
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
    val pending = PendingIntent.getActivity(this, 666, intent, PendingIntent.FLAG_CANCEL_CURRENT)
    val alarm = getSystemService(Context.ALARM_SERVICE) as AlarmManager
    if (buildIsMarshmallowAndUp)
        alarm.setExactAndAllowWhileIdle(AlarmManager.RTC, System.currentTimeMillis() + 100, pending)
    else
        alarm.setExact(AlarmManager.RTC, System.currentTimeMillis() + 100, pending)
    finish()
    System.exit(0)
}

fun Activity.finishSlideOut() {
    finish()
    overridePendingTransition(R.anim.kau_fade_in, R.anim.kau_slide_out_right_top)
}

inline var Activity.navigationBarColor: Int
    @SuppressLint("NewApi")
    get() = if (buildIsLollipopAndUp) window.navigationBarColor else Color.BLACK
    @SuppressLint("NewApi")
    set(value) {
        if (buildIsLollipopAndUp) window.navigationBarColor = value
    }

inline var Activity.statusBarColor: Int
    @SuppressLint("NewApi")
    get() = if (buildIsLollipopAndUp) window.statusBarColor else Color.BLACK
    @SuppressLint("NewApi")
    set(value) {
        if (buildIsLollipopAndUp) window.statusBarColor = value
    }

inline var Activity.statusBarLight: Boolean
    @SuppressLint("InlinedApi")
    get() = if (buildIsMarshmallowAndUp) window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR > 0 else false
    @SuppressLint("InlinedApi")
    set(value) {
        if (buildIsMarshmallowAndUp) {
            val flags = window.decorView.systemUiVisibility
            window.decorView.systemUiVisibility =
                if (value) flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                else flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
        }
    }

/**
 * Themes the base menu icons and adds iicons programmatically based on ids
 *
 * Call in [Activity.onCreateOptionsMenu]
 */
fun Context.setMenuIcons(menu: Menu, @ColorInt color: Int = Color.WHITE, vararg iicons: Pair<Int, IIcon>) {
    iicons.forEach { (id, iicon) ->
        menu.findItem(id).icon = iicon.toDrawable(this, sizeDp = 18, color = color)
    }
}

inline fun Activity.hideKeyboard() {
    currentFocus?.hideKeyboard()
}

inline fun Activity.showKeyboard() {
    currentFocus?.showKeyboard()
}

/**
 * Gets the view set by [Activity.setContentView] if it exists.
 *
 * Taken courtesy of <a href="https://github.com/Kotlin/anko">Anko</a>
 *
 * Previously, Anko was a dependency in KAU, but has been removed on 12/24/2018
 * as most of the methods weren't used
 */
inline val Activity.contentView: View?
    get() = (findViewById(android.R.id.content) as? ViewGroup)?.getChildAt(0)

inline fun Activity.snackbar(
    text: String,
    duration: Int = Snackbar.LENGTH_LONG,
    noinline builder: Snackbar.() -> Unit = {}
) = contentView!!.snackbar(text, duration, builder)

inline fun Activity.snackbar(
    @StringRes textId: Int,
    duration: Int = Snackbar.LENGTH_LONG,
    noinline builder: Snackbar.() -> Unit = {}
) = contentView!!.snackbar(textId, duration, builder)