delight-im / Android-AdvancedWebView

Enhanced WebView component for Android that works as intended out of the box
MIT License
2.39k stars 576 forks source link

[Improve] Use ActivityResultLauncher instead of onActivityResult, because old way has been deprecated. #283

Open dphans opened 3 years ago

dphans commented 3 years ago

I know that onActivityResult deprecated but still used in next API versions. But I suggest to upgrade to consistent with newer API.

Old way (Kotlin)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
   @Suppress("DEPRECATION")
   super.onActivityResult(requestCode, resultCode, data)
   getViewBinding().advancedWebView.onActivityResult(requestCode, resultCode, data)
}

New way (Kotlin)

private val mOnWebViewActivityResult = registerForActivityResult(
   ActivityResultContracts.StartActivityForResult()
) { result ->
   getViewBinding().advancedWebView.handleActivityResultCallback(result)
}
ocram commented 3 years ago

Thanks!

We might, at some point, switch to the new API, but that is absolutely low-priority.

More information on the API is available here as well: https://developer.android.com/training/basics/intents/result

mhemon commented 3 years ago

Can you provide new way in java fragment code?

developerGM commented 3 years ago

@mhemon did you solve using the new way in java?

developerGM commented 3 years ago

you can change original code with this:

public void setListener(final Fragment fragment, final Listener listener, final int requestCodeFilePicker) {
        if (fragment != null) {
            mFragment = new WeakReference<Fragment>(fragment);
            mSelectFileResultLauncher = mFragment.get().registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                onActivityResult(requestCodeFilePicker, result.getResultCode(), result.getData());
            });
        } else {
            mFragment = null;
        }
        setListener(listener, requestCodeFilePicker);
}
 if (mFragment != null && mFragment.get() != null && Build.VERSION.SDK_INT >= 11) {
            mSelectFileResultLauncher.launch(i);
//            mFragment.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker);
        } else if (mActivity != null && mActivity.get() != null) {
            mActivity.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker);
        }