问题
in my application I have 3 activities. First one -the main from which I start activity #2. From #2 I start #3 and at the same time I finish #2. When I finish #3 I automatically come back to #1. Question: How can I add/run code when coming back from 3 to 1?
not sure if it makes sense. But what I want to do is, when ending #3 and coming back to #1 I want to check if file xyz exists and based on it to change UI in activity #1.
OnResume in #1 is not ran, never. (Probably system doesn't run onpause for this first activity)
If there was only activity #1 and 2 I could use startActivityForResult. But two activities don't do what I need...
回答1:
See below example.
your activity#1 code is like this
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
//Do your code here
}
}
Your activity#3 code is like this
public class Activity3 extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity3);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
}
回答2:
From activity #1, don't start activity #2. Instead, start activity #3, passing a flag in the intent to tell activity #3 to start activity #2. If activity #3 calls startActivity
from inside onCreate
, there will be no screen flicker. That way, activity #1 can use startActivityForResult
and get the result back from activity #3.
It's a bit of a kludge, but it works nicely.
回答3:
There are multiple aspects to consider:
Why is in #1 onPause()/onResume() not called? Are you sure about this? It's very unlikely. The Android documentation says about onPause():
(...) When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, (...)
It seems to me that you should consider to look into using fragments instead of multiple activities.
- A quick-fix could be to call startActivity for #1 when finishing #3. You only have to make sure that the launch mode for #1 is set to singleTop.
回答4:
Make a Method on Your Acivity 1:
public void changeViewsMethod(){
textView.setText("demo");
}
Now On Your Activty 2 do this :
@Override
public void onBackPressed() {
super.onBackPressed();
((YOU_ACTIVITY1) getApplicationContext()).changeViewsMethod();
}
Hope it will work.
回答5:
You could write a Preference Variable in OnPause of Activity #3 (something like Activity3Finished=true) Now you can check in every Activity if Activity #3 has finished.
Dont forget to reset the Variable in OnCreate of #3.
来源:https://stackoverflow.com/questions/13220091/how-to-run-code-when-coming-back-to-activity