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

放肆的年华 提交于 2020-06-10 09:24: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 about thread safety of this method.


回答1:


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);
    }
}



回答2:


Probably the result could be unexpected. I'd use a Handler or some other way to send to the activity the order to kill itself in the next iteration.



来源:https://stackoverflow.com/questions/20412871/is-it-safe-to-finish-an-android-activity-from-a-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!