Is it safe to finish an android activity from a background thread?

后端 未结 2 2236
醉梦人生
醉梦人生 2021-02-20 04:09

In Android, is it safe to call Activity.finish() from a background thread, or can it only called from the main thread? The documentation doesn\'t mention anything a

2条回答
  •  忘了有多久
    2021-02-20 05:00

    No, it is not.

    The code uses at least one variable, mFinished, without synchronization. Full stop.

       public void finish() {
        if (mParent == null) {
            int resultCode;
            Intent resultData;
            synchronized (this) {
                resultCode = mResultCode;
                resultData = mResultData;
            }
            if (false) Log.v(TAG, "Finishing self: token=" + mToken);
            try {
                if (resultData != null) {
                    resultData.setAllowFds(false);
                }
                if (ActivityManagerNative.getDefault()
                    .finishActivity(mToken, resultCode, resultData)) {
                    mFinished = true;
                }
            } catch (RemoteException e) {
                // Empty
            }
        } else {
            mParent.finishFromChild(this);
        }
    }
    

提交回复
热议问题