ConnectivityManager类网络状态判断设置+BaseActivity和BaseFragment的封装使用+网络状态工具类+网络请求工具类

一. MainActivity.java

package androidthree_1509d.connect;
import android.widget.RelativeLayout;
import base.BaseActivity;
import fragment.NewsFrament;
public class MainActivity extends BaseActivity {
    private RelativeLayout relativeLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        //找到控件
        relativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);

    }

    @Override
    protected void initData() {
        //使用fragment替换布局的显示

        getSupportFragmentManager().beginTransaction().replace(R.id.relative_layout,new NewsFrament()).commit();
    }
}

二. adapter包下的自定义适配器类:

package adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class NewsAdapter extends BaseAdapter {
    Context context;
    List> list;

    public NewsAdapter(Context context, List> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null){
            view = View.inflate(context,android.R.layout.simple_list_item_1,null);
        }

        TextView textView = view.findViewById(android.R.id.text1);

        textView.setText(list.get(i).get(0)+"----"+list.get(i).get(1));

        return view;
    }
}

三. base包下的自定义Activity和Fragment类:

1. BaseActivity.java

package base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
public abstract class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(getLayoutId());
        
        initView();
        
        initData();
    }

    //获取资源文件的id
    protected abstract int getLayoutId();

    //初始化展示的视图
    protected abstract void initView();

    //初始化数据
    protected abstract void initData();

}

2. BaseFragment.java

package base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public abstract class BaseFragment extends Fragment {

    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = initView(inflater,container);

        return view;
    }

    //初始化视图
    protected abstract View initView(LayoutInflater inflater, ViewGroup container);

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        initData();
        super.onActivityCreated(savedInstanceState);
    }

    //初始化数据
    protected abstract void initData();
}

四. bean包下的数据封装类

五. fragment包下的自定义Fragment类:

package fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.google.gson.Gson;
import java.util.List;
import adapter.NewsAdapter;
import base.BaseFragment;
import bean.DataDataBean;
import internet.NetInfoCallBack;
import util.GetDataUtil;
import util.NetWorkUtil;
import androidthree_1509d.connect.R;

public class NewsFrament extends BaseFragment {

    private ListView listView;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.news_fragment_layout, container, false);

        listView = view.findViewById(R.id.list_view);

        return view;
    }

    @Override
    protected void initData() {
        //获取网络数据,,,,填充到listView...获取之前网络判断


        if (NetWorkUtil.isNetworkConnected(getActivity())){//可用
            GetDataUtil.getDataFromNet("https://suggest.taobao.com/sug?code=utf-8&q=%E6%98%BE%E7%A4%BA%E5%99%A8", new NetInfoCallBack() {
                @Override
                public void getSuccessString(String string) {
                    //获取到了数据...json
                    Gson gson = new Gson();

                    DataDataBean dataDataBean = gson.fromJson(string, DataDataBean.class);

                    List> list = dataDataBean.getResult();

                    //设置适配器
                    NewsAdapter newsAdapter = new NewsAdapter(getActivity(), list);
                    listView.setAdapter(newsAdapter);

                }
            });

        }else {

            NetWorkUtil.showNoNetWorkDlg(getActivity());
        }
    }
}

六. Internet包下的自定义获取网络状态信息的接口类:

package internet;
public interface NetInfoCallBack {
    public void getSuccessString(String string);
}

七. util包下的自定义的工具类:

1. GetDataUtil.java

package util;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import internet.NetInfoCallBack;
public class GetDataUtil {

    public static void getDataFromNet(final String path, final NetInfoCallBack netInfoCallBack){

        AsyncTask asyncTask = new AsyncTask() {
            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(path);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //设置
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);

                    //获取
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200){
                        InputStream inputStream = connection.getInputStream();

                        //转换为字符串
                        String s = StringUtil.streamToString(inputStream, "utf-8");

                        return s;
                    }


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

                return "";
            }

            @Override
            protected void onPostExecute(String json) {
                netInfoCallBack.getSuccessString(json);
            }
        };

        asyncTask.execute();

    }
}

2. NetWorkUtil.java

package util;
import androidthree_1509d.connect.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetWorkUtil {

    /**
     * 判断是否有网络连接.....http://www.jianshu.com/p/10ed9ae02775
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            // 获取NetworkInfo对象
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            //判断NetworkInfo对象是否为空
            if (networkInfo != null)
                return networkInfo.isAvailable();
        }
        return false;
    }

    /**
     * 网络无连接时跳转页面.....http://blog.csdn.net/cy524563/article/details/41686735
     * @param context
     */
    public static void showNoNetWorkDlg(final Context context) {


        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.app_name)
                .setMessage("网络连接不可用,是否去设置?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到系统的网络设置界面
                        Intent intent = null;
                        // 先判断当前系统版本
                        if(android.os.Build.VERSION.SDK_INT > 10){  // 3.0以上
                            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        }else{
                            intent = new Intent();
                            intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
                        }
                        context.startActivity(intent);

                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

}

3. StringUtil.java

package util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringUtil {

    public static String streamToString(InputStream inputStream, String charset) {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String s = null;
            StringBuilder builder = new StringBuilder();
            while ((s = bufferedReader.readLine()) != null){
                builder.append(s);
            }

            bufferedReader.close();
            return builder.toString();

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

        return  null;
    }
}

八. res 文件夹下的布局文件:

1. activity_main.xml

xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relative_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

RelativeLayout>

2. fragment_layout.xml

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    ListView>

LinearLayout>


九. 在AndroidMainifest.xml中添加

1. 网络请求权限:

<uses-permission android:name="android.permission.INTERNET">uses-permission>

2. 判断网络状态的权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">uses-permission>

你可能感兴趣的:(ConnectivityManager类网络状态判断设置+BaseActivity和BaseFragment的封装使用+网络状态工具类+网络请求工具类)