StrictMode activity instance count violation (2 instances, 1 expected) on rotation of completely empty activity

前端 未结 3 1130
一生所求
一生所求 2020-12-07 19:31

Relevant only in that it motivates eliminating any false positives from strict mode, since the continued presence of any makes the death penalty impractical

Over t

3条回答
  •  庸人自扰
    2020-12-07 20:10

    I am not an Android developer so this is a bit of a shot in the dark.

    Presumably since the behaviour is not consistent for other activities, but is triggered nonetheless by a completely trivial one, the issue is down to the time taken for onCreate to complete.

    If onCreate can complete before the pause/stop/destroy sequence is finished (and eventual garbage collection though it need not get quite to that point afaics) for the old activity then there really will be two instances present.

    A simple solution to prevent this is for the activity to have a static atomicboolean "ready" (initially false) that check before doing anything else in onCreate where you'd loop

    while(!ready.compareAndSet(false, true)) {
        //sleep a bit
    }
    

    then override the ondestroy lifecycle callback and invoke ready.compareAndSet(true, false)

    Apologies if this approach is utterly naive.

提交回复
热议问题