How to write a file in android shared internal/external storage? - android

I am currently working with one of my app updates and I am looking for a way to save some files at the root of shared internal storage.
Don't confuse with the word shared here. I just meant here with the phone's internal/external storage which holds a large amount of data.
Now coming to the main point, I have an app that uses the FFmpeg library for android and it records the live streams and saves it into the phone's storage.
Now here's the problem I don't want to save this file in my app package folder.
e.g: /storage/emulated/0/Android/data/com.app.package/files/...
I want to save this video file in the root of the storage folder where I can create a special folder for my app just like WhatsApp then save all required data in it only.
e.g: /storage/emulated/0/MyApp/...
To be more concise I want my app just like WhatsApp which has a separate folder in internal storage for storing its app-related data.
Now, so far I tried these.
getExternalFilesDir(null)?.absolutePath -> /storage/emulated/0/Android/data/com.app.package/files
getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath -> /storage/emulated/0/Android/data/com.app.package/files/Download
externalCacheDir?.absolutePath -> /storage/emulated/0/Android/data/com.app.package/cache
filesDir?.absolutePath -> /data/user/0/com.app.package/files
Environment.getRootDirectory().absolutePath -> /system
Environment.getExternalStorageDirectory().absolutePath -> /storage/emulated/0
Environment.getExternalStoragePublicDirectory("").absolutePath -> /storage/emulated/0
Now these to methods can work for me but they are deprecated getExternalStorageDirectory() & getExternalStoragePublicDirectory()
Just keep in mind my solution is related to the WhatsApp storage folder.
I searched a lot but not so much help as I don't want to go with just a copy-paste and hack solutions. I want to do it in a clean way.
I am trying to open a File Picker via intent for this I have set permission
....
....
and for intent.
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.type = "*/*"
intent.flags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
startActivityForResult(Intent.createChooser(intent, "Select .... file"), RC)
Now here on Android 10, a file picker is not opening and this works perfectly if I add the requestLegacyExternalStorage flag in the manifest.
Or
if I set android:maxSdkVersion="29" also worked but here google wants to use Some SAF or Media Store API but I don't get it I just want to pick a file just a simple txt nothing else.

You can save video file to external storage using this:
#RequiresApi(api = Build.VERSION_CODES.Q)
#Throws(FileNotFoundException::class)
fun addToApiAbove29Gallery(
context: Context,
file: File?,
fileName: String?,
destinationPath: String?,
action: () -> Unit
) {
val valuesvideos: ContentValues
valuesvideos = ContentValues()
valuesvideos.put(
MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM
+ File.separator + context.resources.getString(R.string.app_name)
+ File.separator + File(destinationPath).name
)
valuesvideos.put(MediaStore.Video.Media.TITLE, "${fileName}.mp4")
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, "${fileName}.mp4")
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis())
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 1)
val resolver = context.contentResolver
val collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val uriSavedVideo = resolver.insert(collection, valuesvideos)
val pfd = context.contentResolver.openFileDescriptor(uriSavedVideo!!, "w")
val executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
val handler = Handler(Looper.getMainLooper())
executor.execute {
if (pfd != null) {
try {
val out =
FileOutputStream(pfd.fileDescriptor)
val inputStream = FileInputStream(file)
val buf = ByteArray(8192)
var len: Int
while (inputStream.read(buf).also { len = it } > 0) {
out.write(buf, 0, len)
}
out.close()
inputStream.close()
pfd.close()
valuesvideos.clear()
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 0)
try {
setExifFromUri(
context,
uriSavedVideo,
File(destinationPath)
)
} catch (e: IOException) {
e.printStackTrace()
}
} catch (e: Exception) {
e.printStackTrace()
}
handler.post {
context.contentResolver.update(uriSavedVideo, valuesvideos, null, null)
action()
}
}
}
}
Note that this code is only for android 10 and above, because you can easily save the video file to ecternal storage below android 10.

Related

How to share the THIS applications base.apk using Intent? [duplicate]

This question already has answers here:
exposed beyond app through ClipData.Item.getUri
(4 answers)
Closed 8 months ago.
I want to share my application using a share button inside it. Once the button is clicked it should get the base.apk from the package manager and then share it using Intents.
Here is what I have so far:
All UI is ready and working
I have the following code to get the app and share it
try {
val pm = packageManager
val ai = pm.getApplicationInfo(packageName, 0)
val srcFile = File(ai.publicSourceDir)
val share = Intent()
share.action = Intent.ACTION_SEND
share.type = "application/vnd.android.package-archive"
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(srcFile))
startActivity(Intent.createChooser(share, "Sharing"))
} catch (e: Exception) {
UtilityMethods(this).toast("Failed To Share The App", "e")
e.printStackTrace()
}
But I get an error with this procedure.
android.os.FileUriExposedException: file:///data/app/~~BC-clKZDViP_O7n44ooPbQ%3D%3D/MyAppPublicSourceDirectory/base.apk exposed beyond app through ClipData.Item.getUri()
Is there any help I can get regarding this? I tried a lot of solutions, but they don't work for me.
EDIT:: Updated Code, Copy the base.apk to Downloads Folder and Rename it. Then try to share it (which is where the error invokes from).
try {
// get the base apk of the app
val pm = packageManager
val ai = pm.getApplicationInfo(packageName, 0)
val srcFile = File(ai.publicSourceDir)
// save the file in Downloads folder
val dstFile = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"LogsCalculator.apk"
)
dstFile.createNewFile()
val input = FileInputStream(srcFile)
val output = FileOutputStream(dstFile)
val buffer = ByteArray(1024)
var length: Int = input.read(buffer)
while (length > 0) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
output.flush()
output.close()
input.close()
// share the apk file now
val intent = Intent(Intent.ACTION_SEND)
intent.type = "application/vnd.android.package-archive"
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(dstFile))
startActivity(Intent.createChooser(intent, getString(R.string.sharing)))
} catch (e: Exception) {
UtilityMethods(this).toast("Failed To Share The App", "e")
e.printStackTrace()
}
It Still Does Not Work.
On later API versions, not even backup tools can obtain the APK anymore, therefore the approach is literally pointless. Instead use Firebase Dynamic Links, in order to permit user to user sharing of your application. This way they can install from Google Play Store, instead up installing some APK of unknown origin, which may not update well.
I got the solution.
try {
// get the base.apk
val baseApkLocation =
applicationContext.packageManager.getApplicationInfo(
applicationContext.packageName,
PackageManager.GET_META_DATA
).sourceDir
// get the file
val baseApk = File(baseApkLocation)
// the path
val path = Environment.getExternalStorageDirectory().toString() + "/Download/"
// make the directory
val dir = File(path)
// if the directory doesn't exist, make it
if (!dir.exists()) {
dir.mkdirs()
}
// Copy the .apk file to downloads directory
val destination = File(
path + "MyAppName.apk"
)
if (destination.exists()) {
destination.delete()
}
destination.createNewFile()
val input = FileInputStream(baseApk)
val output = FileOutputStream(destination)
val buffer = ByteArray(1024)
var length: Int = input.read(buffer)
while (length > 0) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
output.flush()
output.close()
input.close()
// get content uri for the file
val uri = FileProvider.getUriForFile(
this,
BuildConfig.APPLICATION_ID + ".provider",
destination
)
// share the file
val intent = Intent(Intent.ACTION_SEND)
intent.type = "application/vnd.android.package-archive"
intent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(Intent.createChooser(intent, getString(R.string.share_app)))
} catch (e: Exception) {
Lib(this).toast("Failed To Share The App", "e")
e.printStackTrace()
}
Here is how it works
Get the base.apk file of the app from its source dir.
Copy the file to the new location and give it a meaningful name.
Get the content URI of the new file. This is what was missing.
// get content uri for the file
val uri = FileProvider.getUriForFile(
this,
BuildConfig.APPLICATION_ID + ".provider",
destination
)
Share the file.
Anyways thanks for all the help.

FileObserver not working on Android SDK 30

I am working on an android application where i have used FileObserver to get data changes on a specific folder. The folder is WhatsApp Images and whenever there is a new file added to that folder i perform my further work when onEvent of FileObserver is triggered.
Everything works fine until i set targetSdkVersion=29 but as i am migrating my project to targetSdkVersion=30 FileObserver stopped working.
Below is my code for FileObserver
import android.os.Environment
import android.os.FileObserver
import android.util.Log
import java.io.File
class WhatsAppImageObserver11(var notify:(msg:String)->Unit) : FileObserver(
File(
Environment.getExternalStorageDirectory().toString(),
Constants.whatsapp_images_path11).toString(), ALL_EVENTS
) {
init {
Log.d("WhatsAppImageObserver11", "start")
}
override fun onEvent(i: Int, str: String?) {
val str2 = "WhatsAppImageObserver11"
if (i == CREATE || i == MOVED_TO && str != ".probe") {
val sb = StringBuilder()
sb.append("create File path--> ")
sb.append(str)
Log.d(str2, sb.toString())
try {
val whatsDeleted = File(
Environment.getExternalStorageDirectory().path,
Constants.whatsapp_reserved_media
)
if(!whatsDeleted.exists()) {
whatsDeleted.mkdirs()
}
val srcFile = File(
Environment.getExternalStorageDirectory(),
Constants.whatsapp_images_path11+str)
val destFile = File(Environment.getExternalStorageDirectory(), Constants.whatsapp_reserved_media+str)
if (srcFile.exists()){
srcFile.copyTo(target = destFile, overwrite = false, bufferSize = DEFAULT_BUFFER_SIZE)
}
} catch (e: Exception) {
val sb2 = StringBuilder()
sb2.append("create error: ")
sb2.append(e.toString())
Log.d(str2, sb2.toString())
}
}
if (i and 512 != 0 || i and 1024 != 0) {
val sb3 = StringBuilder()
sb3.append("dlete File path--> ")
sb3.append(str)
Log.d(str2, sb3.toString())
try {
val whatsDeleted = File(
Environment.getExternalStorageDirectory().path,
Constants.new_whatsapp_deleted_media
)
if(!whatsDeleted.exists()) {
whatsDeleted.mkdirs()
}
val srcFile = File(Environment.getExternalStorageDirectory().path, Constants.whatsapp_reserved_media+str)
val destFile = File(Environment.getExternalStorageDirectory().path, Constants.new_whatsapp_deleted_media+str)
if (srcFile.exists()){
srcFile.copyTo(target = destFile, overwrite = false, bufferSize = DEFAULT_BUFFER_SIZE)
srcFile.delete()
notify(destFile.absolutePath)
}
} catch (e2: Exception) {
val sb4 = StringBuilder()
sb4.append("del error: ")
sb4.append(e2.toString())
Log.d(str2, sb4.toString())
}
}
}
}
Here in this FileObserver i am copying media from WhatsApp Reserved Media to My own WhatsAppDeleted folder for media recovery feature.
What i have tried?
1- As i know Environment.getExternalStorageDirectory() is deprecated i tried replacing it with mContext.getExternalFilesDir(null).getAbsolutePath()
2- Also checked using android:preserveLegacyExternalStorage="true" in Manifest.
3- Tried added ignore attribute in
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage"/>
What is Required?
1- FileObserver on path "/Android/media/" + WHATSAPP_PKG_NAME + "/WhatsApp/Media/WhatsApp Images/" should trigger onEvent when i set targetSdkVersion-30
Can somebody please help me out with this? Any help will be appreciated.
Thank you
As written here:
Apps that run on Android 11 but target Android 10 (API level 29) can still request the requestLegacyExternalStorage attribute. This flag allows apps to temporarily opt out of the changes associated with scoped storage, such as granting access to different directories and different types of media files. After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.
Basically, you don't have permission to "listen" to external directories in the device, but only to your own internal/external directories.
You should use the MediaStore API in order to access media files which have been scanned by the OS (Including WhatsApp's files).
You can use components like JobService to register for the event of a new media been scanned.
Enjoy

Store File To External Storage Not Working For Android 10 and above - Android Studio/Kotlin

My app has an extract button that takes the data from text view and paste it in a text file "Ledger.txt". It creates a folder in Mobile internal Storage Root Directory "WaterLedger" and place a Ledger.txt file in it and if the text file is already present it appends the text in the file. The code is only working till android 9 not above.
In Android 10 on pressing Extract button it asks "grant permission to write file in storage" but even if you press Yes it still wont create folder (WaterLerger) and paste/update data in Text File (Ledger.txt)
Here is the code
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/WaterLedger"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "Ledger.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists() || folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write("****Ledger Updated On Dated:$currentDate*****\n")
out.newLine()
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
// Driver Code
extract.setOnClickListener {
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this, this)
if (anRW) {
pathToFileCreated = WriteFile().execute("$StringBuilder").get()
Log.d("pathToFileCreated", pathToFileCreated)
Toast.makeText(this,"File Saved",android.widget.Toast.LENGTH_LONG).show()
}
This will give you External Pictures directory URI (You can create your desirable directory into it):
private fun createTextURI(): Uri? {
val imageCollection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
else
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
val fileName = System.currentTimeMillis()
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "$fileName.txt")
put(MediaStore.MediaColumns.MIME_TYPE, "text/plain")
}
val finalURI = contentResolver.insert(imageCollection, contentValues)
resultUri = finalURI
return finalURI
}
Use this URI for file creation like this:
new File(finalURI.getPath());
And write into this file which you created above. ✌
Make sure you have WRITE_EXTERNAL_STORAGE permission.
Ref. Demo App

How to delete a temporary file in Download folder on Android 10

Simple to do in every system but Android, but I have and app that needs to create a csv file in SHARED EXTERNAL Download folder. Shutdown/restart phone/app and the file persist. Then I need to delete the file (persistent URI somewhere?) before I recreate it with new data. (if exists() delete)
I see all kinds of doc pointing to SAF for this process, but can find no examples anywhere of how to perform this simple process of create/delete. If is can do this on API 28 and it work on 29+ that would be great.
Without SAF I've done this:
fun writeCSV() {
val CSV_HEADER = "Last,First\n"
val mockData = "Tester,Joe\n"
val contentValues = ContentValues()
contentValues.put(MediaStore.Downloads.DISPLAY_NAME, "aTest.csv")
contentValues.put(MediaStore.Downloads.MIME_TYPE, "text/csv")
contentValues.put(MediaStore.Downloads.IS_PENDING, true)
val uri = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val fileUri = contentResolver.insert(uri, contentValues)
if (fileUri != null) {
try {
val outputStream = contentResolver.openOutputStream(fileUri)
outputStream!!.write(CSV_HEADER.toByteArray())
outputStream!!.write(mockData.toByteArray())
outputStream!!.close()
contentValues.put(MediaStore.Images.Media.IS_PENDING, false)
contentResolver.update(fileUri, contentValues, null, null)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
The problem is when fun is called again I need to delete this file and recreate it with new data because Android creates "aTest (1).csv" instead of overwriting it.

How to access external storage in Android 10?

As per Android 10 update, Reading and writing from external storage is restricted even we have
WRITE_EXTERNAL_STORAGE
I want to move my pdf file from internal storage (private of my android app) to DOWNLOADS folder. I tried so many approaches but nothing worked and there is no any help available on internet related to accessing external storage in android 10.
Privacy changes in Android 10  |  Android Developers
https://developer.android.com
hope below code will help you to resolve your issue and copy any file from internal to external storage.
fun copyPdfFrom(context: Context, sourceFile: File, destinationURIString: String) {
val destinationURI = Uri.parse(destinationURIString)
try {
val bufferedInputStream = BufferedInputStream(FileInputStream(sourceFile.absoluteFile))
val outPutStream = context.contentResolver.openOutputStream(destinationURI)!!
var len = 0
val brr = ByteArray(1024)
while ((bufferedInputStream.read(brr, 0, brr.size).also { len = it }) != -1) {
outPutStream.write(brr, 0, len)
}
outPutStream.flush()
outPutStream.close()
bufferedInputStream.close()
}
catch (e: Exception) {
e.printStackTrace()
}
}

Categories

Resources