gpt4 book ai didi

Java 在执行 Activity 中的代码之前等待线程(在另一个类中)完成

转载 作者:太空宇宙 更新时间:2023-11-04 13:28:59 25 4
gpt4 key购买 nike

在我的 Android 应用程序中,我试图创建一个类似于 ios 委托(delegate)功能的情况。

(在 ios-> 中)调用执行检查的类,完成检查后,它将使用委托(delegate)重定向回 View Controller 并执行下一个功能。

这是我的类(class)

public class Checking{
private boolean flag;

public boolean getFlag(){
return flag;
}

public void checkFunction(){
//..... check database

if(need to do call webservice){
Thread thread = new Thread(){
@Override
public void run(){
// Perform webservice calling
}
};
thread.start();
}
else{
//end
}
}
}
<小时/>

这是我的 Activity

public class ActivityA extends Activity{
@Override
public void onResume(){
doChecking();
}

public void doChecking(){
Checking check = new Checking();
check.checkFunction();

// should finish preform checking in Checking class before proceed
if(check.getFlag()){
// perform next function
}
else{
// show alert
}
}
}

问题在于,在调用 Checking 类之后,它立即执行函数调用下面的 if else 。在某些情况下,检查类中的检查尚未完成并显示空警报。该线程可能启动也可能不启动,具体取决于数据库检查。

有人可以为我提供解决方案来克服这个问题吗?我知道调用 Checking 类后缺少一些内容,但我不太确定将其放在那里才能实现结果。

提前致谢。

最佳答案

您基本上想要做的是点击网络服务,然后等待直到获得网络服务的响应。

首先,您不需要创建自己的线程来访问网络服务。相反,您可以使用 AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

下面是AsyncTask的代码

class MyAsync extends AsyncTask<Void, Void, Void> {

@Override
protected Void doInBackground(Void... arg0) {
//Hit your web service here
}

@Override
protected void onPostExecute(final Void unused) {
//Process the result here
}

}

如果您想限制用户访问该应用程序,直到网络服务被访问。您可以通过其他方法显示对话框,如下所示:

class MyAsync extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {
loadingDialog.setMessage("Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();
}

@Override
protected Void doInBackground(Void... arg0) {
//Hit your web service here
}

@Override
protected void onPostExecute(final Void unused) {
if (loadingDialog.isShowing()) {
loadingDialog.dismiss();
}
//Process the result here
}

}

关于Java 在执行 Activity 中的代码之前等待线程(在另一个类中)完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371706/

25 4 0
文章推荐: java - 如何实现Oauth 2.0客户端处理在数据库中存储refreshToken?
文章推荐: c# - 单击按钮停止刷新页面
文章推荐: html - 将
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com