是否有网络

来源:互联网 发布:软件测试薪资 编辑:程序博客网 时间:2024/05/22 01:59
package com.example.day_post__1;import android.app.AlertDialog;import android.app.Dialog;import android.content.ComponentName;import android.content.DialogInterface;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.AsyncTask;import android.os.Build;import android.provider.Settings;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ListView;import com.google.gson.Gson;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import java.net.URLEncoder;import static android.R.attr.path;import static android.R.attr.value;import static android.content.Context.CONNECTIVITY_SERVICE;import static com.example.day_post__1.R.id.lv;public class MainActivity extends AppCompatActivity {ListView lv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);              Button bu= (Button) findViewById(R.id.bu);        lv=(ListView) findViewById(R.id.lv);        bu.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);                NetworkInfo info = manager.getActiveNetworkInfo();                if (info != null && info.isAvailable()) {                    MyTask task = new MyTask();                    try {                        String path="http://apis.juhe.cn/cook/query.php";                        String value = "menu=" + URLEncoder.encode("牛排", "utf-8") + "&key=13af589c334ec80c037688e927407966&rn=1";                        task.execute(new String[]{path,value});                    } catch (Exception e) {                        e.printStackTrace();                    }                } else {                    showDialog();                }            }        });    }    class MyTask extends AsyncTask<String,Integer,Bean>{        @Override        protected Bean doInBackground(String... strings) {            String data = postData(strings[0], strings[1]);            Gson gson = new Gson();            Bean bean = gson.fromJson(data, Bean.class);            System.out.print(bean);            return bean;        }        @Override        protected void onPostExecute(Bean bean) {            super.onPostExecute(bean);            Myadapter adapter = new Myadapter(bean.result.data.get(0).steps,MainActivity.this);              lv.setAdapter(adapter);        }    }    public  String postData(String path,String value){        try {            URL url = new URL(path);            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.setRequestMethod("POST");            connection.setDoOutput(true);            OutputStream outputStream = connection.getOutputStream();                 outputStream.write(value.getBytes());            int code = connection.getResponseCode();            if (code==200) {                InputStream inputStream = connection.getInputStream();                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));                String str ="";                StringBuilder builder = new StringBuilder();                while ((str=reader.readLine())!=null) {                      builder.append(str);                }                 return builder.toString();            }        } catch (Exception e) {            e.printStackTrace();        }        return  null;    }    public void showDialog(){        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);        builder.setTitle("网络状态提醒");        builder.setMessage("你的网络未开启是否连接网络");          builder.setPositiveButton("开启", new DialogInterface.OnClickListener() {              @Override              public void onClick(DialogInterface dialogInterface, int i) {                  if (Build.VERSION.SDK_INT > 10) {                      Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);                      startActivity(intent);                  } else {                      Intent intent = new Intent();                      ComponentName componentName = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");                      intent.setComponent(componentName);                      intent.setAction(Intent.ACTION_VIEW);                     startActivity(intent);                  }                  dialogInterface.dismiss();              }          });        builder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialogInterface, int i) {                dialogInterface.dismiss();            }        });        builder.create().show();    }}
原创粉丝点击