英文:
Songs List does not display after giving permissions
问题
I've translated the code part as requested. Here it is:
我正在制作一个音乐应用,并已经授予了权限,权限对话框确实出现了,但问题是,一旦我授予了权限,歌曲就不会显示。
但是,当我停止应用程序并重新打开它时,我可以看到歌曲显示出来了。
我想在我授予权限的同时立即显示歌曲。我该如何实现这个目标?
编辑:我正在使用一个片段
private var storagePermissions = arrayOf(READ_EXTERNAL_STORAGE)
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
var storagePermissions13 = arrayOf(READ_MEDIA_AUDIO)
private fun permissionsHandler(): Array<String> {
val p: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
storagePermissions13
} else {
storagePermissions
}
return p
}
private var activityResultLauncher: ActivityResultLauncher<Array<String>> = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
var allAreGranted = true
for (b in result.values) {
allAreGranted = allAreGranted && b
}
if (allAreGranted) {
getMusicList()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
activityResultLauncher.launch(permissionsHandler())
}
Please note that the code translation is provided, but it's important to review the code in its entirety to ensure it fits your project's context and requirements.
英文:
I'm a making a music app and have given permission the permission dialog does appear but the problem is as soon as I grant the permission the songs are not displayed.
But when I stop the app and reopen it, I can see the songs displayed.
I want to display the songs as soon as I give the permissions.How do I achieve that
Edit: I am using a fragment
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
private var storagePermissions = arrayOf(READ_EXTERNAL_STORAGE)
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
var storagePermissions13 = arrayOf(READ_MEDIA_AUDIO)
private fun permissionsHandler(): Array<String> {
val p: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
storagePermissions13
} else {
storagePermissions
}
return p
}
private var activityResultLauncher: ActivityResultLauncher<Array<String>> = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {result ->
var allAreGranted = true
for(b in result.values) {
allAreGranted = allAreGranted && b
}
if(allAreGranted) {
getMusicList()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
activityResultLauncher.launch(permissionsHandler())
<!-- end snippet -->
答案1
得分: 2
以下是您要翻译的内容:
"It's simple with this, Check if storage or media (for android 13) permission is granted or not & if it can be asked again or not. If it can be asked again, then do it and if not then simply show a dialog with a button to redirect user to the app settings screen to grant the permission from there manually.
Here is how to do so.
private val storagePermission = if (isTiramisuPlus())
Manifest.permission.READ_MEDIA_AUDIO
else {
Manifest.permission.READ_EXTERNAL_STORAGE
}
private var askCount = 0
private val permissionsLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (!granted) {
askCount++
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& shouldShowRequestPermissionRationale(storagePermission)
) {
askCount++
askForStoragePermission()
} else {
showSettingsDialog()
}
} else {
onPermissionGranted()
}
}
private var permissionDialog: AlertDialog? = null
private fun showSettingsDialog() {
if (permissionDialog == null) {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setTitle(getString(R.string.permission_denied_title))
.setCancelable(false)
.setMessage(getString(R.string.allow_for_smooth))
.setPositiveButton(R.string.action_settings) { dialog, _ ->
dialog.dismiss()
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts(
"package", packageName,
null
)
intent.data = uri
startActivity(intent)
}
permissionDialog = builder.create()
permissionDialog?.show()
} else {
if (permissionDialog?.isShowing == false) permissionDialog?.show()
}
}
private fun askForStoragePermission() {
permissionsLauncher.launch(storagePermission)
}
private fun storagePermissionGranted() = storagePermission.all {
ContextCompat.checkSelfPermission(
this,
storagePermission
) == PackageManager.PERMISSION_GRANTED
}
Using this code, you'll be able to grant and handle the result of the permission, then put permission related logic in onResume
and load your music files accordingly whenever the permission is granted."
"您可以使用此代码来授予和处理权限的结果,然后在 onResume
中放置与权限相关的逻辑,并在权限被授予时加载您的音乐文件。"
"You have the onPermissionGranted()
method to put your loading logic into."
"您可以使用 onPermissionGranted()
方法来放置加载逻辑。"
英文:
It's simple with this, Check if storage or media (for android 13) permission is granted or not & if it can be asked again or not. If it can be asked again, then do it and if not then simply show a dialog with a button to redirect user to the app settings screen to grant the permission from there manually.
Here is how to do so.
private val storagePermission = if (isTiramisuPlus())
Manifest.permission.READ_MEDIA_AUDIO
else {
Manifest.permission.READ_EXTERNAL_STORAGE
}
private var askCount = 0
private val permissionsLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (!granted) {
askCount++
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& shouldShowRequestPermissionRationale(storagePermission)
) {
askCount++
askForStoragePermission()
} else {
showSettingsDialog()
}
} else {
onPermissionGranted()
}
}
private var permissionDialog: AlertDialog? = null
private fun showSettingsDialog() {
if (permissionDialog == null) {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setTitle(getString(R.string.permission_denied_title))
.setCancelable(false)
.setMessage(getString(R.string.allow_for_smooth))
.setPositiveButton(R.string.action_settings) { dialog, _ ->
dialog.dismiss()
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts(
"package", packageName,
null
)
intent.data = uri
startActivity(intent)
}
permissionDialog = builder.create()
permissionDialog?.show()
} else {
if (permissionDialog?.isShowing == false) permissionDialog?.show()
}
}
private fun askForStoragePermission() {
permissionsLauncher.launch(storagePermission)
}
private fun storagePermissionGranted() = storagePermission.all {
ContextCompat.checkSelfPermission(
this,
storagePermission
) == PackageManager.PERMISSION_GRANTED
}
Using this code, you'll be able to grant and handle the result of the permission, then put permission related logic in onResume
and load your music files accordingly whenever the permission is granted.
override fun onResume() {
super.onResume()
if (!storagePermissionGranted()) {
if (askCount == 0)
askForStoragePermission()
else if (askCount == 2) {
showSettingsDialog()
}
return
} else {
askCount = 2
if (permissionDialog?.isShowing == true)
permissionDialog?.dismiss()
onPermissionGranted()
}
}
You have the onPermissionGranted()
method to put your loading logic into.
private fun onPermissionGranted() {
//Your music files loading logic here
}
答案2
得分: 1
你可以尝试将你的getMusicList()放在onRequestPermissionsResult()内部:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_STORAGE_PERMISSION) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限已授予,在这里更新歌曲列表
} else {
// 权限被拒绝,在这里处理错误
}
}
}
英文:
you can try putting your getMusicList() inside the onRequestPermissionsResult:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_STORAGE_PERMISSION) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, update the song list here
} else {
// Permission denied, handle the error here
}
}
}
答案3
得分: 1
以下是已翻译的代码部分:
您可以使用以下代码以实现您的目标:
~~~
private var storagePermissions = arrayOf(READ_EXTERNAL_STORAGE)
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
var storagePermissions13 = arrayOf(Manifest.permission.READ_MEDIA_AUDIO)
private fun permissionsHandler(): Array<String> {
val p: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
storagePermissions13
} else {
storagePermissions
}
return p
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
ActivityCompat.requestPermissions(activity!!,permissionsHandler(),1)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//Check if permission is granted
if (requestCode == 1 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Call the function to get the music list
getMusicList()
}
}
~~~
您需要稍微修改您的代码。如您所见,在上述代码中,您需要将`getMusicList()`函数放在`onRequestPermissionsResult()`函数内部。`onRequestPermissionsResult()`函数在用户授予权限后立即被调用。因此,通过将`getMusicList()`函数放在`onRequestPermissionsResult()`内部,您可以在权限被授予后立即获取歌曲。
**编辑:**
`androidx.fragment.app.Fragment`中已弃用`onRequestPermissionsResult()`函数。因此,对于片段,必须使用`registerForActivityResult()`函数。以下是示例代码:
```kotlin
//检查权限是否已授予
val requestPermLaunch = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
//如果权限已授予,则运行代码
getMusicList()
} else {
//如果权限未授予,则运行代码
Toast.makeText(getApplicationContext(), "未授予权限", Toast.LENGTH_SHORT).show()
}
}
//启动读取外部存储权限请求
private fun startLocationPermissionRequest() {
requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
请注意,这是已翻译的代码部分,不包括问题回答。
英文:
You can use the following code for your purpose:
private var storagePermissions = arrayOf(READ_EXTERNAL_STORAGE)
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
var storagePermissions13 = arrayOf(Manifest.permission.READ_MEDIA_AUDIO)
private fun permissionsHandler(): Array<String> {
val p: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
storagePermissions13
} else {
storagePermissions
}
return p
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
ActivityCompat.requestPermissions(activity!!,permissionsHandler(),1)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//Check if permission is granted
if (requestCode == 1 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Call the function to get the music list
getMusicList()
}
}
You need to slightly modify your code. As you can see, in the above code, you have to put the getMusicList()
function inside the onRequestPermissionsResult()
function. The onRequestPermissionsResult()
function is called as soon as the user gives permission. So, by putting your getMusicList()
function inside onRequestPermissionsResult()
, you can get the songs as soon as permission is given.
Edit:
onRequestPermissionsResult()
is deprecated in androidx.fragment.app.Fragment
. So, for fragments, the registerForActivityResult()
function has to be used. Example code:
//Check if permission is granted
val requestPermLaunch = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
//Run code if permission is granted
getMusicList()
} else {
//Run code if permission is not granted
Toast.makeText(getApplicationContext(), "Permission has not been granted", Toast.LENGTH_SHORT).show()
}
}
//Launch the read external storage permission
private fun startLocationPermissionRequest() {
requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论