gpt4 book ai didi

java - 如何从可运行线程中获取局部变量

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:12 24 4
gpt4 key购买 nike

我有一个帮助程序(不是 Activity )类,它对 API 进行查询,该 API 具有一个名为 run() 的公共(public)函数。并在新线程上运行(根据 Android 规范)。我的MainActivity创建一个新的 MakeQuery对象并运行其 run()功能:

MakeQuery q = new MakeQuery();
q.run();

但是,我需要从线程中访问一个变量。下面是一个简短的代码示例:

public class MakeQuery implements Runnable {

private void setNewString(String localThreadString){
//NewString comes out null...
NewString = localThreadString;
}

public void run() {
new Thread(new Runnable() {
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

API Api = new API(keys and tokens);

//queryAPI() returns string
setNewString(queryAPI(Api, term1, term2));

//Don't know how to send intent from here (No context),
//I would like:
Intent i = new Intent(MainActivity.class, AnotherActivity.class)
}
}).start();
}

异步任务

//This runs in background thread
@Override
protected Void doInBackground(Void... params) {
API Api = new API(keys and tokens);

setNewString(queryAPI(Api, string1, string2));

return null;
}

@Override
protected void onPostExecute(Void aVoid) {
Intent intent = new Intent(mContext, Activity2.class);
intent.putExtra("NewString", NewString);
Log.d(MYTAG, NewString);
}

主要 Activity

public void buttonPressed(View view) {
Intent intent = new Intent(this, Activity2.class);
...
MakeQuery task = new MakeQuery(this);
task.execute();

startActivity(intent);
}

我尝试在线查看了几个小时。我试过做AsyncTask ,但我不确定如何用我所拥有的实现它。此外,使用 localThread<String>没有帮助。

TLDR:我想知道是否可以获取 NewString,以便我可以通过 Intent 将其传递给另一个 Activity。

解决方案不要使用 Runnable , 创建一个新的 AsyncTask如下所示。另外,确保 StartActivity在辅助类中而不在 MainActivity 中.这是因为在开始新 Activity 之前我没有等待任务完成。

最佳答案

这是一个使用异步任务的实现:

public class MakeQueryTask extends AsyncTask<Void, Void, Void> {

private Context mContext;

private String newString;

public MakeQueryTask(Context context) {
mContext = context;
}

//This runs on a background thread
@Override
protected Void doInBackground(Void... params) {


API Api = new API(keys and tokens);

//queryAPI() returns string
setNewString(queryAPI(Api, term1, term2));

//You should start your activity on main thread. Do it in onPostExecute() which will be invoked after the background thread is done
//Intent i = new Intent(mContext, AnotherActivity.class);
//mContext.startActivity(intent);
return null;
}

private void setNewString(String localThreadString){
newString = localThreadString;
}

//This will run on UI thread
@Override
protected void onPostExecute(Void aVoid) {
Intent intent = new Intent(mContext, AnotherActivity.class);
mContext.startActivity(intent);
}
}

你会这样执行:

 MakeQueryTask task = new MakeQueryTask(this); //Here this is an activity (context)
task.execute();

关于java - 如何从可运行线程中获取局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30359961/

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