如何在Android中同步AsyncTask doInBackground()方法中的语句
我已经编写了如下代码 公共类SplashScreen扩展了BaseActivity{如何在Android中同步AsyncTask doInBackground()方法中的语句,android,android-asynctask,Android,Android Asynctask,我已经编写了如下代码 公共类SplashScreen扩展了BaseActivity{ public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); new DownloadPlistTask().execute("background","Progress","yes"); } private class DownloadPlistTask extends Asyn
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
new DownloadPlistTask().execute("background","Progress","yes");
}
private class DownloadPlistTask extends AsyncTask<String,String,String>{
protected String doInBackground(String... dummy){
return compareLocRemPlist();
}
protected void onProgressUpdate(String... progress){
//some code here.
}
protected void onPostExecute(String result){
//handle return type from doInBackground.
}
public String compareData(){
final Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run(){
//code regarding webservices.
if(boolValue){
//if the boolValue from the webservice is true,cancel the timer.
timer.cancel();
}
},5*60*1000,5*60*1000);
return "finish";
}
}
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
新建DownloadPlistTask()。执行(“后台”、“进度”、“是”);
}
私有类DownloadPlistTask扩展了AsyncTask{
受保护的字符串doInBackground(字符串…虚拟){
返回compareLocReplist();
}
受保护的void onProgressUpdate(字符串…进度){
//这里有一些代码。
}
受保护的void onPostExecute(字符串结果){
//doInBackground中的句柄返回类型。
}
公共字符串compareData(){
最终计时器=新计时器();
timer.schedule(新TimerTask(){
公开募捐{
//关于Web服务的代码。
if(布尔值){
//如果webservice中的布尔值为true,则取消计时器。
timer.cancel();
}
},5*60*1000,5*60*1000);
返回“完成”;
}
}
}
在上面的代码中,onCreate()iam在doInBackground中调用AsyncTask doInBackground iam在compareData()中调用名为compareData()的方法方法iam使用计时器。计时器发送对Web服务的请求,在Web服务iam中获取一个布尔值,如果为true,我需要返回finish。如果为false,我不想返回finish,我应该留在compareData()中方法,并每隔五分钟发送一次请求,直到我得到true。但当计时器等待这五分钟时,在这段时间内,计时器被执行后的语句和返回值finish返回到doInBackground,控件将返回onPostExecute()但是在后台计时器正在运行。当我取消计时器时,如何返回finish(完成)因为您正在
doInBackground
中运行它,所以您可以同步执行检查。因此,您可以使用Thread.sleep
方法代替计时器
static final long RETRY_DURATION = 5*60*1000;
public String compareData(){
boolean boolValue = false;
do{
//code regarding webservices.
if(!boolValue){
try{
Thread.sleep(RETRY_DURATION);
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
}while(!boolValue);
return "finish";
}
非常感谢我会尽力让你知道的