繁体   English   中英

使用TimerTask每X秒发送一次Http请求

[英]Http request every X seconds using 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;
        }
    }
}

问题是这行代码

new AsyncServerRequest().execute(jsonObjectDelete);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM