简体   繁体   中英

OnStart () is called after OnStop() and that is making problems for my aplication

First I would like to say that I am sorry for the vague title. I didn't know what else to name this question.

I have 2 activities (ActivityA, ActivityB). In ActivityA I have overridden the onStop() function and I change value X in a singleton. When I go to ActivityB and onStart() is called I check the value X. The problem is that onStart() is called before onStop() and the value I check in the onStart() function is still the old value before onStop() changes it.

I know why onStart() is called before onStop() . What I am asking you guys is an alternative solution to this problem I am currently having.

I need to save a value in ActivityA before I close it and I need to check for the same value in ActivityB. ActivityB can be accessed from several other activities not just ActivityA. And the otehr activities dont change the value.

SOLVED I changed onStop() to onPause() That worked. Thanks guys!

don't use singletons. Activities have the Intent to be used as a communication channel between them.

do like this, in activity A:

Intent i = new Intent(this, ActivityB.class);
i.putExtra("value", 10);
startActivity(i);

then in activity B, you do (at any point you want):

int value = getIntent.getIntExtra("value", 0);

also works for double, string, float, bundle, arrays, etc, as seen in the docs!

Its entirely upto the system to call these methods, better would be to use onPause(); and onResume();

在此处输入图片说明

See what the Official Docs say here

The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM