判断网络 获取json展示
程序员文章站
2022-06-05 21:06:40
...
判断网络 获取json展示
==
private String apiurl = “http://120.27.23.105/ad/getAd”;
private ListView listView;
private ArrayList arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
listView = findViewById(R.id.listView);
//调用方法
//接收返回的信息
boolean netWorkConnected = NetworkUtils.isNetWorkConnected(MainActivity.this);
if(netWorkConnected) {
getString1();
}else{
Toast.makeText(this, "没网", Toast.LENGTH_SHORT).show();
}
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what)
{
case 0:
String json = (String) msg.obj;
Log.i("xxx",json);
Gson gson = new Gson();
JSON fromJson = gson.fromJson(json, JSON.class);
arrayList = fromJson.getData();
Toast.makeText(MainActivity.this, arrayList.toString(), Toast.LENGTH_SHORT).show();
listView.setAdapter(new MyAdapter(arrayList,MainActivity.this));
break;
}
}
};
<---------------------------------------------------------------------->
封装的判断网络的方式
public class NetworkUtils {
//写一个方法传入上下文
public static boolean isNetWorkConnected(Context context){
//获取网络状态’’
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//得到网路信息
NetworkInfo info = cm.getActiveNetworkInfo();
if (info!=null){
//返回网路状态
return info.isAvailable();
}
return false;
}
}
上一篇: 安卓项目实战之:网络连接判断工具类
下一篇: 网络请求封装