Charlie Collins gave me a perfect answer using the Application.class
. I was not aware that we could subclass it that easily. Here is a simplified example using a custom application class.
AndroidManifest.xml
Give the android:name
attribute to use your own application class.
...
<application android:name="MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
....
MyApplication.java
Use this as a global reference holder. It works fine within a same process.
public class MyApplication extends Application {
private MainActivity mainActivity;
@Override
public void onCreate() {
super.onCreate();
}
public void setMainActivity(MainActivity activity) { this.mainActivity=activity; }
public MainActivity getMainActivity() { return mainActivity; }
}
MainActivity.java
Set the global "singleton" reference to the application instance.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication)getApplication()).setMainActivity(this);
}
...
}
MyPreferences.java
A simple example where I use a main activity from another activity instance.
public class MyPreferences extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (!key.equals("autostart")) {
((MyApplication)getApplication()).getMainActivity().refreshUI();
}
}
}