Skip to content

Instantly share code, notes, and snippets.

View tdcolvin's full-sized avatar

Tom Colvin tdcolvin

  • Basingstoke, UK
  • 19:06 (UTC +01:00)
View GitHub Profile
Button(
onClick = {
//On button press, launch the photo picker
launcher.launch(PickVisualMediaRequest(
//Here we request only photos. Change this to .ImageAndVideo if
//you want videos too.
//Or use .VideoOnly if you only want videos.
mediaType = ActivityResultContracts.PickVisualMedia.ImageOnly
))
}
//The URI of the photo that the user has picked
var photoUri: Uri? by remember { mutableStateOf(null) }
//The launcher we will use for the PickVisualMedia contract.
//When .launch()ed, this will display the photo picker.
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
//When the user has selected a photo, its URL is returned here
photoUri = uri
}
if (photoUri != null) {
//Use Coil to display the selected image
val painter = rememberAsyncImagePainter(
ImageRequest
.Builder(LocalContext.current)
.data(data = photoUri)
.build()
)
Image(
//To allow the user to pick multiple files, use PickMultipleVisualMedia()
//in place of PickVisualMedia() below.
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
//When the user has selected a photo, its URI is returned here
}
private val mainKeyAlias by lazy {
// Although you can define your own key generation parameter specification, it's
// recommended that you use the value specified here.
val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
MasterKeys.getOrCreate(keyGenParameterSpec)
}
private val sharedPreferences by lazy {
//The name of the file on disk will be this, plus the ".xml" extension.
val sharedPrefsFile = "sharedPrefs"
//Create the EncryptedSharedPremises using the key above
EncryptedSharedPreferences.create(
sharedPrefsFile,
mainKeyAlias,
getApplication(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
fun writeToSharedPrefs(value: String) {
with (sharedPreferences.edit()) {
putString("test", value)
apply()
}
}
fun readFromSharedPrefs(): String? {
return sharedPreferences.getString("test", "")
}
private val encryptedFile by lazy {
//This is the app's internal storage folder
val baseDir = getApplication<Application>().filesDir
//The encrypted file within the app's internal storage folder
val fileToWrite = File(baseDir, "encrypted-file.txt")
//Create the encrypted file
EncryptedFile.Builder(
fileToWrite,
fun writeToEncryptedFile(content: String) {
//Open the file for writing, and write our contents to it.
//Note how Kotlin's 'use' function correctly closes the resource after we've finished,
//regardless of whether or not an exception was thrown.
encryptedFile.openFileOutput().use {
it.write(content.toByteArray(StandardCharsets.UTF_8))
it.flush()
}
}