gpt4 book ai didi

java - Android后台任务-如何访问返回值

转载 作者:行者123 更新时间:2023-12-01 08:58:52 24 4
gpt4 key购买 nike

当后台任务返回一个值时,如何从另一个类访问它。只是使用它作为示例代码,但我想要的是后台任务执行某些操作并返回一个值。

protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
// Do your long operations here and return the result
int time = Integer.parseInt(params[0]);

// Sleeping for given time period
Thread.sleep(time);
resp = "Slept for " + time + " milliseconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}

**return resp;**
}

最佳答案

为此,您需要扩展 asynktask 类,例如

extends AsyncTask<String, String, String>

@Override
protected void onPostExecute(String result) {
//heare result is value you return from doInBackground() method
//this is work on UI thread
}

类看起来像

public class AsyncTaskGetResult extends AsyncTask<String, String, String> {

PrintListner mPrintListner ;
private AsyncTaskGetResult (PrintListner mPrintListner) {
this.mPrintListner = mPrintListner;

}

@Override
protected void onPreExecute() {
super.onPreExecute();

}
@Override
protected String doInBackground(String... params) {
return result;
}

@Override
protected void onPostExecute(String result) {
//heare result is value you return from doInBackground() method
//this is work on UI thread
this.mPrintListner.getResult(result);
}

}

public interface PrintListner {
public void getResult(String receiptItem);
}

如果您需要在另一个类中访问它,您可以为此编写监听器并在您的 Activity 中实现

public class MyActivity extends Activity implements PrintListner{

@Override
public void getResult(String receiptItem){
//Do whatever you want
}
}

并像 new AsyncTaskGetResult(this).execute(yourString); 那样调用它

关于java - Android后台任务-如何访问返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41852217/

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