/
MainActivity.kt
252 lines (217 loc) · 8.51 KB
/
MainActivity.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
package com.google.firebase.quickstart.analytics.kotlin
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.preference.PreferenceManager
import androidx.viewpager.widget.ViewPager
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.analytics.R
import com.google.firebase.quickstart.analytics.databinding.ActivityMainBinding
import java.util.Locale
/**
* Activity which displays numerous background images that may be viewed. These background images
* are shown via {@link ImageFragment}.
*/
class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = "MainActivity"
private const val KEY_FAVORITE_FOOD = "favorite_food"
private val IMAGE_INFOS = arrayOf(
ImageInfo(R.drawable.favorite, R.string.pattern1_title, R.string.pattern1_id),
ImageInfo(R.drawable.flash, R.string.pattern2_title, R.string.pattern2_id),
ImageInfo(R.drawable.face, R.string.pattern3_title, R.string.pattern3_id),
ImageInfo(R.drawable.whitebalance, R.string.pattern4_title, R.string.pattern4_id)
)
}
private lateinit var binding: ActivityMainBinding
/**
* The [androidx.viewpager.widget.PagerAdapter] that will provide fragments for each image.
* This uses a [FragmentPagerAdapter], which keeps every loaded fragment in memory.
*/
private lateinit var imagePagerAdapter: ImagePagerAdapter
/**
* The `FirebaseAnalytics` used to record screen views.
*/
// [START declare_analytics]
private lateinit var firebaseAnalytics: FirebaseAnalytics
// [END declare_analytics]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// [START shared_app_measurement]
// Obtain the FirebaseAnalytics instance.
firebaseAnalytics = Firebase.analytics
// [END shared_app_measurement]
// On first app open, ask the user his/her favorite food. Then set this as a user property
// on all subsequent opens.
val userFavoriteFood = getUserFavoriteFood()
if (userFavoriteFood == null) {
askFavoriteFood()
} else {
setUserFavoriteFood(userFavoriteFood)
}
// Create the adapter that will return a fragment for each image.
imagePagerAdapter = ImagePagerAdapter(supportFragmentManager, IMAGE_INFOS)
// Set up the ViewPager with the pattern adapter.
binding.viewPager.adapter = imagePagerAdapter
// Workaround for AppCompat issue not showing ViewPager titles
val params = binding.pagerTabStrip.layoutParams as ViewPager.LayoutParams
params.isDecor = true
// When the visible image changes, send a screen view hit.
binding.viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
recordImageView()
recordScreenView()
}
})
// Send initial screen screen view hit.
recordImageView()
}
public override fun onResume() {
super.onResume()
recordScreenView()
}
/**
* Display a dialog prompting the user to pick a favorite food from a list, then record
* the answer.
*/
private fun askFavoriteFood() {
val choices = resources.getStringArray(R.array.food_items)
val ad = AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(R.string.food_dialog_title)
.setItems(choices) { _, which ->
val food = choices[which]
setUserFavoriteFood(food)
}.create()
ad.show()
}
/**
* Get the user's favorite food from shared preferences.
* @return favorite food, as a string.
*/
private fun getUserFavoriteFood(): String? {
return PreferenceManager.getDefaultSharedPreferences(this)
.getString(KEY_FAVORITE_FOOD, null)
}
/**
* Set the user's favorite food as an app measurement user property and in shared preferences.
* @param food the user's favorite food.
*/
private fun setUserFavoriteFood(food: String) {
Log.d(TAG, "setFavoriteFood: $food")
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putString(KEY_FAVORITE_FOOD, food)
.apply()
// [START user_property]
firebaseAnalytics.setUserProperty("favorite_food", food)
// [END user_property]
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val i = item.itemId
if (i == R.id.menu_share) {
val name = getCurrentImageTitle()
val text = "I'd love you to hear about $name"
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(Intent.EXTRA_TEXT, text)
sendIntent.type = "text/plain"
startActivity(sendIntent)
// [START custom_event]
firebaseAnalytics.logEvent("share_image") {
param("image_name", name)
param("full_text", text)
}
// [END custom_event]
}
return false
}
/**
* Return the title of the currently displayed image.
*
* @return title of image
*/
private fun getCurrentImageTitle(): String {
val position = binding.viewPager.currentItem
val info = IMAGE_INFOS[position]
return getString(info.title)
}
/**
* Return the id of the currently displayed image.
*
* @return id of image
*/
private fun getCurrentImageId(): String {
val position = binding.viewPager.currentItem
val info = IMAGE_INFOS[position]
return getString(info.id)
}
/**
* Record a screen view for the visible [ImageFragment] displayed
* inside [FragmentPagerAdapter].
*/
private fun recordImageView() {
val id = getCurrentImageId()
val name = getCurrentImageTitle()
// [START image_view_event]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) {
param(FirebaseAnalytics.Param.ITEM_ID, id)
param(FirebaseAnalytics.Param.ITEM_NAME, name)
param(FirebaseAnalytics.Param.CONTENT_TYPE, "image")
}
// [END image_view_event]
}
/**
* This sample has a single Activity, so we need to manually record "screen views" as
* we change fragments.
*/
private fun recordScreenView() {
// This string must be <= 36 characters long.
val screenName = "${getCurrentImageId()}-${getCurrentImageTitle()}"
// [START set_current_screen]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
param(FirebaseAnalytics.Param.SCREEN_NAME, screenName)
param(FirebaseAnalytics.Param.SCREEN_CLASS, "MainActivity")
}
// [END set_current_screen]
}
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
@SuppressLint("WrongConstant")
inner class ImagePagerAdapter(
fm: FragmentManager,
private val infos: Array<ImageInfo>
) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(position: Int): Fragment {
val info = infos[position]
return ImageFragment.newInstance(info.image)
}
override fun getCount() = infos.size
override fun getPageTitle(position: Int): CharSequence? {
if (position < 0 || position >= infos.size) {
return null
}
val l = Locale.getDefault()
val info = infos[position]
return getString(info.title).toUpperCase(l)
}
}
}