Shrink apk size : remove dep to mlkit
This commit is contained in:
parent
c0b9b60bb1
commit
ffc525fe27
2 changed files with 382 additions and 179 deletions
|
|
@ -1,9 +1,163 @@
|
||||||
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
|
|
||||||
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
|
||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
|
||||||
import java.io.ByteArrayOutputStream
|
import java.io.ByteArrayOutputStream
|
||||||
import java.util.Properties
|
|
||||||
import java.io.FileInputStream
|
import java.io.FileInputStream
|
||||||
|
import java.util.Properties
|
||||||
|
import javax.inject.Inject
|
||||||
|
import org.gradle.api.DefaultTask
|
||||||
|
import org.gradle.api.file.RegularFileProperty
|
||||||
|
import org.gradle.api.provider.Property
|
||||||
|
import org.gradle.api.tasks.Input
|
||||||
|
import org.gradle.api.tasks.InputFile
|
||||||
|
import org.gradle.api.tasks.Optional
|
||||||
|
import org.gradle.api.tasks.OutputFile
|
||||||
|
import org.gradle.api.tasks.TaskAction
|
||||||
|
import org.gradle.process.ExecOperations
|
||||||
|
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
|
||||||
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
||||||
|
|
||||||
|
abstract class FinalizeApkTask @Inject constructor(
|
||||||
|
private val execOperations: ExecOperations
|
||||||
|
) : DefaultTask() {
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
abstract val alignmentTool: Property<String>
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
abstract val apksignerTool: Property<String>
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
abstract val adbTool: Property<String>
|
||||||
|
|
||||||
|
@get:InputFile
|
||||||
|
abstract val inputApk: RegularFileProperty
|
||||||
|
|
||||||
|
@get:OutputFile
|
||||||
|
abstract val alignedApk: RegularFileProperty
|
||||||
|
|
||||||
|
@get:OutputFile
|
||||||
|
abstract val finalApk: RegularFileProperty
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
@get:Optional
|
||||||
|
abstract val storeFilePath: Property<String>
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
@get:Optional
|
||||||
|
abstract val storePassword: Property<String>
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
@get:Optional
|
||||||
|
abstract val keyAlias: Property<String>
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
@get:Optional
|
||||||
|
abstract val keyPassword: Property<String>
|
||||||
|
|
||||||
|
@TaskAction
|
||||||
|
fun run() {
|
||||||
|
println("=== Début de la finalisation de l'APK (Alignement & Signature) ===")
|
||||||
|
|
||||||
|
val input = inputApk.get().asFile
|
||||||
|
val aligned = alignedApk.get().asFile
|
||||||
|
val signed = finalApk.get().asFile
|
||||||
|
|
||||||
|
if (!input.exists()) {
|
||||||
|
println("Erreur : L'APK non signé est introuvable à l'emplacement : ${input.absolutePath}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Étape 1 : Zipalign
|
||||||
|
println("1. Exécution de zipalign...")
|
||||||
|
val alignResult = execOperations.exec {
|
||||||
|
commandLine(alignmentTool.get(), "-f", "4", input.absolutePath, aligned.absolutePath)
|
||||||
|
isIgnoreExitValue = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (alignResult.exitValue != 0) {
|
||||||
|
println("Erreur lors de l'alignement zipalign (code ${alignResult.exitValue}).")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
println("-> Zipalign réussi.")
|
||||||
|
|
||||||
|
// Étape 2 : Signature
|
||||||
|
println("2. Signature de l'APK...")
|
||||||
|
val signResult = execOperations.exec {
|
||||||
|
commandLine(
|
||||||
|
apksignerTool.get(), "sign",
|
||||||
|
"--ks", storeFilePath.orElse("").get(),
|
||||||
|
"--ks-pass", "pass:${storePassword.orElse("").get()}",
|
||||||
|
"--key-pass", "pass:${keyPassword.orElse("").get()}",
|
||||||
|
"--ks-key-alias", keyAlias.orElse("").get(),
|
||||||
|
"--out", signed.absolutePath,
|
||||||
|
aligned.absolutePath
|
||||||
|
)
|
||||||
|
isIgnoreExitValue = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (signResult.exitValue != 0) {
|
||||||
|
println("Erreur lors de la signature de l'APK (code ${signResult.exitValue}).")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
println("-> APK signé avec succès : ${signed.absolutePath}")
|
||||||
|
|
||||||
|
// Étape 3 : Vérification et installation via ADB
|
||||||
|
println("3. Vérification des appareils connectés...")
|
||||||
|
val stdout = ByteArrayOutputStream()
|
||||||
|
val devicesResult = execOperations.exec {
|
||||||
|
commandLine(adbTool.get(), "devices")
|
||||||
|
standardOutput = stdout
|
||||||
|
isIgnoreExitValue = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (devicesResult.exitValue != 0) {
|
||||||
|
println("Avertissement : Impossible d'interroger adb devices (code ${devicesResult.exitValue}).")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val connectedDevices = stdout.toString()
|
||||||
|
.lines()
|
||||||
|
.drop(1)
|
||||||
|
.filter { it.isNotBlank() && it.contains("device") && !it.contains("offline") }
|
||||||
|
|
||||||
|
if (connectedDevices.isNotEmpty()) {
|
||||||
|
println("-> Appareil(s) détecté(s). Installation de l'APK en cours...")
|
||||||
|
val installResult = execOperations.exec {
|
||||||
|
commandLine(adbTool.get(), "install", "-r", signed.absolutePath)
|
||||||
|
isIgnoreExitValue = true
|
||||||
|
}
|
||||||
|
if (installResult.exitValue == 0) {
|
||||||
|
println("-> Application installée avec succès sur le téléphone !")
|
||||||
|
} else {
|
||||||
|
println("Avertissement : Échec de l'installation via adb (code ${installResult.exitValue}).")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println("-> Aucun appareil connecté. Installation ignorée.")
|
||||||
|
}
|
||||||
|
println("=== Processus terminé ===")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register<FinalizeApkTask>("finalizeApk") {
|
||||||
|
dependsOn("assembleRelease")
|
||||||
|
|
||||||
|
val apkReleaseDir = layout.buildDirectory.dir("outputs/apk/release")
|
||||||
|
val buildToolsVersion = android.buildToolsVersion
|
||||||
|
val sdkDir = android.sdkDirectory
|
||||||
|
val releaseSigning = android.signingConfigs.getByName("release")
|
||||||
|
|
||||||
|
alignmentTool.set(sdkDir.resolve("build-tools/$buildToolsVersion/zipalign").absolutePath)
|
||||||
|
apksignerTool.set(sdkDir.resolve("build-tools/$buildToolsVersion/apksigner").absolutePath)
|
||||||
|
adbTool.set(sdkDir.resolve("platform-tools/adb").absolutePath)
|
||||||
|
|
||||||
|
inputApk.set(apkReleaseDir.map { it.file("composeApp-release.apk") })
|
||||||
|
alignedApk.set(apkReleaseDir.map { it.file("app-release-aligned.apk") })
|
||||||
|
finalApk.set(apkReleaseDir.map { it.file("app-release-signed.apk") })
|
||||||
|
|
||||||
|
storeFilePath.set(releaseSigning.storeFile?.absolutePath ?: "")
|
||||||
|
storePassword.set(releaseSigning.storePassword ?: "")
|
||||||
|
keyAlias.set(releaseSigning.keyAlias ?: "")
|
||||||
|
keyPassword.set(releaseSigning.keyPassword ?: "")
|
||||||
|
}
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.kotlinMultiplatform)
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
|
|
@ -64,7 +218,6 @@ kotlin {
|
||||||
implementation("androidx.camera:camera-camera2:1.3.4")
|
implementation("androidx.camera:camera-camera2:1.3.4")
|
||||||
implementation("androidx.camera:camera-lifecycle:1.3.4")
|
implementation("androidx.camera:camera-lifecycle:1.3.4")
|
||||||
implementation("androidx.camera:camera-view:1.3.4")
|
implementation("androidx.camera:camera-view:1.3.4")
|
||||||
implementation("com.google.mlkit:barcode-scanning:17.3.0")
|
|
||||||
}
|
}
|
||||||
commonMain.dependencies {
|
commonMain.dependencies {
|
||||||
// implementation(compose.components.resources)
|
// implementation(compose.components.resources)
|
||||||
|
|
@ -155,8 +308,8 @@ val localProperties = Properties().apply {
|
||||||
buildTypes {
|
buildTypes {
|
||||||
getByName("release") {
|
getByName("release") {
|
||||||
val enableR8 = project.hasProperty("enableR8") && project.property("enableR8") == "true"
|
val enableR8 = project.hasProperty("enableR8") && project.property("enableR8") == "true"
|
||||||
isMinifyEnabled = true
|
isMinifyEnabled = enableR8
|
||||||
isShrinkResources = true
|
isShrinkResources = enableR8
|
||||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||||
signingConfig = signingConfigs.getByName("release")
|
signingConfig = signingConfigs.getByName("release")
|
||||||
}
|
}
|
||||||
|
|
@ -263,97 +416,7 @@ tasks.configureEach {
|
||||||
dependsOn(generateFilesIndex)
|
dependsOn(generateFilesIndex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tasks.register("finalizeApk") {
|
|
||||||
dependsOn("assembleRelease")
|
|
||||||
|
|
||||||
val apkUnsignedDir = layout.buildDirectory.dir("outputs/apk/release").get().asFile
|
|
||||||
val buildToolsVersion = android.buildToolsVersion
|
|
||||||
val sdkDir = android.sdkDirectory
|
|
||||||
|
|
||||||
val alignmentTool = sdkDir.resolve("build-tools/$buildToolsVersion/zipalign").absolutePath
|
|
||||||
val apksignerTool = sdkDir.resolve("build-tools/$buildToolsVersion/apksigner").absolutePath
|
|
||||||
val adbTool = sdkDir.resolve("platform-tools/adb").absolutePath
|
|
||||||
|
|
||||||
val inputApk = File(apkUnsignedDir, "composeApp-release.apk")
|
|
||||||
val alignedApk = File(apkUnsignedDir, "app-release-aligned.apk")
|
|
||||||
val finalApk = File(apkUnsignedDir, "app-release-signed.apk")
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
println("=== Début de la finalisation de l'APK (Alignement & Signature) ===")
|
|
||||||
|
|
||||||
if (!inputApk.exists()) {
|
|
||||||
println("Erreur : L'APK non signé est introuvable à l'emplacement : ${inputApk.absolutePath}")
|
|
||||||
return@doLast
|
|
||||||
}
|
|
||||||
|
|
||||||
// Étape 1 : Zipalign
|
|
||||||
println("1. Exécution de zipalign...")
|
|
||||||
val alignResult = exec {
|
|
||||||
commandLine(alignmentTool, "-f", "4", inputApk.absolutePath, alignedApk.absolutePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (alignResult.exitValue != 0) {
|
|
||||||
println("Erreur lors de l'alignement zipalign.")
|
|
||||||
return@doLast
|
|
||||||
}
|
|
||||||
println("-> Zipalign réussi.")
|
|
||||||
|
|
||||||
// Étape 2 : Signature
|
|
||||||
println("2. Signature de l'APK...")
|
|
||||||
val releaseConfig = android.signingConfigs.getByName("release")
|
|
||||||
val storeFile = releaseConfig.storeFile?.absolutePath ?: ""
|
|
||||||
val storePassword = releaseConfig.storePassword ?: ""
|
|
||||||
val keyAlias = releaseConfig.keyAlias ?: ""
|
|
||||||
val keyPassword = releaseConfig.keyPassword ?: ""
|
|
||||||
|
|
||||||
val signResult = exec {
|
|
||||||
commandLine(
|
|
||||||
apksignerTool, "sign",
|
|
||||||
"--ks", storeFile,
|
|
||||||
"--ks-pass", "pass:$storePassword",
|
|
||||||
"--key-pass", "pass:$keyPassword",
|
|
||||||
"--ks-key-alias", keyAlias,
|
|
||||||
"--out", finalApk.absolutePath,
|
|
||||||
alignedApk.absolutePath
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (signResult.exitValue != 0) {
|
|
||||||
println("Erreur lors de la signature de l'APK.")
|
|
||||||
return@doLast
|
|
||||||
}
|
|
||||||
println("-> APK signé avec succès : ${finalApk.absolutePath}")
|
|
||||||
|
|
||||||
// Étape 3 : Vérification et installation via ADB
|
|
||||||
println("3. Vérification des appareils connectés...")
|
|
||||||
val stdout = ByteArrayOutputStream()
|
|
||||||
exec {
|
|
||||||
commandLine(adbTool, "devices")
|
|
||||||
standardOutput = stdout
|
|
||||||
}
|
|
||||||
|
|
||||||
val deviceOutput = stdout.toString()
|
|
||||||
// Analyse des lignes de la sortie 'adb devices' (on ignore l'en-tête et les lignes vides)
|
|
||||||
val connectedDevices = deviceOutput.lines()
|
|
||||||
.drop(1)
|
|
||||||
.filter { it.isNotBlank() && it.contains("device") && !it.contains("offline") }
|
|
||||||
|
|
||||||
if (connectedDevices.isNotEmpty()) {
|
|
||||||
println("-> Appareil(s) détecté(s). Installation de l'APK en cours...")
|
|
||||||
val installResult = exec {
|
|
||||||
commandLine(adbTool, "install", "-r", finalApk.absolutePath)
|
|
||||||
}
|
|
||||||
if (installResult.exitValue == 0) {
|
|
||||||
println("-> Application installée avec succès sur le téléphone !")
|
|
||||||
} else {
|
|
||||||
println("Avertissement : Échec de l'installation via adb.")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
println("-> Aucun appareil connecté. Installation ignorée.")
|
|
||||||
}
|
|
||||||
println("=== Processus terminé ===")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tasks.register<Copy>("exportLibs") {
|
tasks.register<Copy>("exportLibs") {
|
||||||
group = "distribution"
|
group = "distribution"
|
||||||
description = "Copie les bibliothèques partagées pour le Thin JAR"
|
description = "Copie les bibliothèques partagées pour le Thin JAR"
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,11 @@
|
||||||
package mg.dot.feufaro.ui
|
package mg.dot.feufaro.ui
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
|
import android.graphics.Bitmap
|
||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.ImageFormat
|
||||||
|
import android.Manifest
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
|
@ -12,37 +14,46 @@ import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.camera.core.*
|
import androidx.camera.core.*
|
||||||
|
import androidx.camera.core.ImageAnalysis
|
||||||
|
import androidx.camera.core.ImageProxy
|
||||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||||
import androidx.camera.view.PreviewView
|
import androidx.camera.view.PreviewView
|
||||||
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.Canvas
|
import androidx.compose.foundation.Canvas
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.material.icons.filled.Close
|
import androidx.compose.material.icons.filled.Close
|
||||||
import androidx.compose.material.icons.filled.Image
|
import androidx.compose.material.icons.filled.Image
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.nativeCanvas
|
import androidx.compose.ui.graphics.nativeCanvas
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.compose.ui.viewinterop.AndroidView
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
|
import com.google.zxing.BarcodeFormat
|
||||||
import com.google.mlkit.vision.barcode.BarcodeScanning
|
import com.google.zxing.BinaryBitmap
|
||||||
import com.google.mlkit.vision.barcode.common.Barcode
|
import com.google.zxing.ChecksumException
|
||||||
import com.google.mlkit.vision.common.InputImage
|
import com.google.zxing.common.HybridBinarizer
|
||||||
import feufaro.composeapp.generated.resources.Res
|
import com.google.zxing.DecodeHintType
|
||||||
|
import com.google.zxing.FormatException
|
||||||
|
import com.google.zxing.MultiFormatReader
|
||||||
|
import com.google.zxing.NotFoundException
|
||||||
|
import com.google.zxing.PlanarYUVLuminanceSource
|
||||||
|
import com.google.zxing.qrcode.QRCodeReader
|
||||||
|
import com.google.zxing.RGBLuminanceSource
|
||||||
import feufaro.composeapp.generated.resources.icon
|
import feufaro.composeapp.generated.resources.icon
|
||||||
import org.jetbrains.compose.resources.painterResource
|
import feufaro.composeapp.generated.resources.Res
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
|
import org.jetbrains.compose.resources.painterResource
|
||||||
|
|
||||||
class QRScannerActivity : ComponentActivity() {
|
class QRScannerActivity : ComponentActivity() {
|
||||||
|
|
||||||
|
|
@ -52,47 +63,77 @@ class QRScannerActivity : ComponentActivity() {
|
||||||
|
|
||||||
private val cameraExecutor = Executors.newSingleThreadExecutor()
|
private val cameraExecutor = Executors.newSingleThreadExecutor()
|
||||||
private val mainHandler = Handler(Looper.getMainLooper())
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
private val scanner = BarcodeScanning.getClient(
|
|
||||||
BarcodeScannerOptions.Builder()
|
|
||||||
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
|
|
||||||
.enableAllPotentialBarcodes()
|
|
||||||
.build()
|
|
||||||
)
|
|
||||||
|
|
||||||
private val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
private val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||||
uri?.let {
|
if (uri == null) return@registerForActivityResult
|
||||||
|
|
||||||
|
cameraExecutor.execute {
|
||||||
|
var bitmap: Bitmap? = null
|
||||||
try {
|
try {
|
||||||
val inputStream = contentResolver.openInputStream(uri)
|
bitmap = contentResolver.openInputStream(uri)?.use { inputStream ->
|
||||||
val bitmap = BitmapFactory.decodeStream(inputStream)
|
BitmapFactory.decodeStream(inputStream)
|
||||||
if (bitmap != null) {
|
}
|
||||||
val image = InputImage.fromBitmap(bitmap, 0)
|
|
||||||
scanner.process(image)
|
if (bitmap == null) {
|
||||||
.addOnSuccessListener { barcodes ->
|
mainHandler.post {
|
||||||
for (barcode in barcodes) {
|
Toast.makeText(this, "Erreur lors de la lecture de l'image", Toast.LENGTH_SHORT).show()
|
||||||
val rawValue = barcode.rawValue ?: barcode.rawBytes?.let { String(it, Charsets.UTF_8) }
|
}
|
||||||
if (!rawValue.isNullOrBlank()) {
|
return@execute
|
||||||
mainHandler.post {
|
}
|
||||||
println("QR Code décodé depuis la galerie : $rawValue")
|
|
||||||
Toast.makeText(this, "QR Code détecté depuis la galerie !", Toast.LENGTH_SHORT).show()
|
val decodedText = decodeQrCodeFromBitmap(bitmap)
|
||||||
pendingResultCallback?.invoke(rawValue)
|
|
||||||
pendingResultCallback = null
|
mainHandler.post {
|
||||||
finish()
|
if (!decodedText.isNullOrBlank()) {
|
||||||
}
|
println("QR Code décodé depuis la galerie : $decodedText")
|
||||||
return@addOnSuccessListener
|
Toast.makeText(this, "QR Code détecté depuis la galerie !", Toast.LENGTH_SHORT).show()
|
||||||
}
|
pendingResultCallback?.invoke(decodedText)
|
||||||
}
|
pendingResultCallback = null
|
||||||
Toast.makeText(this, "Aucun QR code valide trouvé dans l'image", Toast.LENGTH_SHORT).show()
|
finish()
|
||||||
}
|
} else {
|
||||||
.addOnFailureListener {
|
Toast.makeText(this, "Aucun QR code valide trouvé dans l'image", Toast.LENGTH_SHORT).show()
|
||||||
Toast.makeText(this, "Erreur lors de la lecture de l'image", Toast.LENGTH_SHORT).show()
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
|
mainHandler.post {
|
||||||
|
Toast.makeText(this, "Erreur lors de la lecture de l'image", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
bitmap?.recycle()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun decodeQrCodeFromBitmap(bitmap: Bitmap): String? {
|
||||||
|
val width = bitmap.width
|
||||||
|
val height = bitmap.height
|
||||||
|
if (width <= 0 || height <= 0) return null
|
||||||
|
|
||||||
|
val pixels = IntArray(width * height)
|
||||||
|
bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
|
||||||
|
|
||||||
|
val source = RGBLuminanceSource(width, height, pixels)
|
||||||
|
val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
|
||||||
|
val reader = QRCodeReader()
|
||||||
|
val hints = mapOf(
|
||||||
|
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
|
||||||
|
DecodeHintType.TRY_HARDER to true
|
||||||
|
)
|
||||||
|
|
||||||
|
return try {
|
||||||
|
reader.decode(binaryBitmap, hints).text
|
||||||
|
} catch (_: NotFoundException) {
|
||||||
|
null
|
||||||
|
} catch (_: ChecksumException) {
|
||||||
|
null
|
||||||
|
} catch (_: FormatException) {
|
||||||
|
null
|
||||||
|
} finally {
|
||||||
|
reader.reset()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private val requestPermissionLauncher = registerForActivityResult(
|
private val requestPermissionLauncher = registerForActivityResult(
|
||||||
ActivityResultContracts.RequestPermission()
|
ActivityResultContracts.RequestPermission()
|
||||||
) { isGranted ->
|
) { isGranted ->
|
||||||
|
|
@ -210,7 +251,7 @@ class QRScannerActivity : ComponentActivity() {
|
||||||
containerColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.15f),
|
containerColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.15f),
|
||||||
contentColor = MaterialTheme.colorScheme.onPrimary
|
contentColor = MaterialTheme.colorScheme.onPrimary
|
||||||
),
|
),
|
||||||
border = ButtonDefaults.outlinedButtonBorder.copy(width = 0.dp),
|
border = ButtonDefaults.outlinedButtonBorder(enabled = true).copy(width = 0.dp),
|
||||||
shape = RoundedCornerShape(24.dp),
|
shape = RoundedCornerShape(24.dp),
|
||||||
modifier = Modifier.height(48.dp)
|
modifier = Modifier.height(48.dp)
|
||||||
) {
|
) {
|
||||||
|
|
@ -250,26 +291,33 @@ class QRScannerActivity : ComponentActivity() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startCamera(previewView: PreviewView, onScan: (String) -> Unit) {
|
private fun startCamera(previewView: PreviewView, onScan: (String) -> Unit) {
|
||||||
|
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (cameraExecutor.isShutdown) return
|
||||||
|
|
||||||
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
|
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
|
||||||
|
|
||||||
cameraProviderFuture.addListener({
|
cameraProviderFuture.addListener({
|
||||||
val cameraProvider = cameraProviderFuture.get()
|
if (isFinishing || isDestroyed || cameraExecutor.isShutdown) return@addListener
|
||||||
val preview = Preview.Builder().build().also {
|
|
||||||
it.setSurfaceProvider(previewView.surfaceProvider)
|
|
||||||
}
|
|
||||||
|
|
||||||
val imageAnalyzer = ImageAnalysis.Builder()
|
|
||||||
.setTargetResolution(android.util.Size(1280, 720))
|
|
||||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
|
||||||
.build()
|
|
||||||
.also {
|
|
||||||
it.setAnalyzer(cameraExecutor, MLKitBarcodeAnalyzer(scanner) { qrResult ->
|
|
||||||
onScan(qrResult)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
val cameraProvider = cameraProviderFuture.get()
|
||||||
|
val preview = Preview.Builder().build().also {
|
||||||
|
it.setSurfaceProvider(previewView.surfaceProvider)
|
||||||
|
}
|
||||||
|
|
||||||
|
val imageAnalyzer = ImageAnalysis.Builder()
|
||||||
|
.setTargetResolution(android.util.Size(1280, 720))
|
||||||
|
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||||
|
.build()
|
||||||
|
.also { analyzerUseCase ->
|
||||||
|
analyzerUseCase.setAnalyzer(cameraExecutor, ZxingBarcodeAnalyzer { qrResult ->
|
||||||
|
onScan(qrResult)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
cameraProvider.unbindAll()
|
cameraProvider.unbindAll()
|
||||||
cameraProvider.bindToLifecycle(
|
cameraProvider.bindToLifecycle(
|
||||||
this,
|
this,
|
||||||
|
|
@ -289,37 +337,129 @@ class QRScannerActivity : ComponentActivity() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class MLKitBarcodeAnalyzer(
|
class ZxingBarcodeAnalyzer(
|
||||||
private val scanner: com.google.mlkit.vision.barcode.BarcodeScanner,
|
|
||||||
private val onQrCodeDetected: (String) -> Unit
|
private val onQrCodeDetected: (String) -> Unit
|
||||||
) : ImageAnalysis.Analyzer {
|
) : ImageAnalysis.Analyzer {
|
||||||
private var isScanning = false
|
|
||||||
|
|
||||||
@SuppressLint("UnsafeOptInUsageError")
|
private val reader = QRCodeReader()
|
||||||
|
private val hints = mapOf(
|
||||||
|
DecodeHintType.POSSIBLE_FORMATS to listOf(com.google.zxing.BarcodeFormat.QR_CODE),
|
||||||
|
DecodeHintType.TRY_HARDER to true
|
||||||
|
)
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var isHandled = false
|
||||||
|
|
||||||
override fun analyze(imageProxy: ImageProxy) {
|
override fun analyze(imageProxy: ImageProxy) {
|
||||||
val mediaImage = imageProxy.image
|
try {
|
||||||
if (mediaImage != null && !isScanning) {
|
if (isHandled) return
|
||||||
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
|
if (imageProxy.format != ImageFormat.YUV_420_888) return
|
||||||
isScanning = true
|
|
||||||
scanner.process(image)
|
val yPlane = imageProxy.planes[0]
|
||||||
.addOnSuccessListener { barcodes ->
|
val srcWidth = imageProxy.width
|
||||||
for (barcode in barcodes) {
|
val srcHeight = imageProxy.height
|
||||||
val rawValue = barcode.rawValue ?: barcode.rawBytes?.let { String(it, Charsets.UTF_8) }
|
val rowStride = yPlane.rowStride
|
||||||
if (!rawValue.isNullOrBlank()) {
|
val pixelStride = yPlane.pixelStride
|
||||||
onQrCodeDetected(rawValue)
|
val buffer = yPlane.buffer
|
||||||
return@addOnSuccessListener
|
|
||||||
|
// Extraction propre du plan Y en tenant compte de rowStride et pixelStride
|
||||||
|
val rawY = ByteArray(srcWidth * srcHeight)
|
||||||
|
val rowData = ByteArray(rowStride)
|
||||||
|
var outIdx = 0
|
||||||
|
|
||||||
|
for (row in 0 until srcHeight) {
|
||||||
|
val rowStart = row * rowStride
|
||||||
|
if (rowStart + rowStride > buffer.capacity()) return
|
||||||
|
buffer.position(rowStart)
|
||||||
|
val bytesToRead = minOf(rowStride, buffer.remaining())
|
||||||
|
buffer.get(rowData, 0, bytesToRead)
|
||||||
|
|
||||||
|
if (pixelStride == 1) {
|
||||||
|
System.arraycopy(rowData, 0, rawY, outIdx, srcWidth)
|
||||||
|
outIdx += srcWidth
|
||||||
|
} else {
|
||||||
|
for (col in 0 until srcWidth) {
|
||||||
|
val idx = col * pixelStride
|
||||||
|
if (idx < bytesToRead) {
|
||||||
|
rawY[outIdx++] = rowData[idx]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.addOnFailureListener {
|
}
|
||||||
|
|
||||||
}
|
val rotation = imageProxy.imageInfo.rotationDegrees
|
||||||
.addOnCompleteListener {
|
val (orientedY, outW, outH) = rotateYuv90Multiple(rawY, srcWidth, srcHeight, rotation)
|
||||||
imageProxy.close()
|
|
||||||
isScanning = false
|
val source = PlanarYUVLuminanceSource(
|
||||||
}
|
orientedY,
|
||||||
} else {
|
outW,
|
||||||
|
outH,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
outW,
|
||||||
|
outH,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
val bitmap = BinaryBitmap(HybridBinarizer(source))
|
||||||
|
|
||||||
|
val text = try {
|
||||||
|
reader.decode(bitmap, hints).text
|
||||||
|
} catch (_: NotFoundException) {
|
||||||
|
null
|
||||||
|
} catch (_: ChecksumException) {
|
||||||
|
null
|
||||||
|
} catch (_: FormatException) {
|
||||||
|
null
|
||||||
|
} finally {
|
||||||
|
reader.reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!text.isNullOrBlank()) {
|
||||||
|
isHandled = true
|
||||||
|
onQrCodeDetected(text)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
imageProxy.close()
|
imageProxy.close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private fun rotateYuv90Multiple(
|
||||||
|
data: ByteArray,
|
||||||
|
width: Int,
|
||||||
|
height: Int,
|
||||||
|
rotationDegrees: Int
|
||||||
|
): Triple<ByteArray, Int, Int> {
|
||||||
|
return when ((rotationDegrees % 360 + 360) % 360) {
|
||||||
|
90 -> {
|
||||||
|
val rotated = ByteArray(width * height)
|
||||||
|
for (y in 0 until height) {
|
||||||
|
for (x in 0 until width) {
|
||||||
|
val newX = height - 1 - y
|
||||||
|
val newY = x
|
||||||
|
rotated[newY * height + newX] = data[y * width + x]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Triple(rotated, height, width)
|
||||||
|
}
|
||||||
|
180 -> {
|
||||||
|
val rotated = ByteArray(width * height)
|
||||||
|
for (i in data.indices) {
|
||||||
|
rotated[data.size - 1 - i] = data[i]
|
||||||
|
}
|
||||||
|
Triple(rotated, width, height)
|
||||||
|
}
|
||||||
|
270 -> {
|
||||||
|
val rotated = ByteArray(width * height)
|
||||||
|
for (y in 0 until height) {
|
||||||
|
for (x in 0 until width) {
|
||||||
|
val newX = y
|
||||||
|
val newY = width - 1 - x
|
||||||
|
rotated[newY * height + newX] = data[y * width + x]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Triple(rotated, height, width)
|
||||||
|
}
|
||||||
|
else -> Triple(data, width, height)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue