package com.example.a13717.rikaoday03; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import com.google.gson.Gson; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView list_view; private String url = "http://apis.juhe.cn/cook/query.php?menu=%E8%8F%9C&dtype=&pn=0&rn=30&albums=&=&key=e41e0c184e92b917adf9511c411395a6"; @SuppressLint("HandlerLeak") private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what==0){ String json = (String) msg.obj; Gson gson = new Gson(); //转换为gson Bean bean = gson.fromJson(json, Bean.class); List<Bean.ResultBean.DataBean> list = bean.getResult().getData(); list_view.setAdapter(new MyAdapter(list,MainActivity.this)); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控件 list_view = findViewById(R.id.list_view); //获取网络管理器 ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo(); if (activeNetworkInfo==null){ new AlertDialog.Builder(MainActivity.this) .setMessage("当前没有网络,请设置网络") .setNegativeButton("取消",null) .setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); } }) .show(); }else{ new Thread(){ @Override public void run() { try { URL u = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); if (urlConnection.getResponseCode()==200){ InputStream inputStream = urlConnection.getInputStream(); int len = -1 ; byte[] b = new byte[1024]; StringBuffer stringBuffer = new StringBuffer(); while ((len=inputStream.read(b))!=-1){ String s = new String(b,0 ,len); stringBuffer.append(s); } Message msg = new Message(); msg.obj=stringBuffer.toString(); msg.what=0; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } } }
判断网络;连接状态
最新推荐文章于 2023-04-14 13:31:58 发布