I have a very large project that happens to need to be able to access the Activity Context regularly outside of the Activity class, of which there will only ever be a single instance. I've done a lot of research trying to hammer out the code but there doesn't seem to be a good clean way to access the context and/or activity when needed. It can't be stored in other classes and it shouldn't passed around, as both can cause memory leaks. But can the context and a reference to the activity be stored statically within the activity class itself? If the activity is destroyed, the context/reference will go away too, so there shouldn't be a problem, just like how it would if the application context were stored... is this right?
My main issue is that I have hundreds if not thousands of random objects such as textures, sprites, meshes, scripts, and whatnot, that not only need the context at times (such as loading and renedring), but they need to be preserved/reconstructed across configuration state changes and such using ViewModel, and I want to preserve the object-oriented nature and not put everything in one place (ie, the activity). Most of the data I want to store is Model data and not View data, so keeping it in View breaks the whole OO model of separation. So I'm trying to make each class life-cycle aware, but I need the activity reference to do it:
public class RendererActivity extends AppCompatActivity
{
static Context activityContex = null;
static RendererActivity activityReference = null;
...
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
activityContext = this;
activityReference = this;
}
}
class Texture
{
static List textureList = null;
Texture( )
{
// check if list allocated
if(textureList == null) textureList = ViewModelProviders.of(RendererActivity.ActivityReference).get(Texture.List.class);
...
}
public class List extends ViewModel
{
...
}
}
This seems to work perfectly and keeps the OO model clean. I just don't know it it's a good thing to do under the Android framework. I haven't noticed any memory leaks, but it's the potential issues I'm worried about. Any ideas and/or suggestions would be much appreciated.