将数据从线程传递到Activity

时间:2010-06-12 17:38:05

标签: android multithreading communication android-activity

我想将数据从Thread传递回Activity(创建线程)。

所以我在Android documentation上描述的那样:

public class MyActivity extends Activity {

    [ . . . ]
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        [ . . . ]
    }

    protected void startLongRunningOperation() {

        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
                mResults = doSomethingExpensive();
                mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }

    private void updateResultsInUi() {

        // Back in the UI thread -- update our UI elements based on the data in mResults
        [ . . . ]
    }
}

我在这里只缺少一件事 - 应该在哪里以及如何定义mResults,以便我可以从ActivityThread访问它,并且还可以根据需要进行修改?如果我在final中将其定义为MyActivity,我无法在Thread中更改它 - 正如示例中所示...

谢谢!

1 个答案:

答案 0 :(得分:2)

如果在类中定义mResults而不是方法,则可以从任一位置更改它。例如:

protected Object mResults = null;

(使用受保护,因为it's faster