在Android中每10秒使用AsyncTask调用REST方法

时间:2014-06-04 22:00:47

标签: android

我需要每隔10秒调用一次服务器的REST方法,

我的目的是使用AsyncTask以下列方式执行此操作:

myTask = new AsyncTask<Void, Void, String>() {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    ...
    }

    @Override
    protected String doInBackground(Void... params) {
        //invoke REST service
        ....
        return "";
    }

    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);
        //post execute operations
        ...
    }
};

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:4)

解决方案是从TimerTask

调用AsyncTask
protected class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        (new AsyncTask<Void, Void, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                ...
            }

            @Override
            protected String doInBackground(Void... params) {
                //invoke REST service
                ....
                return "";
            }

            @Override
            protected void onPostExecute(String response) {
                super.onPostExecute(response);
                //post execute operations
                ...
            }
        }).execute();
    }
}

如果您担心对服务器的调用时间太长,然后要求它们重叠,您可以通过以下方式输入带有AtomicBoolean(同步)的信号量:

信号量声明

private final AtomicBoolean isRunning = new AtomicBoolean(false);

带信号量的TimerTask

protected class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        //if isRunning is true does not execute the task
        if (isRunning.get()) return;

        (new AsyncTask<Void, Void, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                //active flag isRunning
                isRunning.set(true);

                ...
            }

            @Override
            protected String doInBackground(Void... params) {

                ....
                //invoke REST service
                ....
                return "";
            }

            @Override
            protected void onPostExecute(String response) {
                super.onPostExecute(response);
                //post execute operations
                ...

                //deactive flag isRunning
                isRunning.set(false);
            }
        }).execute();
    }
}

注意:当您发现错误时,请小心关闭信号量,因为如果由于某种原因保持活动状态将不再运行AsyncTask

答案 1 :(得分:2)

考虑使用AlarmManager。创建服务或广播接收器以捕获AlarmManager意图并发出服务器请求。下面的例子说明了如何每隔10秒从AlarmManager建立重复事件。

   AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
   Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
   PendingIntent pending = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0);
   am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), TEN_SECONDS, pending);