Skip to content

Instantly share code, notes, and snippets.

@molidev8
Created June 9, 2022 14:18
Show Gist options
  • Save molidev8/13b243ccbb2d6528afc0d5b1dcfcb4c7 to your computer and use it in GitHub Desktop.
Save molidev8/13b243ccbb2d6528afc0d5b1dcfcb4c7 to your computer and use it in GitHub Desktop.
A callback to receive information with Android Nearby
private inner class DataReceivedCallback : PayloadCallback() {
private val incomingFilePayloads = SimpleArrayMap<Long, Payload>()
private val completedFilePayloads = SimpleArrayMap<Long, Payload>()
private var filePayloadFilename: String = ""
override fun onPayloadReceived(endPointId: String, payload: Payload) {
when (payload.type) {
Payload.Type.BYTES -> {
val gson = Gson()
val recipe =
gson.fromJson(String(payload.asBytes()!!), RecipeWithIng::class.java)
filePayloadFilename = recipe.domainRecipe.image
viewModel.setRecipeReceivedWithNearby(recipe)
Log.d(GENERAL, recipe.toString())
}
Payload.Type.FILE -> {
incomingFilePayloads.put(payload.id, payload)
}
}
}
override fun onPayloadTransferUpdate(endPointId: String, update: PayloadTransferUpdate) {
if (update.status == PayloadTransferUpdate.Status.SUCCESS) {
val payload = incomingFilePayloads.remove(update.payloadId)
completedFilePayloads.put(update.payloadId, payload)
if (payload?.type == Payload.Type.FILE) {
val filePayload = completedFilePayloads[update.payloadId]
if (filePayload != null && filePayloadFilename != "") {
completedFilePayloads.remove(update.payloadId)
// Get the received file (which will be in the Downloads folder)
// Because of https://developer.android.com/preview/privacy/scoped-storage, we are not
// allowed to access filepaths from another process directly. Instead, we must open the
// uri using our ContentResolver.
val uri = filePayload.asFile()!!.asUri()
try {
// Copy the file to a new location.
val input: InputStream? = context.contentResolver.openInputStream(uri!!)
if (input != null) {
val storageDir: File? =
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val file = File(storageDir, filePayloadFilename.split("/").last())
copyStream(input, FileOutputStream(file))
viewModel.updateWithRecipeReceivedWithNearby()
}
} catch (e: IOException) {
Log.d(GENERAL, "error al guardar el fichero", e)
} finally {
// Delete the original file.
context.contentResolver.delete(uri!!, null, null)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment