gpt4 book ai didi

android - 如何从android中的线程获取结果?

转载 作者:太空狗 更新时间:2023-10-29 12:42:07 26 4
gpt4 key购买 nike

我有一个主类,一个工作线程类,它们是分开的。在主线程中,我将输入传递给工作线程并要求它工作。完成后,我希望它将结果发送回主线程。我该怎么做?

public class MainActivity extends Activity{
Handler showResults = new Handler(){
public void handleMessage(Message msg){
//Show results on textview.
}

workerThread worker = new workThread();
worker.setInput(input);
}

}

工作线程:

public class workerThread extends Thread{
int result = 0;
public void run(){
//when receive input from main class. it will work
.............
//after working, it return result, and i want it to send this result
//to Handler in main activity, so, i can display that result on textview.
}

//function to get input
public void setInput(){
//get input form main class to work
}
}

谁知道答案请告诉我。谢谢。:)

最佳答案

也许你应该试试 AsynTask,它就是为此而设计的:

 private class MyThread extends AsyncTask<Params, Progress, Result> {
protected Long doInBackground(URL... urls) {
// Calculate and return retulst
}


protected void onPostExecute(Long result) {
// This is executed in main Thread, use the result
}
}

你像这样执行这个线程:

new MyThread().execute(params, ...);

参见 http://developer.android.com/reference/android/os/AsyncTask.html

关于android - 如何从android中的线程获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24104271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com