美文网首页
Activity Result API

Activity Result API

作者: 九风特 | 来源:发表于2022-02-16 16:31 被阅读0次

Activity result API就是用来替换和扩展老式的startActivityForResult的,同时还能用于动态申请权限,当然还能自定义,但我认为前两者足够用了,所以没有模拟自定义的情况。用到时在研究吧。通过看下面的代码和注释就知道了.
值得注意的是用这套api申请权限,别忘了在appManifest中声明权限

    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
package com.sky.testactivityresultapi

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts


class BlankFragment : Fragment() {
    private lateinit var textView: TextView

    /**
     * 这是最简单的使用方式,利用系统给定的ActivityResultContract
     * 就相当于传统的startActivityForResult
     * 目标activity应设定想要返回的intent
     * 在回调中通过it.data访问返回的intent得到相应的值, 以及一个标记it.resultCode
     */
    private val simpleTest =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            textView.text = "code:${it.resultCode}, data:${it.data?.getStringExtra("value")}"
        }

    /**
     * 测试申请一个权限
     * 我们例子中申请了一个访问通讯录的权限,我们看到比传统方式简单明了的多
     * 需要注意的是,该权限应该在manifest清单文件中声明
     */
    private val permissionOneTest =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { permissionGranted ->
            textView.text = permissionGranted.toString()
        }

    /**
     * 测试获取通讯录
     *
     */
    private val pickContact =
        registerForActivityResult(ActivityResultContracts.PickContact()){uri->
            textView.text = uri?.toString()
        }

    /**
     * 测试申请多个权限
     *
     */
    private val permissionMulti =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()){retMap->
            retMap?.also {
                textView.text = it.toString()
            }
        }

    //用摄像机截图并存储,这个比较复杂 懒得写 真用到的时候在研究吧
    //https://stackoverflow.com/questions/65751435/activityresultcontracts-takepicture-returns-no-such-file-or-directory
    private val takePicture =
        registerForActivityResult(ActivityResultContracts.TakePicture()){

        }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false).also {
            textView = it!!.findViewById(R.id.textView)
            it.findViewById<Button>(R.id.button1)?.setOnClickListener {
                val intent = Intent(activity, DataActivity1::class.java).apply {
                    putExtra("arg", "zrm")
                }
                simpleTest.launch(intent)
            }

            //获取单个权限
            it.findViewById<Button>(R.id.buttonOnePermission)?.setOnClickListener {
                permissionOneTest.launch(Manifest.permission.READ_CONTACTS)
            }

            //访问通讯录
            it.findViewById<Button>(R.id.pickContact)?.setOnClickListener {
                pickContact.launch(null)
            }

            //获取多个权限
            it.findViewById<Button>(R.id.buttonMulti)?.setOnClickListener {
                permissionMulti.launch(
                    arrayOf(
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA,
                    )
                )
            }

            //和本主题无关的一个测试,启动其它app
            it.findViewById<Button>(R.id.buttonStartup)?.setOnClickListener {
                val to = Intent(Intent.ACTION_VIEW,
                    Uri.parse("zrm://bony.zhu.com/main?arg1=100&arg2=hero"))
                startActivity(to)
            }
        }
    }
}
package com.sky.testactivityresultapi

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class DataActivity1 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_data1)

        findViewById<TextView>(R.id.textViewArg).text = intent.getStringExtra("arg")
        findViewById<Button>(R.id.buttonOk).setOnClickListener {
            setResult(Activity.RESULT_OK, Intent().putExtra("value", "I am back!"))
            finish()
        }
        findViewById<Button>(R.id.buttonCancel).setOnClickListener {
            setResult(Activity.RESULT_CANCELED, Intent().putExtra("value", "I am canceled!"))
            finish()
        }
    }
}

相关文章

网友评论

      本文标题:Activity Result API

      本文链接:https://www.haomeiwen.com/subject/rkddlrtx.html