public class GenericApp extends Application {
// hold the reference to some global object here
private CustomObj myObjRef;
public void onCreate() {
...
// initialize it only once!
myObjRef = new CustomObj();
...
}
public CustomObj getMyObjReference() {
return myObjRef;
}
}
Then in each Activity
:
public class ActivityXXX extends Activity {
private CustomObj savedObjRef;
public void onCreate() {
...
savedObjRef = ((GenericApp) getApplication()).getMyObjReference();
...
}
}
The reason why I need this is I want to create custom object only once and hold somewhere its reference so that it won't be destroyed when I switch between activities. Each activity runs in its own process (to prevent specific memory leaks; do not suggest me to use the same process instead).
But, as explained there, due to process dependence, each Activity
starts in different Application
. My custom object is too heavy to be Serializable
.
Can I declare to use one Application
instance for all processes? I think it's impossible. If so, how can I be sure to create only one instance of my custom object to be synchronized by it later among all activities?
Use case: opening Camera
each time onResume()
is called and closing it in Activity's
onPause()
. Since opening and closing Camera
performs in separate Thread
and takes ~300 ms, sometimes Camera
doesn't manage to release itself properly in previous Activity
before it begins opening via another AsyncTask
in another Activity
.
Note. I've already tried:
- Fragments
- common process
- Serializable / Parcelable
I think background Service
with its own process (android:process=":detector"
) can handle my task. But since each process spawns new Application
, should I consider my Service
to be local or remote? Should I use ResultReceiver
or BroadcastReceiver
?
Update. Simple approach, described above doesn't work. My AndroidManifest.xml (shortened):
<application android:name=".GenericApp">
<activity android:name=".ActivityOne"
android:process="process1" />
<activity android:name=".ActivityTwo"
android:process="process2" />
</application>