I am currently learning to code for Android, and I have some troubles to understand how to correctly connect to APIs, or in my particular case to Google fit API.
In the example provided by Google developers, they connect to API in onCreate() method. However, I was thinking if it was the best practice when developing a more complex application, and when it is ok to leave the code connecting to the API in the activity class? To be more specific, when this should be moved to other threads? I am concerned about performance issues keeping the code this way - on the other hands, is it possible that if I move this code to other threads, I may face some connection issues related to android service killing when running in the background?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FitnessOptions fitnessOptions = FitnessOptions.builder()
.addDataType(TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.addDataType(DataType.AGGREGATE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.build();
if (!GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this), fitnessOptions)) {
GoogleSignIn.requestPermissions(
this,
REQUEST_OAUTH_REQUEST_CODE,
GoogleSignIn.getLastSignedInAccount(this),
fitnessOptions);
} else {
accessGoogleFit();
}
}
I apologies in advance if my question looks stupid and basic, but I am very keen to learn more about best practices when it comes to coding and understand how to develop working applications!
To give you a better understanding, USUALLY any example given by google (or most people really) is in its most simple form just to give you an understanding of the code or the framework, how you decide to implement it best is up to you, which you will gain from experience.
To further answer your question, it really depends on the situation. Leaving the api call in the create of the activity is probably fine if your activity isn't going to be created or recreated a number of times (even if it IS destroyed and recreated, it still might be fine depending on the situation), but yes, ideally this call should be moved out to different threads, using something like RxJava or other threading techniques. The reason for this is because (when api calls are done on a main thread) it could potentially suspend your entire app until that api call returns with information, which is bad practice and will give you a lot of problems. Moving this code out to different theads will not worsen performance (quite the opposite) and you should probably try to implement this code is some form of thread.