Java Android:如何每 10 秒通过服务发送一次 http 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19617621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:49:53  来源:igfitidea点击:

Android: How to send http request via service every 10 seconds

javaandroidservicehttprequest

提问by ?V?

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

我需要每 10 秒从服务器接收一次状态。

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

我尝试通过服务发送 http 请求来做到这一点。

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

非常感谢阿维

采纳答案by null

Put a handler inside onPostExecute to send a http request after 10 secs

将处理程序放入 onPostExecute 以在 10 秒后发送 http 请求

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

After 10 secs doInBackground will be executed again, after that onPostExecute again, handler again and so on and so on..

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

回答by Rushabh Patel

You can simply use CountDownTimerclass in android.

您可以简单地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
    }
}

Hope it will help you.

希望它会帮助你。

回答by Zymurgeek

The reason the code only runs once is that there's a returnin your timer loop. However, I'd advise moving the loop to your background task or using one of the other answers given here rather than implementing a loop in onStartCommand()that never returns.

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

回答by Vladimir Mamulov

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

回答by user3325431

put return START_STICKY; after while , and service will work properly

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