陌简曦东
2015-08-11 05:14
采纳率: 57.1%
浏览 4.1k
已采纳

xutils框架的httputils怎么实现每隔5秒请求一次服务器?

xutils框架的httputils怎么实现每隔5秒请求一次服务器?
代码如下每隔5秒执行一次getdataFromNet不出错如何实现

 public class MainActivity extends Activity {
    private Thread thread;
    private MapView mapView;
    private AMap aMap;
    private LocationManagerProxy locationManagerProxy;
    private ImageView iv_maptag;
    private EditText et_search;
    private ImageView iv_user;
    private ImageView iv_setmenu;
    private ImageView iv_location;
    private Marker marker;
    private OnLocationChangedListener mListener;
    private MarkerOptions markerOptions;
    private ArrayList<Aircraft> aircraftList;
    private MarkerOptions markerOptionslist;
    private ArrayList<Marker> listmarker;
    private ArrayList<MarkerOptions> list = new ArrayList<MarkerOptions>();
    private String line = null;
    private Handler mHandler = new Handler();
    private boolean ThreadFlag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
        mapView.onCreate(savedInstanceState);
        setUpMap();
        initData();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case 1:
                // list=new ArrayList<MarkerOptions>();
                aircraftList = (ArrayList<Aircraft>) msg.obj;
                if (aircraftList != null) {
                    for (int i = 0; i < aircraftList.size(); i++) {
                        Double latitedu = Double.parseDouble(aircraftList
                                .get(i).Latitude);
                        Double longitedu = Double.parseDouble(aircraftList
                                .get(i).Longitude);
                        markerOptionslist = new MarkerOptions();
                        markerOptionslist.position(new LatLng(latitedu,
                                longitedu));
                        // Toast.makeText(getApplicationContext(),
                        // markerOptionslist+"", Toast.LENGTH_LONG).show();
                        markerOptionslist.perspective(true);// 设置marker的近大远小效果
                        markerOptionslist
                                .icon(BitmapDescriptorFactory
                                        .fromResource(R.drawable.civil_aircraft_selected));
                        markerOptionslist.draggable(true);
                        markerOptionslist.setFlat(true);
                        markerOptionslist.period(50);// 定位marker图标在中间显示
                        list.add(markerOptionslist);
                    }
                    listmarker = aMap.addMarkers(list, false);
                }
                break;
            default:
                break;
            }
        }
    };

    private void initData() {
        getDataFromNet();// 每隔五秒执行一次此方法不报错
        // requestFlyAirplane();//第一种实现报错,异常为java.lang.RuntimeException//Can't create handler inside thread that has not called Looper.prepare()

        // new Thread(networkTask1).start();//第二种一样报错

    }

    private void initView() {
        mapView = (MapView) findViewById(R.id.main_mapview1);
        iv_location = (ImageView) findViewById(R.id.iv_location);
        iv_setmenu = (ImageView) findViewById(R.id.iv_setmenu);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    private void setUpMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
    // private void requestFlyAirplane(){
    // thread=new Thread(new Runnable() {
    // @Override
    // public void run() {
    // while(ThreadFlag){
    // try {
    // aircraftList1=getDataFromNet();
    // Message message=handler.obtainMessage();
    // message.obj=aircraftList;
    // message.what=1;
    // handler.sendMessage(message);
    // // getDataFromNet();
    // // Thread.sleep(5000);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // }
    // });
    // thread.start();
    // }
    Runnable networkTask1 = new Runnable() {
        @Override
        public void run() {
            // TODO
            while (ThreadFlag) {
                try {
                    aircraftList = getDataFromNet();
                    Message message = handler.obtainMessage();
                    message.obj = aircraftList;
                    message.what = 1;
                    handler.sendMessage(message);
                    // getDataFromNet();
                    // Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
    ArrayList<Aircraft> aircraftList1 = new ArrayList<AircraftInfo.Aircraft>();
    private ArrayList<Aircraft> getDataFromNet() {
        HttpUtils httpUtils = new HttpUtils();
        String url = "http://124.207.158.74:60023/aircraft/baidu";
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json; encoding=utf-8");
        params.setHeader("Accept", "application/json");
        params.setHeader("Username", "haifeng");
        params.setHeader("appkey", "fff2dd6003243e46a4aefab71d4366f0c3ebfb12");
        params.setHeader("system", "1");
        params.setHeader("logindevice",
                Secure.getString(getContentResolver(), Secure.ANDROID_ID));
        httpUtils.send(HttpMethod.GET, url, params,
                new RequestCallBack<String>() {
                    // 请求成功
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        // Toast.makeText(getApplicationContext(),
                        // "请求成功"+result, Toast.LENGTH_SHORT).show();
                        // processData(result);
                        Gson gson = new Gson();
                        AircraftInfo aircrafts = gson.fromJson(result,
                                AircraftInfo.class);
                        aircraftList1 = aircrafts.AircraftInfos;
                        Message message = handler.obtainMessage();
                        message.obj = aircraftList;
                        message.what = 1;
                        handler.sendMessage(message);
                    }

                    // 请求失败
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplicationContext(), "网络错误",
                                Toast.LENGTH_SHORT).show();
                        error.printStackTrace();
                    }
                });
        try {
            // httpUtils.wait(5000);
            // httpUtils.notifyAll();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return aircraftList1;
    }

}

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 胖子爱你520 2015-08-11 06:42
    已采纳

    你看看这个,希望对你有帮助http://www.tuicool.com/articles/nMFb2q

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题