-
-
Notifications
You must be signed in to change notification settings - Fork 800
Expand file tree
/
Copy pathBaseActivity.kt
More file actions
333 lines (290 loc) · 13.4 KB
/
BaseActivity.kt
File metadata and controls
333 lines (290 loc) · 13.4 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
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
package org.wikipedia.activity
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.MotionEvent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.ColorInt
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.skydoves.balloon.Balloon
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.wikimedia.testkitchen.instrument.InstrumentImpl
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.BreadcrumbsContextHelper
import org.wikipedia.analytics.eventplatform.BreadCrumbLogEvent
import org.wikipedia.analytics.eventplatform.EventPlatformClient
import org.wikipedia.analytics.testkitchen.TestKitchenAdapter
import org.wikipedia.appshortcuts.AppShortcuts
import org.wikipedia.auth.AccountUtil
import org.wikipedia.concurrency.FlowEventBus
import org.wikipedia.connectivity.ConnectionStateMonitor
import org.wikipedia.donate.DonateDialog
import org.wikipedia.events.LoggedOutInBackgroundEvent
import org.wikipedia.events.ReadingListsEnableDialogEvent
import org.wikipedia.events.ReadingListsNoLongerSyncedEvent
import org.wikipedia.events.SplitLargeListsEvent
import org.wikipedia.events.ThemeFontChangeEvent
import org.wikipedia.events.UnreadNotificationsEvent
import org.wikipedia.games.onthisday.OnThisDayGameResultFragment
import org.wikipedia.login.LoginActivity
import org.wikipedia.main.MainActivity
import org.wikipedia.notifications.NotificationPresenter
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.readinglist.ReadingListSyncBehaviorDialogs
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.readinglist.sync.ReadingListSyncEvent
import org.wikipedia.recurring.RecurringTasksExecutor
import org.wikipedia.richtext.CustomHtmlParser
import org.wikipedia.settings.Prefs
import org.wikipedia.theme.Theme
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.views.ImageZoomHelper
import org.wikipedia.yearinreview.YearInReviewActivity
import org.wikipedia.yearinreview.YearInReviewOnboardingActivity
import org.wikipedia.yearinreview.YearInReviewViewModel
abstract class BaseActivity : AppCompatActivity(), ConnectionStateMonitor.Callback {
interface Callback {
fun onPermissionResult(activity: BaseActivity, isGranted: Boolean)
}
private var currentTooltip: Balloon? = null
private var imageZoomHelper: ImageZoomHelper? = null
var callback: Callback? = null
// For subclasses to create instruments that they would like to persist for the lifetime of the activity.
protected var _instrument: InstrumentImpl? = null
val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
callback?.onPermissionResult(this, isGranted)
}
private val requestDonateActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
ExclusiveBottomSheetPresenter.dismiss(supportFragmentManager)
FeedbackUtil.showMessage(this, R.string.donate_gpay_success_message)
}
}
@RequiresApi(Build.VERSION_CODES.O)
private val notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if(!granted){
if(ActivityCompat.shouldShowRequestPermissionRationale(this,android.Manifest.permission.POST_NOTIFICATIONS)){
//User denied once->Show Snackbar
FeedbackUtil.makeSnackbar(this, getString(R.string.notification_permission_rationale))
.setAction(R.string.notification_permission_rationale_action){
DeviceUtil.openNotificationSettings(this)
}
.show()
}else{
//User denied (with "Don't Ask Again")
FeedbackUtil.makeSnackbar(this, getString(R.string.notification_permission_denied))
.setAction(R.string.app_settings){
DeviceUtil.openNotificationSettings(this)
}
.show()
}
}
}
private val yearInReviewLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_CANCELED) {
FeedbackUtil.showMessage(this, getString(R.string.year_in_review_get_started_later))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!DeviceUtil.assertAppContext(this, true)) {
finish()
return
}
setTheme()
removeSplashBackground()
if (AppShortcuts.ACTION_APP_SHORTCUT == intent.action) {
intent.putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, Constants.InvokeSource.APP_SHORTCUTS)
val shortcutId = intent.getStringExtra(AppShortcuts.APP_SHORTCUT_ID)
if (!shortcutId.isNullOrEmpty()) {
ShortcutManagerCompat.reportShortcutUsed(applicationContext, shortcutId)
}
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Conditionally execute all recurring tasks
RecurringTasksExecutor().run()
if (Prefs.isReadingListsFirstTimeSync && AccountUtil.isLoggedIn) {
Prefs.isReadingListsFirstTimeSync = false
Prefs.isReadingListSyncEnabled = true
ReadingListSyncAdapter.manualSyncWithForce()
}
WikipediaApp.instance.connectionStateMonitor.registerCallback(this)
DeviceUtil.setLightSystemUiVisibility(this)
setStatusBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color))
setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color))
maybeShowLoggedOutInBackgroundDialog()
maybeShowYearInReview()
Prefs.localClassName = localClassName
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
FlowEventBus.events.collectLatest { event ->
if (event is ThemeFontChangeEvent) {
ActivityCompat.recreate(this@BaseActivity)
}
}
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
FlowEventBus.events.collectLatest { event ->
when (event) {
is SplitLargeListsEvent -> {
MaterialAlertDialogBuilder(this@BaseActivity)
.setMessage(getString(R.string.split_reading_list_message, Constants.MAX_READING_LIST_ARTICLE_LIMIT))
.setPositiveButton(R.string.reading_list_split_dialog_ok_button_text, null)
.show()
}
is ReadingListsNoLongerSyncedEvent -> {
ReadingListSyncBehaviorDialogs.detectedRemoteTornDownDialog(this@BaseActivity)
}
is ReadingListsEnableDialogEvent, (this@BaseActivity is MainActivity) -> {
ReadingListSyncBehaviorDialogs.promptEnableSyncDialog(this@BaseActivity)
}
is LoggedOutInBackgroundEvent -> {
maybeShowLoggedOutInBackgroundDialog()
}
is ReadingListSyncEvent -> {
if (event.showMessage && !Prefs.isSuggestedEditsHighestPriorityEnabled) {
FeedbackUtil.makeSnackbar(this@BaseActivity, getString(R.string.reading_list_toast_last_sync)).show()
}
}
is UnreadNotificationsEvent -> {
runOnUiThread {
if (!isDestroyed) {
onUnreadNotification()
}
}
}
}
}
}
}
}
override fun onDestroy() {
WikipediaApp.instance.connectionStateMonitor.unregisterCallback(this)
CustomHtmlParser.pruneBitmaps(this)
super.onDestroy()
}
override fun onPause() {
super.onPause()
WikipediaApp.instance.appSessionEvent.persistSession()
TestKitchenAdapter.client.onAppPause()
EventPlatformClient.flushCachedEvents()
}
override fun onResume() {
super.onResume()
WikipediaApp.instance.appSessionEvent.touchSession()
TestKitchenAdapter.client.onAppResume()
BreadCrumbLogEvent.logScreenShown(this)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onStart() {
super.onStart()
NotificationPresenter.maybeRequestPermission(this, notificationPermissionLauncher)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressedDispatcher.onBackPressed()
true
}
else -> false
}
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN ||
event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) {
dismissCurrentTooltip()
}
BreadcrumbsContextHelper.dispatchTouchEvent(window, event)
imageZoomHelper?.let {
return it.onDispatchTouchEvent(event) || super.dispatchTouchEvent(event)
}
return super.dispatchTouchEvent(event)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && data?.hasExtra(OnThisDayGameResultFragment.EXTRA_GAME_COMPLETED) == true) {
OnThisDayGameResultFragment.maybeShowOnThisDayGameEndContent(this)
}
}
protected fun setStatusBarColor(@ColorInt color: Int) {
window.statusBarColor = color
}
protected fun setNavigationBarColor(@ColorInt color: Int) {
DeviceUtil.setNavigationBarColor(window, color)
}
protected open fun setTheme() {
if (WikipediaApp.instance.currentTheme != Theme.LIGHT) {
setTheme(WikipediaApp.instance.currentTheme.resourceId)
}
}
override fun onGoOffline() {}
override fun onGoOnline() {}
fun launchDonateDialog(campaignId: String? = null, donateUrl: String? = null) {
ExclusiveBottomSheetPresenter.show(supportFragmentManager, DonateDialog.newInstance(campaignId, donateUrl))
}
fun launchDonateActivity(intent: Intent) {
requestDonateActivity.launch(intent)
}
fun getInstrument(): InstrumentImpl? {
return _instrument
}
private fun maybeShowYearInReview() {
if (this !is YearInReviewOnboardingActivity && this !is YearInReviewActivity &&
!Prefs.isInitialOnboardingEnabled &&
YearInReviewViewModel.isAccessible && Prefs.isYearInReviewEnabled && !Prefs.yearInReviewVisited) {
yearInReviewLauncher.launch((YearInReviewOnboardingActivity.newIntent(this)))
}
}
private fun removeSplashBackground() {
window.setBackgroundDrawable(ColorDrawable(ResourceUtil.getThemedColor(this, R.attr.paper_color)))
}
private fun maybeShowLoggedOutInBackgroundDialog() {
if (Prefs.loggedOutInBackground) {
Prefs.loggedOutInBackground = false
val instrument = TestKitchenAdapter.client.getInstrument("apps-authentication")
.setDefaultActionSource("logout_background_dialog")
.startFunnel("logout_account_background")
instrument.submitInteraction("impression")
MaterialAlertDialogBuilder(this)
.setCancelable(false)
.setTitle(R.string.logged_out_in_background_title)
.setMessage(R.string.logged_out_in_background_dialog)
.setPositiveButton(R.string.logged_out_in_background_login) { _, _ ->
instrument.submitInteraction("click", elementId = "login_button")
startActivity(LoginActivity.newIntent(this@BaseActivity, LoginActivity.SOURCE_LOGOUT_BACKGROUND))
}
.setNegativeButton(R.string.logged_out_in_background_cancel) { _, _ ->
instrument.submitInteraction("click", elementId = "cancel")
}
.show()
}
}
private fun dismissCurrentTooltip() {
currentTooltip?.dismiss()
currentTooltip = null
}
fun setCurrentTooltip(tooltip: Balloon) {
dismissCurrentTooltip()
currentTooltip = tooltip
}
fun setImageZoomHelper() {
imageZoomHelper = ImageZoomHelper(this)
}
open fun onUnreadNotification() { }
}