观心静

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

前言

  startActivityForResult() 被弃用,现在可以通过registerForActivityResult 进行Activity之间的传值和获取申请动态权限结果

Activity向上传值

MainActivity

package com.zh.demo
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.zh.demo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val activityResult =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == RESULT_OK) {
                    Log.e("zh", "返回数据 = ${it.data?.getStringExtra("data")}")
                }
            }

        binding.jump.setOnClickListener {
            activityResult.launch(Intent(this, DemoActivity::class.java))
        }
    }
}

DemoActivity

package com.zh.demo

import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.zh.demo.databinding.ActivityDemoBinding


class DemoActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        val binding = ActivityDemoBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.back.setOnClickListener {
            val intent = Intent()
            intent.putExtra("data", "返回的数据")
            setResult(RESULT_OK, intent)
            finish()
        }
    }
}

申请动态权限

package com.zh.demo
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.zh.demo.databinding.ActivityMainBinding
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.permission.setOnClickListener {
           requestPermission(listOf(android.Manifest.permission.CAMERA))
        }
    }

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissionResults ->
            if(permissionResults.isEmpty()){
                Log.e("zh", "没有申请权限")
                return@registerForActivityResult
            }
            permissionResults.values
            var isGranted = true
            for(it in permissionResults.keys){
                Log.e("zh", "${it} >>>>> ${ContextCompat.checkSelfPermission(this@MainActivity, it)} ", )
                if(ContextCompat.checkSelfPermission(this@MainActivity, it) != PackageManager.PERMISSION_GRANTED){
                    isGranted = false
                }
                if(shouldShowRequestPermissionRationale(it)){
                    /*
                    用户之前拒绝了权限请求但未选择“禁止后不再询问”:当用户之前拒绝了某个权限的请求,但没有选择“禁止后不再询问”的选项时,再次请求该权限时,
                    shouldShowRequestPermissionRationale将返回true,表示此时应该向用户展示一个解释为什么需要这个权限的对话框。
                     */
                    Log.e("zh", "需要解释权限>>${it}")
                } else {
                     /*
                        1.从未请求过该权限:如果应用从未向用户请求过某个权限,那么shouldShowRequestPermissionRationale将返回false,因为此时不需要向用户解释权限请求的原因。
                        2.用户已禁止权限且选择了“禁止后不再询问”:当用户之前拒绝了权限请求,并且选择了“禁止后不再询问”的选项,再次请求该权限时,shouldShowRequestPermissionRationale也会返回false,因为系统不会再次弹出权限请求对话框,而是需要用户手动在应用设置中开启权限。
                        3.用户已允许权限:如果用户已经允许了某个权限,那么再次请求该权限时,shouldShowRequestPermissionRationale也会返回false,因为权限已经被授予,无需再向用户解释。
                      */
                    Log.e("zh", "无需解释权限>>${it}")
                }
            }
            if(!isGranted){
                Log.e("zh", "权限被拒绝")
                return@registerForActivityResult
            }
        }

    fun requestPermission(
        permissions: List<String>,
    ) {
        lifecycleScope.launch {
            //repeatOnLifecycle 需要引入   implementation ("androidx.lifecycle:lifecycle-runtime-ktx:2.5.1")
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                val notGrantedList = permissions.filter { ContextCompat.checkSelfPermission(this@MainActivity, it) != PackageManager.PERMISSION_GRANTED }
                if(notGrantedList.isEmpty()){
                    Log.e("zh", "已经被全部授权了")
                    return@repeatOnLifecycle
                }
                requestPermissionLauncher.launch(notGrantedList.toTypedArray())
            }
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

End

posted on 2024-10-20 14:10  观心静  阅读(147)  评论(0编辑  收藏  举报