Reputation: 2621
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?.
Upvotes: 5
Views: 11009
Reputation: 18863
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>
Upvotes: 3
Reputation: 16394
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>
Upvotes: 11