11

I need to receive a status from the server every 10 seconds.

I tried to do that by sending a http request via service.

The problem is that my code executes only once.

This is the code for my service:

public class ServiceStatusUpdate extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    while(true)
    {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            new DoBackgroundTask().execute(Utilities.QUERYstatus);
            e.printStackTrace();
        }
        return START_STICKY;            
    }
}

private class DoBackgroundTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String response = "";
        String dataToSend = params[0];
        Log.i("FROM STATS SERVICE DoBackgroundTask", dataToSend);
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(Utilities.AGENT_URL);

        try {
            httpPost.setEntity(new StringEntity(dataToSend, "UTF-8"));

            // Set up the header types needed to properly transfer JSON
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept-Encoding", "application/json");
            httpPost.setHeader("Accept-Language", "en-US");

            // Execute POST
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            if (responseEntity != null) {
                response = EntityUtils.toString(responseEntity);
            } else {
                response = "{\"NO DATA:\"NO DATA\"}";
            }
        } catch (ClientProtocolException e) {
            response = "{\"ERROR\":" + e.getMessage().toString() + "}";
        } catch (IOException e) {
            response = "{\"ERROR\":" + e.getMessage().toString() + "}";
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        Utilities.STATUS = result;
        Log.i("FROM STATUS SERVICE: STATUS IS:", Utilities.STATUS);
        super.onPostExecute(result);
    }
}
}

Thank's alot Avi

4

5 回答 5

19

在 onPostExecute 中放置一个处理程序以在 10 秒后发送一个 http 请求

new Handler().postDelayed(new Runnable() {
        public void run() {
            requestHttp();
        }
    }, 10000);

10 秒后,doInBackground 将再次执行,之后再次执行 onPostExecute,再次执行处理程序,依此类推。

于 2013-10-27T11:46:23.853 回答
1

你可以简单地CountDownTimer在android中使用类。

public class AlertSessionCountDownTimer extends CountDownTimer {

    public AlertSessionCountDownTimer(long startTime, long interval) {
        super(startTime, interval);
    }

    @Override
    public void onFinish() {
        //YOUR LOGIC ON FINISH 10 SECONDS
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //YOUR LOGIC ON TICK
    }
}

希望它会帮助你。

于 2013-10-27T11:45:25.137 回答
0

代码只运行一次的原因是return你的计时器循环中有一个。但是,我建议将循环移动到您的后台任务或使用此处给出的其他答案之一,而不是实现一个onStartCommand()永远不会返回的循环。

于 2013-10-27T12:17:39.627 回答
0
Handler handler_proc = new Handler();

final Runnable runnable_proc = new Runnable() {
    public void run() {
        requestHttp(new OnFinish() {
            @Override
            public void onSuccess() {
                // pause should be considered since the end of the previous http request.
                // Otherwise, new requests will occur before the previous one is complete,
                // if http_timeout > delay
                handler_proc.postDelayed(runnable_proc, 10000);
            }
        });
    }
}

handler_proc.post(runnable_proc);
于 2014-12-06T14:22:16.450 回答
0

放回 START_STICKY;一段时间后,服务将正常工作

于 2015-02-01T21:31:43.267 回答