Skip to content

Instantly share code, notes, and snippets.

@williaanlopes
Last active September 24, 2022 05:12
Show Gist options
  • Save williaanlopes/cdd60fd0bbb977af12c86072753a96cb to your computer and use it in GitHub Desktop.
Save williaanlopes/cdd60fd0bbb977af12c86072753a96cb to your computer and use it in GitHub Desktop.
New Android registerForActivityResult camera photo
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" tools:remove="android:maxSdkVersion"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme"
android:requestLegacyExternalStorage="true"
tools:targetApi="n">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<!-- provider_paths -->
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
<!-- provider_paths -->
private var latestTmpUri: Uri? = null
// call camera
getTmpFileUri().let { uri ->
latestTmpUri = uri
takeImageResult.launch(uri)
}
private val takeImageResult =
registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
if (isSuccess) {
latestTmpUri?.let { uri ->
requireContext().contentResolver.openInputStream(uri).let { inputStream ->
val bitmap = BitmapFactory.decodeStream(inputStream)
}
}
}
}
private fun getTmpFileUri(): Uri {
val imageFileName = "${System.currentTimeMillis()}"
val tmpFile =
File.createTempFile(imageFileName, ".jpeg", requireActivity().cacheDir).apply {
createNewFile()
deleteOnExit()
}
return FileProvider.getUriForFile(
requireContext(),
"${BuildConfig.APPLICATION_ID}.fileprovider",
tmpFile
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment