我有一个设置为启动Java活动(称为MyJavaActivity)的android应用,这反过来又会启动NativeActivity。NativeActivity完成后,它将返回到MyJavaActivity。
我还有一个Java单例类(称为MyJavaSingleton),我希望在应用程序的整个生命周期中都将其保留在内存中。我从NativeActivity(使用JNI)中设置了一些单例类的成员变量,以后可以由MyJavaActivity检索。
问题是,MyJavaSingleton实例似乎一直在内存中,直到NativeActive退出为止,但是当MyJavaActivity再次启动时,似乎又以某种方式再次设置为null,因此我在NativeActivity中设置的所有变量现在都重置为其默认值。为什么会这样?
public class MyJavaActivity extends Activity implements View.OnTouchListener
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MyJavaSingleton.Instance().DoStuff();
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
Intent intent = new Intent(MyJavaActivity.this, NativeActivity.class);
startActivity(intent); // at this point, android_main will be executed
}
}
/
public class MyJavaSingleton
{
static private MyJavaSingleton mInstance = null;
synchronized public static MyJavaSingleton Instance()
{
if( mInstance == null )
{
mInstance = new MyJavaSingleton();
Log.v(TAG, "New MyJavaSIngleton instance");
}
return mInstance;
}
}
/
// Native
void android_main(struct android_app* state)
{
// Do various stuff, set some variables on the MyJavaSingleton
// At this point, MyJavaSingleton.mInstance is still at the same address in memory, which is good //
ANativeActivity_finish(state->activity);
exit(0);
// Problem: sometime after this exit and before MyJavaActivity::onCreate is called, MyJavaSingleton.mInstance is set to null!
}
在上面的代码提取中,在首次启动应用程序时打印“ New
MyJavaSIngleton实例”,然后在NativeActivity退出后(即,在android_main退出之后)再次打印,并再次调用MyJavaActivity的onCreate。
重新输入MyJavaActivity时,为什么MyJavaSingleton.mInstance变为NULL?