Navigating the always-evolving scenery of Android improvement requires staying abreast of API adjustments and deprecations. 1 specified important alteration is the deprecation of the onActivityResult
methodology, a agelong-lasting mechanics for dealing with outcomes from actions launched with startActivityForResult
. This displacement has near galore builders questioning astir the champion alternate and however to seamlessly combine it into their initiatives. This article delves into the causes down the deprecation, explores the beneficial alternativeβthe Act Consequence APIβand offers a blanket usher to its implementation.
Wherefore onActivityResult
Was Deprecated
The onActivityResult
methodology, piece useful, suffered from respective drawbacks that led to its deprecation. Its reliance connected petition codes and consequence codes created a analyzable and mistake-susceptible scheme, particularly once dealing with aggregate act launches. The choky coupling betwixt actions made investigating and codification care difficult. Furthermore, the scheme lacked kind condition, expanding the hazard of runtime errors. The Act Consequence API addresses these points, offering a much sturdy and streamlined attack.
Ideate launching aggregate actions for antithetic functions, similar choosing an representation, requesting permissions, oregon accessing determination information. Managing these requests with integer-based mostly petition codes grew to become a nightmare, starring to possible conflicts and debugging complications. The fresh API gives a overmuch cleaner resolution.
Introducing the Act Consequence API
The Act Consequence API, launched successful AndroidX act
and fragment
libraries interpretation 1.2.zero, simplifies the procedure of dealing with act outcomes. It leverages powerfully typed contracts and callbacks, eliminating the demand for petition codes and enhancing codification readability. This fresh attack gives amended kind condition, decreasing the probability of runtime errors and bettering general codification choice.
This API introduces the conception of “contracts,” which pre-specify communal act consequence situations similar selecting an representation, requesting permissions, oregon getting contented from a URI. This standardized attack makes codification much predictable and simpler to realize.
Implementing the Act Consequence API
Implementing the Act Consequence API entails a fewer cardinal steps:
- Adhd the essential dependencies to your
physique.gradle
record. - Make an case of the due
ActivityResultContract
. - Registry the declaration utilizing
registerForActivityResult()
. - Motorboat the act utilizing the
motorboat()
methodology of the registered launcher. - Grip the consequence successful the offered callback.
For illustration, to choice an representation from the audience, you would usage the ActivityResultContracts.GetContent()
declaration. The returned URI tin past beryllium utilized to entree the chosen representation.
Advantages of Utilizing the Act Consequence API
The Act Consequence API affords respective benefits complete the deprecated onActivityResult
:
- Improved Kind Condition: Powerfully typed contracts destroy the hazard of kind-associated errors.
- Simplified Codification: Nary much managing petition codes and consequence codes.
- Amended Testability: Decoupled elements facilitate part investigating.
- Enhanced Readability: Clearer codification construction improves maintainability.
These advantages lend to a much strong, maintainable, and little mistake-susceptible codebase.
Dealing with Antithetic Consequence Situations
The Act Consequence API supplies assorted pre-constructed contracts for communal eventualities, together with GetContent
, StartActivityForResult
, RequestPermission
, and RequestMultiplePermissions
. This simplifies the implementation of divers functionalities similar choosing pictures, requesting permissions, and launching actions for circumstantial outcomes. Customized contracts tin besides beryllium created to grip much specialised usage instances.
For case, utilizing RequestMultiplePermissions
permits you to petition aggregate permissions concurrently and grip the granted and denied permissions individually inside the callback. This simplifies approval direction in contrast to the older, much cumbersome attack.
Wanting for deeper insights? Cheque retired this adjuvant assets: Getting a consequence from an act
Besides, see exploring Stack Overflow discussions connected this subject for applicable examples and assemblage insights.
For additional speechmaking connected contemporary Android improvement practices, you mightiness discovery this article connected Android improvement champion practices invaluable.
See this illustration: You’re processing an app that requires the person to choice an representation from their audience. With the Act Consequence API, you tin seamlessly combine this performance with conscionable a fewer traces of codification, guaranteeing a creaseless person education.
[Infographic Placeholder: Illustrating the procedure of utilizing the Act Consequence API with antithetic contracts]
By adopting the Act Consequence API, builders tin streamline their codification, trim errors, and better the general choice of their Android purposes. This contemporary attack to dealing with act outcomes gives a important betterment complete the deprecated onActivityResult
, making it an indispensable accomplishment for immoderate Android developer. It’s important to replace your initiatives to make the most of this fresh API for amended maintainability and to act actual with champion practices. This modulation, piece initially requiring any codification changes, finally leads to a much sturdy and businesslike improvement procedure. Research the linked sources and examples to statesman integrating the Act Consequence API into your tasks present. Commencement leveraging its advantages and lend to gathering much contemporary and maintainable Android purposes. Detect much astir associated subjects similar contemporary Android structure elements and champion practices for a deeper knowing of the evolving Android ecosystem. Clasp the alteration and heighten your improvement workflow.
Dive deeper into the planet of Android improvement and research assets similar the authoritative Android documentation and on-line communities. Act up to date connected the newest champion practices and API modifications to physique chopping-border purposes. Larn much astir structure elements similar ViewModel and LiveData to additional heighten your improvement abilities and make strong and scalable apps. Click on present for much.
Question & Answer :
I late found that onActivityResult
is deprecated. What ought to we bash to grip it?
Immoderate alternate launched for that?
A basal grooming is disposable astatine developer.android.com.
Present is an illustration connected however to person the current codification with the fresh 1:
The aged manner:
national void openSomeActivityForResult() { Intent intent = fresh Intent(this, SomeActivity.people); startActivityForResult(intent, 123); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent information) { if (resultCode == Act.RESULT_OK && requestCode == 123) { doSomeOperations(); } }
The fresh manner (Java):
national void openSomeActivityForResult() { Intent intent = fresh Intent(this, SomeActivity.people); someActivityResultLauncher.motorboat(intent); } // You tin bash the duty wrong onAttach oregon onCreate, i.e, earlier the act is displayed ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult( fresh ActivityResultContracts.StartActivityForResult(), fresh ActivityResultCallback<ActivityResult>() { @Override national void onActivityResult(ActivityResult consequence) { if (consequence.getResultCode() == Act.RESULT_OK) { // Location are nary petition codes Intent information = consequence.getData(); doSomeOperations(); } } });
The fresh manner (Kotlin):
amusive openSomeActivityForResult() { val intent = Intent(this, SomeActivity::people.java) resultLauncher.motorboat(intent) } var resultLauncher = registerForActivityResult(StartActivityForResult()) { consequence -> if (consequence.resultCode == Act.RESULT_OK) { // Location are nary petition codes val information: Intent? = consequence.information doSomeOperations() } }
EDIT. A amended attack would beryllium to brand it much generalised truthful that we tin reuse it. The snippet beneath is utilized successful 1 of my tasks however beware that it’s not fine-examined and whitethorn not screen each the circumstances.
BetterActivityResult.java
import android.contented.Intent; import androidx.act.consequence.ActivityResult; import androidx.act.consequence.ActivityResultCaller; import androidx.act.consequence.ActivityResultLauncher; import androidx.act.consequence.declaration.ActivityResultContract; import androidx.act.consequence.declaration.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.annotation.Nullable; national people BetterActivityResult<Enter, Consequence> { /** * Registry act consequence utilizing a {@nexus ActivityResultContract} and an successful-spot act consequence callback similar * the default attack. You tin inactive customise callback utilizing {@nexus #motorboat(Entity, OnActivityResult)}. */ @NonNull national static <Enter, Consequence> BetterActivityResult<Enter, Consequence> registerForActivityResult( @NonNull ActivityResultCaller caller, @NonNull ActivityResultContract<Enter, Consequence> declaration, @Nullable OnActivityResult<Consequence> onActivityResult) { instrument fresh BetterActivityResult<>(caller, declaration, onActivityResult); } /** * Aforesaid arsenic {@nexus #registerForActivityResult(ActivityResultCaller, ActivityResultContract, OnActivityResult)} but * the past statement is fit to {@codification null}. */ @NonNull national static <Enter, Consequence> BetterActivityResult<Enter, Consequence> registerForActivityResult( @NonNull ActivityResultCaller caller, @NonNull ActivityResultContract<Enter, Consequence> declaration) { instrument registerForActivityResult(caller, declaration, null); } /** * Specialised technique for launching fresh actions. */ @NonNull national static BetterActivityResult<Intent, ActivityResult> registerActivityForResult( @NonNull ActivityResultCaller caller) { instrument registerForActivityResult(caller, fresh ActivityResultContracts.StartActivityForResult()); } /** * Callback interface */ national interface OnActivityResult<O> { /** * Known as last receiving a consequence from the mark act */ void onActivityResult(O consequence); } backstage last ActivityResultLauncher<Enter> launcher; @Nullable backstage OnActivityResult<Consequence> onActivityResult; backstage BetterActivityResult(@NonNull ActivityResultCaller caller, @NonNull ActivityResultContract<Enter, Consequence> declaration, @Nullable OnActivityResult<Consequence> onActivityResult) { this.onActivityResult = onActivityResult; this.launcher = caller.registerForActivityResult(declaration, this::callOnActivityResult); } national void setOnActivityResult(@Nullable OnActivityResult<Consequence> onActivityResult) { this.onActivityResult = onActivityResult; } /** * Motorboat act, aforesaid arsenic {@nexus ActivityResultLauncher#motorboat(Entity)} but that it permits a callback * executed last receiving a consequence from the mark act. */ national void motorboat(Enter enter, @Nullable OnActivityResult<Consequence> onActivityResult) { if (onActivityResult != null) { this.onActivityResult = onActivityResult; } launcher.motorboat(enter); } /** * Aforesaid arsenic {@nexus #motorboat(Entity, OnActivityResult)} with past parameter fit to {@codification null}. */ national void motorboat(Enter enter) { motorboat(enter, this.onActivityResult); } backstage void callOnActivityResult(Consequence consequence) { if (onActivityResult != null) onActivityResult.onActivityResult(consequence); } }
With the supra attack, you inactive person to registry it earlier oregon throughout launching the act oregon fragment attachment. Erstwhile outlined, it tin beryllium reused inside the act oregon fragment. For illustration, if you demand to commencement fresh actions successful about of the act, you tin specify a BaseActivity
and registry a fresh BetterActivityResult
similar this:
BaseActivity.java
national people BaseActivity extends AppCompatActivity { protected last BetterActivityResult<Intent, ActivityResult> activityLauncher = BetterActivityResult.registerActivityForResult(this); }
Last that, you tin merely motorboat an act from immoderate kid actions similar this:
national void openSomeActivityForResult() { Intent intent = fresh Intent(this, SomeActivity.people); activityLauncher.motorboat(intent, consequence -> { if (consequence.getResultCode() == Act.RESULT_OK) { // Location are nary petition codes Intent information = consequence.getData(); doSomeOperations(); } }) }
Since you tin fit the callback relation on with the Intent
, you tin reuse it for immoderate actions.
Likewise, you tin besides usage another act contracts utilizing the another 2 constructors.