Skip to content

Commit

Permalink
Refactor Repository
Browse files Browse the repository at this point in the history
Change-Id: I1040ecef0254d2ae7d659b013cbe64e58a6420da
  • Loading branch information
secondsun committed Mar 22, 2024
1 parent 920a557 commit 72d3cb1
Show file tree
Hide file tree
Showing 6 changed files with 291 additions and 249 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,16 @@
package com.google.android.samples.socialite

import android.app.Application
import com.google.android.samples.socialite.widget.SocialiteWidget
import com.google.android.samples.socialite.widget.SociaLiteAppWidget
import com.google.android.samples.socialite.widget.model.WidgetModelRepository
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject

@HiltAndroidApp
class SocialApp : Application() {

@Inject lateinit var repository: WidgetModelRepository
override fun onCreate() {
super.onCreate()
SocialiteWidget.update(this@SocialApp, repository)
SociaLiteAppWidget.update(this@SocialApp)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import com.google.android.samples.socialite.widget.model.WidgetModelDao
WidgetModel::class,
],
views = [ChatWithLastMessage::class],
version = 2,
version = 1,
)
abstract class AppDatabase : RoomDatabase() {
abstract fun contactDao(): ContactDao
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,6 @@ object DatabaseModule {
@Provides
fun providesWidgetModelDao(database: AppDatabase): WidgetModelDao = database.widgetDao()

@Provides
fun provideWidgetModelRepository(widgetModelDao: WidgetModelDao, @ApplicationContext appContext: Context) = WidgetModelRepository(widgetModelDao, providesApplicationCoroutineScope(), appContext)

@Provides
@Singleton
@AppCoroutineScope
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* 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.
*/

package com.google.android.samples.socialite.widget

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.drawable.toBitmapOrNull
import androidx.core.net.toUri
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.GlanceTheme
import androidx.glance.Image
import androidx.glance.ImageProvider
import androidx.glance.LocalContext
import androidx.glance.action.clickable
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.glance.appwidget.ImageProvider
import androidx.glance.appwidget.SizeMode
import androidx.glance.appwidget.action.actionStartActivity
import androidx.glance.appwidget.components.Scaffold
import androidx.glance.appwidget.components.TitleBar
import androidx.glance.appwidget.lazy.LazyColumn
import androidx.glance.appwidget.provideContent
import androidx.glance.appwidget.updateAll
import androidx.glance.layout.Alignment
import androidx.glance.layout.Box
import androidx.glance.layout.Column
import androidx.glance.layout.ContentScale
import androidx.glance.layout.Row
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.padding
import androidx.glance.layout.size
import androidx.glance.layout.wrapContentHeight
import androidx.glance.text.FontFamily
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
import coil.Coil
import coil.request.CachePolicy
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.SuccessResult
import coil.transform.CircleCropTransformation
import com.google.android.samples.socialite.MainActivity
import com.google.android.samples.socialite.R
import com.google.android.samples.socialite.SocialApp
import com.google.android.samples.socialite.model.Contact
import com.google.android.samples.socialite.widget.model.WidgetModel
import com.google.android.samples.socialite.widget.model.WidgetModelRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class SociaLiteAppWidget : GlanceAppWidget() {

override val sizeMode: SizeMode
get() = SizeMode.Exact

override suspend fun provideGlance(context: Context, glanceId: GlanceId) {

val glanceAppWidgetManager = GlanceAppWidgetManager(context)
val widgetId = glanceAppWidgetManager.getAppWidgetId(glanceId)
Log.i("SOCIAL", "$widgetId")
provideContent {
Content(widgetId, context)
}
}

companion object {
fun update(context: Context) {
CoroutineScope(Dispatchers.Default).launch {
SociaLiteAppWidget().updateAll(context)
}
}
}

@Composable
private fun Content(widgetId: Int, context: Context) {
val repository = WidgetModelRepository.get(context)
val model = repository.loadModel(widgetId).collectAsState(null).value
GlanceTheme {
Scaffold(
titleBar = {
TitleBar(
textColor = GlanceTheme.colors.onSurface,
startIcon = ImageProvider(R.mipmap.ic_launcher),
title = "SociaLite",
)
},
backgroundColor = GlanceTheme.colors.widgetBackground,
modifier = GlanceModifier.fillMaxSize(),
) {
when (model) {
null -> ZeroState(repository, widgetId, context)
else -> FavoriteContact(model)
}
}
}
}

@Composable
private fun FavoriteContact(model: WidgetModel) {
val appContext = LocalContext.current.applicationContext
Box(
modifier = GlanceModifier.fillMaxSize().then(

if (model.unreadMessages) {
GlanceModifier.clickable(
actionStartActivity(
Intent(appContext, MainActivity::class.java)
.setAction(Intent.ACTION_VIEW)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.setData("https://socialite.google.com/chat/${model.contactId}".toUri()),
),
)
} else {
GlanceModifier
},
),
contentAlignment = Alignment.Center,
) {
Column {
Image(
provider = ImageProvider(model.photo.toUri()),
contentDescription = model.displayName,
)
Text(
text = model.displayName,
style = TextStyle(
fontWeight = FontWeight.Bold,
color = GlanceTheme.colors.onBackground,
),
)
Text(
text = if (model.unreadMessages) "New Message!" else "No messages",
style = TextStyle(color = GlanceTheme.colors.onBackground),
)
}
}
}

@Composable
private fun ZeroState(repository: WidgetModelRepository, widgetId: Int, context: Context) {
Box(modifier = GlanceModifier.fillMaxSize(), contentAlignment = Alignment.TopStart) {
LazyColumn {
items(Contact.CONTACTS.size) { contactIndex ->
val contact = Contact.CONTACTS[contactIndex]
val profileImage = remember(contact.iconUri) { mutableStateOf<Bitmap?>(null) }

LaunchedEffect(contact.iconUri) {
profileImage.value = getImage(contact.iconUri, false, context)
}

Row(
modifier = GlanceModifier.fillMaxWidth().clickable(
{
runBlocking {
repository.create(
WidgetModel(
widgetId,
contact.id,
contact.name,
contact.iconUri.toString(),
false,
),
)
}
},
).wrapContentHeight().padding(4.dp),
verticalAlignment = Alignment.Vertical.CenterVertically,
) {
Image(
modifier = GlanceModifier.size(48.dp).padding(end = 8.dp),
contentScale = ContentScale.Fit,
provider = if (profileImage.value == null) {
ImageProvider(R.drawable.ic_launcher_background)
} else {
ImageProvider(
profileImage.value!!,
)
},
contentDescription = "Avatar",

)
Column(
modifier = GlanceModifier.defaultWeight(),
horizontalAlignment = Alignment.Horizontal.Start,
) {
Text(
text = contact.name,
style = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 16.sp,
color = GlanceTheme.colors.onBackground,
),
)
Text(
text = "Click to select as favorite contact",
style = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
fontFamily = FontFamily.Monospace,
color = GlanceTheme.colors.onBackground,
),
)
}
}
}
}
}
}

private suspend fun getImage(url: Uri, force: Boolean = false, context: Context): Bitmap? {
val request =
ImageRequest.Builder(context).transformations(CircleCropTransformation()).data(url)
.apply {
if (force) {
memoryCachePolicy(CachePolicy.DISABLED)
diskCachePolicy(CachePolicy.DISABLED)
}
}.build()

// Request the image to be loaded and throw error if it failed
return when (val result = Coil.imageLoader(context).execute(request)) {
is ErrorResult -> {
Log.e("GLANCE", "Error " + result.throwable.message)
throw result.throwable
}

is SuccessResult -> result.drawable.toBitmapOrNull()
}
}
}
Loading

0 comments on commit 72d3cb1

Please sign in to comment.