I have a simple Android app with one Activity. This Activity downloads a small XML file and displays the contents to the user. Currently I kick-off the download in the Activity's onStart
method.
It's my understanding that Activities are destroyed and re-created when the device orientation changes. So when users rotate my app the XML file is downloaded again. I'd like the app to download the file just once as it doesn't change more than a few times per day. Hence I'd like some object to retain the downloaded data so the local data can be re-used when the device orientation changes. What's the ideal object in Android to retain the data?
On iOS I'd use the AppDelegate
to download the data once and retain it. Then the viewController that displays the data can just re-use the local data should it be destroyed and re-created.
So an app delegate is an object that the application object can use to do certain things like display the first window or view when the app starts up, handle outside notifications or save data when the app goes into the background.
AppDelegate. UIViewController is allocated as the window's initial view controller. To make the window visible, makeKeyAndVisible method is called.
You have to create your own subclass of Application and specify it in the AndroidManifest.xml. After that the new instance of this class will be created and can be accessed throughout your application.
Example:
Manifest.xml
<application name="YourApp">
YourApp.java
public class YourApp extends Application {
private String yourState;
public void setState(String state){
yourState = state;
}
public String getState(){
return yourState;
}
}
YourActivity.java
public class YourActivity extends Activity {
@Override
public void onCreate(Bundle bundle){
YourApp appState = ((YourApp)getApplicationContext());// you can use getApplication() as well in the activity
String state = appState.getState();
}
}
More info about Application
Make your main class implement ProcessLifecycleObserver
.
It is the equivalent of the AppDelegate in iOS as it "summarizes" activity handlers like onCreate
, onResume
on an app-process basis.
https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With