Shuyun6
Shuyun6

Reputation: 191

After Activity.onDestroy() method, why I can still get this activity's instance?

I have created a class to cache Activities, like:

public class ActivityList {

    public static List<WeakReference<Activity>> list = new LinkedList<>();

    public static void put(Activity activity) {
        list.add(new WeakReference<>(activity));
    }

}

and, the onDestroy method:

@Override
protected void onDestroy() {
    super.onDestroy();
    Log..e("test", "call onDestroy");
}

Secondly, I enable the "Don't keep activities" in System's developer options, to make sure an activity will be killed after I left

Then, I start an Activity and put an instance into then ActivityList class

ActivityList.put(this);

When I left this activity to another activity, the LogCat shows the first activity called onDestroy(). Then in then second activity, I get the first activity's instance like:

WeakReference<Activity> weakReference = ActivityList.list.get(0);
Activity activity = weakReference.get();
activity.runOnUiThread(() -> Toast.makeText(this, "HHHH", Toast.LENGTH_SHORT).show());

Then code works well ?! In my view, the first activity called onDestroy() then I cannot use it anymore, so the Toast should NOT show. AND after onDestroy(), there are no any strong references refer to the activity, it should be GC by system.

So, Why does it work?

Upvotes: 0

Views: 116

Answers (1)

JiajiaGu
JiajiaGu

Reputation: 1339

Weak references should be cleared at Garbage Collection,but finish an activity may not trigger GC.

Upvotes: 1

Related Questions