How to return a result (startActivityForResult) from a TabHost Activity?

后端 未结 5 1878
悲哀的现实
悲哀的现实 2020-11-22 12:40

I have 3 classes in my example: Class A, the main activity. Class A calls a startActivityForResult:

Intent intent = new Intent(this, ClassB.class);
startAct         


        
5条回答
  •  情书的邮戳
    2020-11-22 13:32

    Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

    If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

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

    So my solution is to set result to the parent activity if present, like that:

    Intent data = new Intent();
     [...]
    if (getParent() == null) {
        setResult(Activity.RESULT_OK, data);
    } else {
        getParent().setResult(Activity.RESULT_OK, data);
    }
    finish();
    

    I hope that will be helpful if someone looks for this problem workaround again.

提交回复
热议问题