Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run method once per app start?

Tags:

android

Hey I would like to know how I can run a method say, refreshChannel(); in an onCreate in one of my Activities only once, until the application is killed or restarted?.

like image 986
Aashir Avatar asked Oct 16 '13 22:10

Aashir


2 Answers

You can extend Application and run that method in the onCreate of your custom application class. This is only run once per application start-up.

For example:

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // Your methods here...
    }
}

Note that this should not be long-running. If it's going to take some time, do it in an AsyncTask.

Last of all, you need to tell Android you have a custom Application class. You do this in your manifest by referencing your application class in the android:name attribute of the application tag:

<manifest ... >
    <application
        android:name=".MyApp"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity>
            ...
        </activity>
    </application>
</manifest>
like image 61
Adam S Avatar answered Nov 02 '22 05:11

Adam S


You can subclass the application class. Then override the onCreate method in the subclass of the Application class. Add a field to the application subclass.

public class SubApplication extends Application {
public boolean hasRefreshed;
        @Override
    public void onCreate() {
        super.onCreate();
        hasRefreshed=false;
    }
}

Then when you execute on your Activity:

SubApplication app = (SubApplication ) context
                    .getApplicationContext();
if(app.hasRefreshed){
//do nothing
}else{
refresh();
app.hasRefreshed=true;
}

Last, add this line to your manifest so the system knows to use the subclass.

<application
        android:name=".SubApplication "
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity>
            ...
        </activity>
    </application>
like image 22
wtsang02 Avatar answered Nov 02 '22 06:11

wtsang02