我正在尝试在同一个Activity中处理并重新启动OpenGLView或AndroidGameView,但似乎游戏在放入同一个Activity后无法再启动。这是我使用monodroid游戏示例项目的测试:
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();
//}
提前感谢您的帮助。
使用我的新代码进行更新以避免重用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");
}
});
}
答案 0 :(得分:1)
我玩了你的代码,发现Timer
仍在运行,但RunOnUiThread()
内的块未被调用。我删除了view.Stop()
方法和view.Dispose()
,它开始正常运行。
这是我的完整代码(当时使用5000毫秒间隔)
GLView1 view;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Timer timer = new Timer(OnTimerDone, this, 5000, 5000);
}
void OnTimerDone(object state)
{
RunOnUiThread(() =>
{
try
{
LinearLayout linearLayoutMain = ((Activity)state).FindViewById<LinearLayout>(Resource.Id.linearLayoutMain);
if (view != null)
{
linearLayoutMain.RemoveView(view);
view = null;
}
else
{
view = new GLView1(this);
view.Run();
linearLayoutMain.AddView(view);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
});
}
旧视图似乎仍然是垃圾回收(请参阅下面的日志)。我不认为额外的电话是必要的。我没有遇到任何问题,直接运行了大约15分钟。
11-16 00:30:05.828 D/dalvikvm( 2144): GC_EXPLICIT freed 119K, 6% free 8813K/9351K, paused 3ms+5ms, total 56ms
11-16 00:30:08.047 D/dalvikvm( 2144): GC_CONCURRENT freed 992K, 12% free 8270K/9351K, paused 4ms+36ms, total 162ms
11-16 00:30:10.667 D/dalvikvm( 2144): GC_CONCURRENT freed 202K, 10% free 8467K/9351K, paused 5ms+63ms, total 116ms