简体   繁体   中英

Android Java Identify “this.” or child class calling in a parent function

In my parent class :

// ParentActivity.java
@Override
protected void onResume() {

    if (this instanceof ParentActivity) connectToGoogleAnalytic("parent");

    // do something else

    super.onResume();
}

In child class:

// ChildActivity.java extent ParentActivity
@Override
public void onResume() {
    if (this instanceof ChildActivity) connectToGoogleAnalytic("child");
    super.onResume();
}

The case is if the activity is ChildActivity , then when calling onResume , it will call the ParentActivity's onResume as well, instead of calling ChildActivity's onResume and mess up the analytics' data. I tried using instanceof to check if this equals ParentActivity but it is not working.

If ChildActivity extends ParentActivity then an instance of ChildActivity is both a ChildActivity and a ParentActivity.

Since you're calling super.onResume you can just remove

if (this instanceof ChildActivity) connectToGoogleAnalytic();

from ChildActivity.onResume

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