1. 程式人生 > >判斷網路 獲取json展示

判斷網路 獲取json展示

判斷網路 獲取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;
}
}