Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS AppDelegate equivalent in Android

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.

like image 701
SundayMonday Avatar asked Aug 06 '12 14:08

SundayMonday


People also ask

What is iOS AppDelegate?

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.

Which method of AppDelegate is called first in iOS?

AppDelegate. UIViewController is allocated as the window's initial view controller. To make the window visible, makeKeyAndVisible method is called.


2 Answers

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

like image 147
Alexey Avatar answered Sep 22 '22 14:09

Alexey


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

like image 33
Manuel Avatar answered Sep 21 '22 14:09

Manuel