Anddroid 7.0 之后系统默认禁止访问公共存储目录。所以需要将文件保存在系统分配给APP的私有空间中,该路径获取也是很简单的,主要有两种场景。
1 在Activity 中获取该路径:
该场景只需调用函数
getExternalFilesDir(null)
函数即可获得,代码如下
var privatePath = getExternalFilesDir(null).toString()
该私有空间路径位于“外部存储根目录/Android/data/应用包名/files”下
2 在其他类中获取该路径
由于函数getExternalFilesDir() 函数只能在Activity中直接调用,那在我们需要写一些工具类时,也需要获取该路径,该如何实现呢?
比较推荐的方法是先写一个继承自Application的类,在该类中声明 context 的静态常量(也就是一个全局的context),这样在该APP的所有类中均可直接调用该context下的方法。代码如下
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
//获取context
context = applicationContext
}
companion object {
//创建一个伴生对象,以便获取context对象
var context: Context? = null
private set
}
}
注意:这个类写完后需要在 AndroidManifest.xml 文件中的< application >节点下声明一下。这样APP在初始化时才会把这个 context 作为一个全局常量初始化
<application
android:name=".MyApplication"
以上完成后,就可以在其他的类中使用该 context 了,例如下面的代码
import com.example.recorder.MyApplication.Companion.context
fun getAPPpath():String{
return context?.getExternalFilesDir(null).toString()
}