我正在开发一个 android 应用程序,我曾经在其中FileObserver
获取特定文件夹的数据更改。该文件夹是 WhatsApp 图片,每当有新文件添加到该文件夹时,我都会在触发时执行我的进一步onEvent
工作FileObserver
。在我设置之前一切正常,targetSdkVersion=29
但是当我将项目迁移到targetSdkVersion=30
FileObserver 时停止工作。
下面是我的 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())
}
}
}
}
在此 FileObserver 中,我正在将媒体从 WhatsApp 保留媒体复制到我自己的 WhatsAppDeleted 文件夹以进行媒体恢复功能。
我试过什么?
1-据我所知Environment.getExternalStorageDirectory()
已弃用,我尝试将其替换为mContext.getExternalFilesDir(null).getAbsolutePath()
2-也在android:preserveLegacyExternalStorage="true"
清单中检查使用。
3-尝试添加忽略属性
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage"/>
什么是必需的?
1-路径上的 FileObserver应该在我设置时"/Android/media/" + WHATSAPP_PKG_NAME + "/WhatsApp/Media/WhatsApp Images/"
触发onEvent
targetSdkVersion-30
有人可以帮我解决这个问题吗?任何帮助将不胜感激。
谢谢