I’m trying to dispose and restart an OpenGLView or AndroidGameView within the same Activity, but it seems the game can’t start another time after disposed inside the same Activity. Here is my test using monodroid game sample project:
GLView1 view;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create our OpenGL view, and display it
//view = new GLView1(this);
//SetContentView(view);
Timer timer = new Timer(OnTimerDone, this, 3000, 3000);
}
void OnTimerDone(object state)
{
System.Diagnostics.Debug.WriteLine("timer");
((Activity)state).RunOnUiThread(() =>
{
if (view != null)
{
//view.Stop();
view.Dispose();
view = null;
SetContentView(null);
GC.Collect();
}
else
{
view = new GLView1((Activity)state);
//view.Resume();
SetContentView(view);
}
});
}
//protected override void OnPause()
//{
// base.OnPause();
// view.Pause();
//}
//protected override void OnResume()
//{
// base.OnResume();
// view.Resume();
//}
Thanks in advance for your help.
Update with my new code to avoid reuse SetContentView:
GLView1 view;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create our OpenGL view, and display it
//view = new GLView1(this);
//SetContentView(view);
SetContentView(Resource.Layout.Main);
Timer timer = new Timer(OnTimerDone, this, 3000, 3000);
}
void OnTimerDone(object state)
{
((Activity)state).RunOnUiThread(() =>
{
LinearLayout linearLayoutMain = ((Activity)state).FindViewById<LinearLayout>(Resource.Id.linearLayoutMain);
if (view != null)
{
System.Diagnostics.Debug.WriteLine("timer delete");
linearLayoutMain.RemoveView(view);
try
{
view.Stop();
view.Dispose();
view = null;
//SetContentView(null);
GC.Collect();
}
catch (Exception ex)
{
//Android.Util.Log.Debug("ex:", ex.ToString());
System.Diagnostics.Debug.WriteLine("ex:" + ex);
}
}
else
{
view = new GLView1((Activity)state);
view.Run();
//view.Resume();
//SetContentView(view);
linearLayoutMain.AddView(view);
System.Diagnostics.Debug.WriteLine("timer create");
}
});
}
I had a play around with your code and found that the
Timerwas still running but the block insideRunOnUiThread()wasn’t being called. I removed theview.Stop()method and theview.Dispose()and it started working correctly.Here is my full code (using a 5000ms interval for the time)
The old View appears to still be garbage-collected (see in the log below). I don’t think the extra calls were necessary. I ran the application for about 15 minutes straight with no issues.