APK写入的推荐位置是应用程序专用目录。可以通过以下代码示例获取该目录的路径:
// 获取应用程序专用目录的根路径
File rootDir = context.getFilesDir();
// 获取应用程序专用目录下的子目录路径
File subDir = context.getDir("subdir", Context.MODE_PRIVATE);
// 获取应用程序专用缓存目录的路径
File cacheDir = context.getCacheDir();
// 获取应用程序专用外部存储目录的路径
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File externalDir = context.getExternalFilesDir(null);
}
其中,context
是Context
的实例,可以通过Activity
、Service
等子类的this
关键字获取到。在上述示例中,getFilesDir()
获取应用程序专用目录的根路径,getDir()
获取应用程序专用目录下的子目录路径。getCacheDir()
获取应用程序专用缓存目录的路径。getExternalFilesDir()
获取应用程序专用外部存储目录的路径,如果设备没有外部存储,则返回null
。
在Android 6.0及以上版本中,需要动态申请读写外部存储的权限。可以通过以下代码示例进行权限申请:
// 动态申请读写外部存储的权限
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
return;
}
}