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?.
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>
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>
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