AndroidManifest.xml 权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" />
build.gradle --用了第三方管理动态权限申请的库
implementation 'com.yanzhenjie:permission:2.0.0-rc4'
下面是代码很简单:
主界面Main,布局文件就是4个button
class MainActivity3 : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) AndPermission.with(this@MainActivity3).permission(Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE).onGranted(object : Action { override fun onAction(permissions: MutableList<String>?) { //同意权限 var rootDir: File = File(AudioConfig.rootDir) var audioFile: File = File(AudioConfig.audioPath) if (!rootDir.exists()) { var isDir = rootDir.mkdir() if (!isDir) { Toast.makeText(this@MainActivity3, "创建文件夹失败", Toast.LENGTH_SHORT).show() return } } if (!audioFile.exists()) { var isFile = audioFile.createNewFile() if (isFile) { Toast.makeText(this@MainActivity3, "创建文件成功", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity3, "创建文件失败", Toast.LENGTH_SHORT).show() return } } } }).onDenied(object : Action { //拒绝权限 override fun onAction(permissions: MutableList<String>?) { Toast.makeText(this@MainActivity3, "没有权限", Toast.LENGTH_SHORT