1.网络请求,发生给Handler
private void toutiao() {
new Thread(){
@Override
public void run() {
String path="http://www.toutiao.com/hot_words/";
try {
URL url = new URL(path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
int responseCode = urlConnection.getResponseCode();
if (responseCode==200){
InputStream inputStream = urlConnection.getInputStream();
String s = convertStreamToString(inputStream);
Message m=Message.obtain();
m.obj=s;
m.what=0;
h.sendMessage(m);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
2.Handler接收;;;;;遍历数据;;;;展示在textview控件上;;;;;数据延时3秒,切换下条数
据
Handler h=new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what==0){
String obj = (String) msg.obj;
//解析...android中json格式的数据只有两种,,一种是{}对应的,解析出来是对象;;;一种是[]对应的,这种是数组或者集合
//1.集合或者数据在json原生解析,使用的JSONArray这个类...{}对应的在原声解析里面是JSONObject
//2.使用gson解析数组格式的json字符串
Gson gson = new Gson();
Type type = new TypeToken<List<String>>(){}.getType();
List<String> o = gson.fromJson(obj, type);
for (int i=0;i<o.size();i++){
list.addAll(o);
}
//设置第一条数据的显示
tiao.setText(list.get(index));
//发送一个延时的消息
h.sendEmptyMessageDelayed(1,3000);
}else if(msg.what==1){
//接收到延时消息
index++;
index=index%list.size();
tiao.setText(list.get(index));
h.sendEmptyMessageDelayed(1,3000);
}
}
};
头条数据切换
最新推荐文章于 2024-05-23 16:31:47 发布