检测网络状态以及设置网络

package com.bw.test.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
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.widget.ListView;
import android.widget.Toast;

import com.bw.test.R;
import com.bw.test.adapter.MyAdapter;
import com.bw.test.utils.NetWorkUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
/**
* 接口地址 http://v.juhe.cn/toutiao/index
*


* 参数1 type
* 默认默认值 top
* 参数2 key
* 默认值 dbedecbcd1899c9785b95cc2d17131c5
*/

private String type = "top";
private String key = "dbedecbcd1899c9785b95cc2d17131c5";


private String path = "http://v.juhe.cn/toutiao/index?type=" + type + "&key=" + key;
private ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lv = findViewById(R.id.lv);


    //通过代码动态注册广播监听网络状态

    NetWrokBroadcastReceiver receiver = new NetWrokBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    registerReceiver(receiver, intentFilter);


}


//定义广播监听网络状态
private class NetWrokBroadcastReceiver extends BroadcastReceiver {


    //重写接收广播的方法
    @Override
    public void onReceive(Context context, Intent intent) {

        boolean netWorkConnect = NetWorkUtils.isNetWorkConnect(context);
        if (netWorkConnect) {
            Toast.makeText(context, "有网", Toast.LENGTH_SHORT).show();

            //获取网络数据
            getServerData();


            boolean wifi = NetWorkUtils.isWifi(context);
            if (wifi) {

                Toast.makeText(context, "wifi", Toast.LENGTH_SHORT).show();

            } else {
                boolean mobile = NetWorkUtils.isMobile(context);
                if (mobile) {

                    Toast.makeText(context, "流量大大有", Toast.LENGTH_SHORT).show();
                }


            }


        } else {

            Toast.makeText(context, "无网", Toast.LENGTH_SHORT).show();

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("网络提示");
            builder.setMessage("请求设置网络");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //整体:
                    //startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                    //WIFI:
                    //startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    //流量:
                    startActivity(new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS));
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

            builder.show();

        }


    }
}

private void getServerData() {

    //获取网络数据
    MyAsyncTask task = new MyAsyncTask();

    //执行异步任务
    task.execute(path);


}


private class MyAsyncTask extends AsyncTask<String, Integer, String> {


    //作耗时操作
    @Override
    protected String doInBackground(String... parmas) {
        String uri = parmas[0];
        //把接口地址包装成网络地址
        try {
            URL url = new URL(uri);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;

                while ((len = inputStream.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                inputStream.close();
                bos.close();
                String json = bos.toString();
                return json;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    //更新UI
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Log.i("xxx", s);
        //第一种 Gson解析成bean对象  列表展示  自己玩


        //第二种 原生解析

        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray data = result.getJSONArray("data");

            Log.i("xxx", data.length() + "");

            MyAdapter adapter = new MyAdapter(MainActivity.this, data);
            lv.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //第三种 原生和bean结合使用


    }
}

}
/判断网络类型*******/
package com.bw.test.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetWorkUtils {

//判断是否有网
public static boolean isNetWorkConnect(Context context){
    //获取网络连接状态管理器

 ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   //得到网络信息
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info!=null){
        return info.isAvailable();
    }


    return false;
}

//判断是wifi

public static boolean isWifi(Context context){
    //获取网络连接状态管理器
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   //从网络连接管理器中获取wifi
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifi!= null){
        return true;
    }



    return false;
}


//判断是流量
public static boolean isMobile(Context context){
    //获取网络连接状态管理器
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    //从网络连接管理器中获取wifi
    NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobile!= null){
        return true;
    }



    return false;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值