简体   繁体   中英

Android instance of parent activity

I have 2 activities, A & B for example. I navigate to Activity B within Activity A using startActivity()

My question is when I'm on Activity B, how can I get access to activity A ?

Thanks,

To access functionality that is shared between Activities, it is a best practice to move that functionality to an Application class, or some other form of Singleton. The reason for that is the activity lifecycle does not allow you to be certain that the exited activity still exists while the focused activity is running. So you need to use an object that is able to be persistent between activities, even of Activity.finish() is called on either activity.

Here is documentation on the Application class. http://developer.android.com/reference/android/app/Application.html

You can access the application from within any activity by calling

this.getApplication();

It really depends on what you want to do, and why you think you need that access. One thing you can do is pass data into an activity using intent.putExtra and then startActivityForResult and listen for results in onActivityResult . Can you give more information on what exactly you want to do?

To perform a method when an activity finishes, call the 'child' activity like this:

Intent child = new Intent(this, ChildActivity.class);
startActivityForResult(child, CHILD_CODE);

where CHILD_CODE is a nonnegative integer field. Now, you have to set a result in the 'child' activity (the one you started with onActivityResult ).

    Intent resultIntent = new Intent();
    setResult(Activity.RESULT_OK, resultIntent);
    finish();

now in your 'parent' activity, implement the onActivityResult method like this:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case CHILD_CODE:
        if (resultCode == Activity.RESULT_OK) {
            yourMethod();
        }
    }
}

为什么不使用Actvity可以访问的单例类?

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