【发布时间】:2015-07-05 10:20:35
【问题描述】:
我想每隔 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;
}
}
}
【问题讨论】:
标签: java android timer httprequest timertask