2013-01-03 39 views
0

您好我在Android中有一个服务,它处理HTTP方法POST,如下所述。现在,我需要调用的意图在Android中的服务中的HTTP响应

replaceResourceSegment()

方法。它有一个处理程序,需要将近90秒才能完成任务。在那段时间内,控制权会退出处理程序块。但我希望我的程序在POST的处理程序中继续。总之,我希望我的服务在POST处理程序中暂停一段时间,直到我的Intent(使用处理程序)完成其执行,并且需要延迟发送HTTP Post的响应。有人可以指导我如何做到这一点?

if(method.equals("POST")) 
     { 
     conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);    
     HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();   
     String content_type = ""+entity.getContentType(); 
     JSONReceived = EntityUtils.toString(entity); 
     if(content_type.contains("json")) 
     {  
     Log.d(TAG,"Content received is: "+JSONReceived); 
     bufferedWriter = new BufferedWriter(new FileWriter(new File(getFilesDir()+File.separator+constants.UPDATED_SCRIPT_FILE))); 
     bufferedWriter.write(JSONReceived); 
     bufferedWriter.close();    
     try { 
      parseJSON(JSONReceived); 
      replaceResourceSegment(); //Call to an intent with startActivityForResult() 
      continueExecution(); //Continue the execution from here            
     } catch (IOException e) { 
      e.printStackTrace(); 
      Log.d(TAG,"IOException line 157"); 
     } 

代码发送回响应:

 HttpResponse postResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); 
     postResponse.setEntity(new StringEntity("Got it")); 
     conn.sendResponseHeader(postResponse); 
     conn.sendResponseEntity(postResponse); 

回答

0

我设法通过使用默认值false一个布尔变量来解决这个问题。它会定期检查并将控件保存在POST方法的处理程序中。

android.os.SystemClock.sleep(30000); //Sleeps for 30 seconds and invoke busy waiting in a thread 
Thread syncThread = new Thread(new LoopCheck()); 
syncThread.start(); 
synchronized(syncThread) 
{ 
Log.d(TAG,"Inside synchronized blockk"); 
try 
{ 
syncThread.wait(); 
}catch(InterruptedException ie){ 
ie.printStackTrace(); 
} 
} 

线程类被定义为如下:

class LoopCheck extends Thread{ 
public LoopCheck(){ 
} 
public void run(){ 
while(true) 
{ 
try { 
Thread.sleep(10000);      
if(write) 
{       
write = false; 
synchronized(syncThread) 
{ 
syncThread.notify(); 
} 
break; 
}       
} catch (InterruptedException e) { 
e.printStackTrace(); 
} 
} 
}  
} 
相关问题