为什么这不起作用?我也修改了Manifest。 我没有按照我的编码要求获得许可。它表现得好像我甚至没有请求任何许可。
我已经制作了一个闪屏,我希望它在进入MainActivity之前请求许可。
启动画面应持续1秒。
class SplashActivity : AppCompatActivity() {
var permissionsString = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.PROCESS_OUTGOING_CALLS,
Manifest.permission.RECORD_AUDIO)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
if (hasPermissions(this@SplashActivity,*permissionsString)){
ActivityCompat.requestPermissions(this@SplashActivity,permissionsString,131)
}else{
Handler().postDelayed({
val startAct = Intent(this@SplashActivity,MainActivity::class.java)
startActivity(startAct)
this.finish()},1000)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when(requestCode){
131 ->{
if (grantResults.isNotEmpty()
&& grantResults[0]==PackageManager.PERMISSION_GRANTED
&& grantResults[1]==PackageManager.PERMISSION_GRANTED
&& grantResults[2]==PackageManager.PERMISSION_GRANTED
&& grantResults[3]==PackageManager.PERMISSION_GRANTED
&& grantResults[4]==PackageManager.PERMISSION_GRANTED){
Handler().postDelayed({
val startAct = Intent(this@SplashActivity,MainActivity::class.java)
startActivity(startAct)
this.finish()},1000)
}else{
Toast.makeText(this@SplashActivity,"Grant it Please",Toast.LENGTH_SHORT).show()
this.finish()
}
return
}
else->{
Toast.makeText(this@SplashActivity,"Something wrong",Toast.LENGTH_SHORT).show()
this.finish()
return
}
}
}
fun hasPermissions(context: Context,vararg permissions: String): Boolean{
var hasAllPermissions = true
for (permission in permissions){
val res = context.checkCallingOrSelfPermission(permission)
if (res!=PackageManager.PERMISSION_GRANTED){
hasAllPermissions = false
}
}
return hasAllPermissions
}
}
答案 0 :(得分:0)
检查
targetSdkVersion
项目gradle文件中的。 <> = 23可以调用运行时权限,否则将自动获得权限。
答案 1 :(得分:0)
那是因为你的if condition
错了。它应该包括NOT运算符以请求许可,如下所示:
if (!hasPermissions(this@SplashActivity,*permissionsString)) {
//Ask for permission
}
如果您未获得许可,请征得同意。在您的情况下,您正在检查您是否有权限,然后请求许可是错误的。