安卓Android开发:以ActivityResultLauncher方式进行页面跳转、传递参数、拍照或选择文件,以及调用系统应用打开各种类型的指定文件

ActivityResultLauncher是安卓官方推荐的用来替代startActivityForResult的新方式。通过它可以非常方便地调用系统Intent进行拍照,或是选取本地的文件。

本文共分为5个章节 :

一、定义ActivityResultLauncher

二、注册Launcher

三、调用系统Intent

四、使用FileProvider复制一份文件

五、使用系统应用打开各种类型的指定文件

欢迎给我留言,或是写邮件给我:

randolph.carter.xu@gmail.com

28300098@qq.com

一、定义ActivityResultLauncher

在需要调用系统Intent之前,我们需要定义所需的Launcher:

protected ActivityResultLauncher activityResultLauncher;
protected ActivityResultLauncher takePhotoLauncher;
protected ActivityResultLauncher selectImageLauncher;
protected ActivityResultLauncher selectFileLauncher;

此处我定义了4个不同的Launcher,分别用来处理普通的Intent跳转、拍照、选择相册中已有的图片和选择手机中的文件。

activityResultLauncher:处理普通的Intent跳转,并携带参数往返;

takePhotoLauncher:打开照相机进行拍照,并获得照片;

selectImageLauncher:打开系统Intent选择手机上的图片;

selectFileLauncher:打开系统Intent选择手机里的文件。

二、注册Launcher

在正式使用之前,我们需要先针对不同的需要注册不同的Launcher。

2.1注册普通Intent跳转及回调

this.activityResultLauncher = this.registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    new ActivityResultCallback<ActivityResult>(){

        @Override
        public void onActivityResult(ActivityResult result) {
            //使用result.getResultCode()来获取返回的result code数据
            //使用result.getData.getStringExtra()或其它方法,可以获取返回参数
        }
    }
);

请注意上述代码片段中的以下内容:

ActivityResultContracts.StartActivityForResult()

其对应的Callback方法是:

ActivityResultCallback<ActivityResult>(){

   @Override
   public void onActivityResult(ActivityResult result) {
      //使用result.getResultCode()来获取返回的result code数据
      //使用result.getData.getStringExtra()或其它方法,可以获取返回参数
   }
}

2.2注册拍照Intent及回调

this.takePhotoLauncher = this.registerForActivityResult(
    new ActivityResultContracts.TakePicture(), 
    new ActivityResultCallback<Boolean>() {
        @Override
        public void onActivityResult(Boolean result) {
            if(result){
                //result 是布尔值,为true时表示拍照成功
            }
        }
    }
);

请注意上述代码片段中的以下内容:

ActivityResultContracts.TakePicture()

其对应的Callback方法是:

ActivityResultCallback<Boolean>() {
    @Override
    public void o
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值