头部联动 小圆点 数据请求 网络判断 自动轮播

时间:2022-01-13 20:42:09
                                                                  头部联动 小圆点 数据请求 网络判断 自动轮播
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.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;



public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, XListView.IXListViewListener {
    private ReceiverJt receiverJt;
    private ViewPager viewPager;
    private LinearLayout ll;
    //创建图片数组
    String[] imgs={"http://image.wufazhuce.com/Fu6o0fqKHsI_TjdpPX3N2Kc99vNP",
            "http://image.wufazhuce.com/FmDRnQ1XhReHRHB4jYqAPSx8htsP",
            "http://image.wufazhuce.com/FvVmWbqlle7jlUCTeozoval9NyBH",
            "http://image.wufazhuce.com/FuPgOcbGDD9__fyuCdPBXb5pbA1C"};
    //定义存放原点图片的集合
    List<ImageView> dot_list=new ArrayList<ImageView>();

    //网络地址
    String url="http://v.juhe.cn/toutiao/index?type=top";
    //String params="?key=c1885686ef47f19bcb45e39c4447e040";

    //自动轮播
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==100)
            {
                int c=viewPager.getCurrentItem();
                c++;
                viewPager.setCurrentItem(c);

            }

            handler.sendEmptyMessageDelayed(100,2000);
        }
    };
    private List<Bean.ResultBean.DataBean> list;
    private XListView xlv_list;
    private JsonAdapter jsonAdapter;
    private MySqlDao dao;
    private NetworkInfo info;

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

        initView();
        initDot();
        handler.sendEmptyMessageDelayed(100,2000);

        //实例化ReceiverJt
        receiverJt = new ReceiverJt();
        //动态注册
        registerReceiver(receiverJt, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    /**
     * 初始化控件
     */
    private void initView() {
        dao = new MySqlDao(MainActivity.this);
        //xlv_list初始化放在设置header上边
        xlv_list = (XListView) findViewById(R.id.xlv_list);

        //设置header
        View v= LayoutInflater.from(this).inflate(R.layout.header_item,null);
        viewPager=v.findViewById(R.id.viewPager);
        ll=v.findViewById(R.id.ll);
        xlv_list.addHeaderView(v);

        viewPager.setOnPageChangeListener(this);
        ViewPagerAdapter vpAdapter=new ViewPagerAdapter(this);
        viewPager.setAdapter(vpAdapter);

        //xlist监听事件
        xlv_list.setXListViewListener(this);
        //支持刷新和加载更多
        xlv_list.setPullLoadEnable(true);
        xlv_list.setPullRefreshEnable(true);
    }

    /**
     * 画圆的方法
     */
    private void initDot() {

        for (int i = 0; i <imgs.length ; i++) {
            ImageView iv=new ImageView(this);
            if(i==0)
            {
                iv.setImageResource(R.drawable.red);
            }else{
                iv.setImageResource(R.drawable.blue);
            }
            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(10,10);
            params.setMargins(10,5,10,5);
            ll.addView(iv,params);
            dot_list.add(iv);
        }

    }
    /**
     * ViewPager的点击事件
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    /**
     * 设置圆点跟着图片滑动
     * @param position
     */
    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i <dot_list.size() ; i++) {
            if(i==position%imgs.length)
            {
                dot_list.get(i).setImageResource(R.drawable.red);
            }else{
                dot_list.get(i).setImageResource(R.drawable.blue);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        if(info==null)
        {
            xlv_list.setPullRefreshEnable(false);
            xlv_list.setPullLoadEnable(false);
            Toast.makeText(this, "请连接网络", Toast.LENGTH_SHORT).show();
        }
        jsonAdapter.notifyDataSetChanged();
        //停止刷新和加载
        xlv_list.stopLoadMore();
        xlv_list.stopRefresh();
    }

    @Override
    public void onLoadMore() {
        if(info==null)
        {
            xlv_list.setPullRefreshEnable(false);
            xlv_list.setPullLoadEnable(false);
            Toast.makeText(this, "请连接网络", Toast.LENGTH_SHORT).show();
        }
        list.addAll(list);
        //刷新适配器
        jsonAdapter.notifyDataSetChanged();
        //停止刷新和加载
        xlv_list.stopLoadMore();
        xlv_list.stopRefresh();
    }

    /**
     * 广播判断网络  记着是public
     */
    public class ReceiverJt extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //得到网络连接状态
            info = manager.getActiveNetworkInfo();
            //处理逻辑   !=null 为有网状态
            if(info !=null){
                Toast.makeText(context, "有网络连接,做有网时的逻辑", Toast.LENGTH_SHORT).show();
                new MyAsyncTask().execute(url);
            }else{
                Toast.makeText(context, "无网络连接,做无网时的逻辑", Toast.LENGTH_SHORT).show();
                AlertDialog.Builder b=new AlertDialog.Builder(MainActivity.this);
                b.setMessage("进入设置界面");
                b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent=new Intent();
                        intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
                        startActivity(intent);
                    }
                });
                b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                String json = dao.select();
                System.out.println("取消:select================="+json);
                getJson(json);
                b.create().show();
            }
        }
    }

    //动态注册销毁
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //动态注册广播须要销毁
        unregisterReceiver(receiverJt);
    }

    /**
     * 异步加载网络数据
     */
    class MyAsyncTask extends AsyncTask<String,Integer,String>{

        //获取网络数据的操作
        @Override
        protected String doInBackground(String... strings) {

            //接收获取的json串
            StringBuffer result=new StringBuffer();
            try {
                URL uri=new URL(strings[0]);
                HttpURLConnection connection= (HttpURLConnection) uri.openConnection();
                //设置请求方法
                connection.setRequestMethod("POST");
                //获取输入输出流
                connection.setDoOutput(true);
                connection.setDoInput(true);
                //追加参数
                DataOutputStream dos=new DataOutputStream(connection.getOutputStream());
                //追加key值
                String params="&key=c1885686ef47f19bcb45e39c4447e040";
                dos.writeBytes(params);
                dos.flush();
                dos.close();
                //获取连接
                connection.connect();
                System.out.println("connection==========="+connection);
                if(200==connection.getResponseCode())
                {
                    InputStream inputStream=connection.getInputStream();
                    BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                    String line=null;
                    while((line=reader.readLine())!=null)
                    {
                        result.append(line);
                    }
                    //调用数据库
                    dao.insert(result.toString());
                    String select = dao.select();
                    System.out.println("select============"+select);
                    System.out.println("json===================="+result);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return result.toString();
        }

        //获取完网络数据后的操作
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            getJson(s);
        }
    }

    /**
     * 解析json串
     * @param s
     */
    private void getJson(String s) {
        Gson gson=new Gson();
        Bean bean = gson.fromJson(s, Bean.class);
        list = bean.getResult().getData();
        for (Bean.ResultBean.DataBean b: list) {
            System.out.println("bean=========="+b.getAuthor_name()+" "+b.getTitle()+" "+b.getThumbnail_pic_s());

        }
        //设置关联适配器
        jsonAdapter = new JsonAdapter(this, list);
        xlv_list.setAdapter(jsonAdapter);
    }
}