Created
June 30, 2022 14:42
-
-
Save Astroa7m/ce98a6744c3d0032a6515229dc53f8a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RemoteWidget : GlanceAppWidget(errorUiLayout = R.layout.widget_error_layout) { | |
override val stateDefinition: GlanceStateDefinition<*> | |
get() = CustomGlanceStateDefinition | |
@Composable | |
override fun Content() { | |
val pref = currentState<Preferences>() | |
val filePathString: String = remember { | |
pref[stringPreferencesKey(FILE_URI)] ?: "" | |
} | |
val bitmap = rememberImageBitmap(filePathString) | |
Image( | |
provider = ImageProvider(bitmap), | |
contentDescription = null, | |
modifier = GlanceModifier.fillMaxSize(), | |
contentScale = ContentScale.Crop | |
) | |
} | |
@Composable | |
private fun rememberImageBitmap(filePathString: String): Bitmap { | |
val context = LocalContext.current | |
return remember { | |
if (filePathString.isEmpty()) { | |
val file = context.applicationContext.filesDir | |
.listFiles() | |
?.find { it.path.endsWith(".jpg") } | |
val path = file?.toURI()?.path | |
BitmapFactory.decodeFile(path) | |
} else | |
BitmapFactory.decodeFile(filePathString) | |
} | |
} | |
} | |
object CustomGlanceStateDefinition : GlanceStateDefinition<Preferences> { | |
private const val fileName = "widget_preference" | |
override suspend fun getDataStore(context: Context, fileKey: String): DataStore<Preferences> { | |
return context.dataStore | |
} | |
override fun getLocation(context: Context, fileKey: String): File { | |
return File(context.applicationContext.filesDir, "datastore/$fileName") | |
} | |
private val Context.dataStore: DataStore<Preferences> | |
by preferencesDataStore(name = fileName) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment