XResultLauncher
open class XResultLauncher<I, O>(caller: ActivityResultCaller, contract: ActivityResultContract<I, O>) {
private var launcher: ActivityResultLauncher<I>? = null
private var callback: ActivityResultCallback<O>? = null
init {
launcher = caller.registerForActivityResult(contract, ActivityResultCallback { result: O ->
if (callback != null) {
callback!!.onActivityResult(result)
callback = null
}
})
}
fun launch(@SuppressLint("UnknownNullness") input: I, callback: ActivityResultCallback<O>) {
this.callback = callback
launcher!!.launch(input)
}
}
XActivityLauncher
open class XActivityLauncher(caller: ActivityResultCaller) :
XResultLauncher<String, Uri?>(caller,ActivityResultContracts.GetContent())
使用方法
private XActivityLauncher getContentLauncher = new XActivityLauncher(this);
getContentLauncher.launch("txt/*", new ActivityResultCallback<Uri>() {
@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
public void onActivityResult(Uri result) {
//回调的逻辑
}
});
没封装前
ActivityResultLauncher launcher = registerForActivityResult(new ResultContract("txt/*"), new ActivityResultCallback<Intent>() {
@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
public void onActivityResult(Intent result) {
if (result == null) {
return;
}
Uri uri = result.getData();
readFromXML(PickUtils.getFileApiQ(uri,getContext()), new CommonCallback<String>() {
@Override
public void Callback(String bean) {
Log.d("DashboardFragment", bean);
}
});
}
});
ResultContract
public class ResultContract extends ActivityResultContract<Boolean, Intent> {
private String fileType;
public ResultContract(String type){
this.fileType = type;
}
@NonNull
@Override
public Intent createIntent(@NonNull Context context, Boolean input) {
Intent intent = new Intent();
intent.setType(fileType);//同时选择视频和图片
intent.setAction(Intent.ACTION_GET_CONTENT);
// Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
return intent;
}
@Override
public Intent parseResult(int resultCode, @Nullable Intent intent) {
return intent;
}
}
调用
launcher.launch(true);