网络数据

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.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bwie.zaihui.adapter.MyAdapter;
import com.bwie.zaihui.adapter.ViewPagerAdapetr;
import com.bwie.zaihui.bean.News;
import com.bwie.zaihui.sql.MyDao;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import view.xlistview.XListView;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener ,XListView.IXListViewListener{
    private ViewPager vp;
    private LinearLayout ll;
    private XListView xlist;
    private String path="http://v.juhe.cn/toutiao/index?key=22a108244dbb8d1f49967cd74a0c144d";
    //图片的路径
    private String photoOne="http://i02.pictn.sogoucdn.com/a38250efa28d2e7c";
    private String photoTwo="http://i02.pictn.sogoucdn.com/cc486fd733334627";
    private String photoThree="http://i02.pictn.sogoucdn.com/78b429f175218fc1";
    private String[] imgsum={photoOne,photoTwo,photoThree};
    private List listDot=new ArrayList<>();
    private ReceiverJt receiverJt;
    private StringBuffer buffer;
    private List list;
    private MyAdapter adapter;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int c=vp.getCurrentItem();
            if(msg.what==100){
                c++;
                vp.setCurrentItem(c);
            }
            //延时
            handler.sendEmptyMessageDelayed(100,2000);
        }
    };
    private MyDao dao;
    private NetworkInfo info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //延时
        handler.sendEmptyMessageDelayed(100,2000);
        //初始化控件
        initView();
        //小圆点
        initDot();
        //动态注册
        receiverJt=new ReceiverJt();
        registerReceiver(receiverJt,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
       //异步对象
        MyAsnyTask asnyTask=new MyAsnyTask();
        asnyTask.execute(path);
    }
    /**
     * 控件的方法
     */
    private void initView() {
        xlist= (XListView) findViewById(R.id.xlist);
        //头部
        View inflate= LayoutInflater.from(MainActivity.this).inflate(R.layout.headeritem,null);
        vp=inflate.findViewById(R.id.vp);
        ll=inflate.findViewById(R.id.ll);
        xlist.addHeaderView(inflate);
        //viewpage的监听事件
        vp.setOnPageChangeListener(this);
        //viewpage的适配器
        ViewPagerAdapetr adapter=new ViewPagerAdapetr(MainActivity.this);
        vp.setAdapter(adapter);
        //监听事件
        xlist.setXListViewListener(this);
        xlist.setPullLoadEnable(true);//允许加载
        xlist.setPullRefreshEnable(true);//允许刷新
    }

    /**
     * 小圆点
     */
    private void initDot() {
        for (int i = 0; i             ImageView image_view=new ImageView(this);
            if(i==0){
                image_view.setImageResource(R.drawable.red);
            }else{
                image_view.setImageResource(R.drawable.green);
            }
            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(20,20);
            params.setMargins(10,5,10,5);
            ll.addView(image_view,params);
            listDot.add(image_view);
        }
    }
    /**
     * viewpage的监听事件的方法
     * @param position
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }
    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i             if(i==position%imgsum.length){
                listDot.get(i).setImageResource(R.drawable.red);
            }else{
                listDot.get(i).setImageResource(R.drawable.green);
            }
        }
    }
    @Override
    public void onPageScrollStateChanged(int state) {

    }
//下拉刷新
    @Override
    public void onRefresh() {
        if(info==null){
            xlist.setPullLoadEnable(false);
            xlist.setPullRefreshEnable(false);
            Toast.makeText(MainActivity.this,"请连接网络",Toast.LENGTH_SHORT).show();
        }
        adapter.notifyDataSetChanged();
        xlist.stopRefresh();
        xlist.stopLoadMore();
    }
//上拉加载
    @Override
    public void onLoadMore() {
        if(info==null){
            xlist.setPullLoadEnable(false);
            xlist.setPullRefreshEnable(false);
            Toast.makeText(MainActivity.this,"请连接网络",Toast.LENGTH_SHORT).show();
        }
        list.addAll(list);
        adapter.notifyDataSetChanged();
        xlist.stopRefresh();
        xlist.stopLoadMore();
    }

    //判断网络
    private class ReceiverJt extends BroadcastReceiver {
        private AlertDialog.Builder ab;
        @Override
        public void onReceive(Context context, Intent intent) {
            //得到网络连接状态管理   系统服务
            ConnectivityManager manager= (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
            //得到网络连接状态  info设置全局
            info = manager.getActiveNetworkInfo();
            //处理逻辑   !=null 为有网状态
            if(info !=null){
                Toast.makeText(context,"有网络连接,做有网时的逻辑",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(context,"无网络连接,做有网时的逻辑",Toast.LENGTH_SHORT).show();
                //弹框
                ab = new AlertDialog.Builder(MainActivity.this)
                        .setMessage("网络连接")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //跳转到wifi的界面
                                Intent intent = new Intent();
                                intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
                                startActivity(intent);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                ab.create();
                ab.show();

            }
        }
    }
    //动态注册销毁
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //动态注册广播须销毁
        unregisterReceiver(receiverJt);
    }
    //异步
    class MyAsnyTask extends AsyncTask{
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //解析字符串
            Gson gson=new Gson();
            News fromJson = gson.fromJson(s.toString(), News.class);
            list = fromJson.result.data;
            for (News.Result.Data da:list){
                Log.i("xxx",da.author_name+" "+da.title+" "+da.thumbnail_pic_s02);
                dao = new MyDao(MainActivity.this);
                dao.add(da.author_name,da.title,da.thumbnail_pic_s02);
            }
                adapter = new MyAdapter(MainActivity.this,list);
                xlist.setAdapter(adapter);
    }
        @Override
        protected String doInBackground(String... strings) {
            buffer = new StringBuffer();
            try {
                URL url=new URL(path);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                if(200==connection.getResponseCode()){
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                    String line=null;
                    while((line=reader.readLine())!=null){
                        buffer.append(line);
                    }
                    return buffer.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Intent... values) {
            super.onProgressUpdate(values);
        }
    }
}

你可能感兴趣的:(网络数据)