Android-AdvancedWebView icon indicating copy to clipboard operation
Android-AdvancedWebView copied to clipboard

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

Open dphans opened this issue 4 years ago • 4 comments

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)
}

dphans avatar Dec 16 '20 10:12 dphans

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

ocram avatar Dec 16 '20 14:12 ocram

Can you provide new way in java fragment code?

mhemon avatar Dec 23 '20 19:12 mhemon

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

developerGM avatar Jun 17 '21 10:06 developerGM

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);
        }

developerGM avatar Jun 17 '21 12:06 developerGM