使用TimerTask每隔X秒发出Http请求

时间:2015-07-05 10:20:35

标签: java android timer httprequest timertask

我想每隔X秒向服务器发送一次请求,并获得结果。 没有使用计时器它工作正常,但如果我使用timer.scheduleAtFixedRate我得到例外:

"无法在未调用Looper.prepare()"

的线程内创建处理程序

我怎样摆脱这个? 谢谢!

public class MainMap extends ActionBarActivity implements LocationListener , View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        int initialDelay = 1000;
        int period = 5000; 
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {

            public void run() {
                //request every 5 seconds
                setPosition();
            }
        };
        timer.scheduleAtFixedRate(task, initialDelay, period);
    }

    public void setPosition() {
        getCurrentLocation();

        ArrayList<JSONObject> dataDelete = new ArrayList<>();
        Map<String,String> mUserDelete = new HashMap<>();

        if (isOnline) {
            mUserDelete.put("available", String.valueOf(1));
        } else {
            mUserDelete.put("available", String.valueOf(0));
        }

        mUserDelete.put("id",user.getId());
        mUserDelete.put("longitude", String.valueOf(longitude));
        mUserDelete.put("latitude", String.valueOf(latitude));
        dataDelete.add(new JSONObject(mUserDelete));
        JSONArray jsonArrayDelete = new JSONArray();
        jsonArrayDelete.put(dataDelete);
        final JSONObject jsonObjectDelete = new JSONObject();

        try {
            jsonObjectDelete.put("request", jsonArrayDelete);

            new AsyncServerRequest().execute(jsonObjectDelete);

        } catch (JSONException e) {
            Log.d(Constants.tag, "JSONException: " + e.getMessage());
        }
    }

    public void getCurrentLocation() {
        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

        longitude = location.getLongitude();
        latitude = location.getLatitude();

    }


    public class AsyncServerRequest extends AsyncTask<JSONObject, Integer, Long> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Long aLong) {
            super.onPostExecute(aLong);
        }

        @Override
        protected Long doInBackground(final JSONObject... jsonObjects) {
            final HttpRequest request = new HttpRequest(uriStatus, jsonObjects[0]);
            request.makeHttpRequest();
            return null;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于这行代码

new AsyncServerRequest().execute(jsonObjectDelete);

您不能也不应该从后台线程启动AsyncTask,但始终从UI线程启动。而且您可能不需要AsyncTask,因为TimerTask已经在后台线程上运行