根据服务器的内容来更新spinner
本文内容请结合如下两篇文章一起看:
腾讯云函数node.js返回自动带反斜杠
腾讯云函数部署环境[使用函数URL]
现在有这样一个需求,APP有一个下拉选择框作为版本选择,因为改个管脚就变成一个版本,客户需求也很零散,所以后期会大量增加版本,这时候每增加一个版本就让客户更新一次APP比较麻烦,因为客户有很多,不好处理,所以思来想去还是这个下拉选择框能够从服务器获取然后更新比较好,现在就来做这个事情!
首先要把发送网络请求拿到服务器数据的功能搞出来,不加这个功能之前的下拉列表是这样的(上图是最终加了的效果):
String[] ctype = new String[]{"001","001-1", "002","002-1","002-2","003","004","004-1","001-2",};spinner_versiontype_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ctype); //创建一个数组适配器spinner_versiontype_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //设置下拉列表框的下拉选项样式
onCreate函数中增加如下内容:
Thread thread = new Thread("Thread1") {public void run() {HttpURLConnection connection=null;try {URL url = new URL("https://1xxxxxxxx.scf.tencentcs.com/RequestJson?id=BleCloudControlMode");connection = (HttpURLConnection) url.openConnection();connection.setConnectTimeout(3000);connection.setReadTimeout(3000);//设置请求方式 GET / POST 一定要大小connection.setRequestMethod("GET");connection.setDoInput(true);connection.setDoOutput(false);connection.connect();int responseCode = connection.getResponseCode();if (responseCode != HttpURLConnection.HTTP_OK) {throw new IOException("HTTP error code" + responseCode);}String result = getStringByStream(connection.getInputStream());if (result == null) {Log.d("Fail", "失败了");}else{result = result.substring(1,result.length()-1).replace("\\","");Gson gson = new Gson();Employee empObject = gson.fromJson(result, Employee.class);//System.out.println(empObject);Message message = new Message();message.what = 1;message.obj = empObject.getMode();mHandler.sendMessage(message);}} catch (Exception e) {e.printStackTrace();}};};thread.start();
这里从服务器拿到数据后发送一个消息给主线程,主线程收到后这样操作UI显示:
//全局变量ArrayAdapter<String> spinner_versiontype_adapter;Handler mHandler;mHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what){case 1:String str=(String)(msg.obj);String[] mode = str.split(";");spinner_versiontype_adapter = new ArrayAdapter<String>(OTA_Active.this, android.R.layout.simple_spinner_item, mode);spinner_versiontype.setAdapter(spinner_versiontype_adapter);spinner_versiontype_adapter.notifyDataSetChanged();}}};
根据腾讯云函数node.js返回自动带反斜杠文章的代码说明可以得到代码运行后下拉选择框会变成本章节第一幅图的样子!
这样修改后,如果还要增加版本号只用修改云函数然后重新部署就行了,客户不用升级APP,极大方便使用,而且这种方式比在COS上保存一个xml文件来得更加容易,也是为了后面的功能做铺垫!