private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: MenuInfo men= (MenuInfo) msg.obj; list = men.getResult(); listview.setAdapter(new GetAdapter(MainActivity.this,list)); break; case 2: Toast.makeText(MainActivity.this, "获取失败", Toast.LENGTH_SHORT).show(); break; } }};
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview = (ListView) findViewById(R.id.listview); getDateByWork(); } public void getDateByWork() { new Thread() { @Override public void run() { super.run(); try { URL url = new URL("http://apis.juhe.cn/catering/query"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestMethod("POST"); OutputStream os = connection.getOutputStream(); os.write("lng=121.538123&lat=31.677132&key=8594ec18ce64a17b5f8f20e1f5c9e4c0".getBytes()); os.flush(); os.close(); int code = connection.getResponseCode(); if (code == 200) { InputStream is = connection.getInputStream(); String json = StringTools.getJson(is); Gson gson = new Gson(); MenuInfo menuinfo = gson.fromJson(json, MenuInfo.class); Message msg = Message.obtain(); msg.what=1; msg.obj=menuinfo; handler.sendMessage(msg); }else{ Message obtain = Message.obtain(); obtain.what=2; handler.sendMessage(obtain); } } catch (Exception e) { e.printStackTrace(); } } }.start();
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交