Android服务中的Http响应



嗨,我在Android中有一个服务,处理HTTP方法POST如下所述。现在,我需要调用

中的Intent

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);

我设法通过使用默认值为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();
}
}
}       
}

相关内容

  • 没有找到相关文章

最新更新