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