1. 程式人生 > >廣播監聽網路請求條目展示

廣播監聽網路請求條目展示

package com.list.ypp;

import android.app.AlertDialog;
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.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.list.adapter.MyAdapter;
import com.list.bean.Data;
import com.list.bean.Json;
import com.list.net.NetUtil;
import com.google.gson.Gson;

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

public class MainActivity extends AppCompatActivity {
private ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = findViewById(R.id.list);
    //在廣播動態註冊許可權
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    NetUtilBroadcastReceiver receiver = new NetUtilBroadcastReceiver();
    registerReceiver(receiver, intentFilter);
}

private class NetUtilBroadcastReceiver extends BroadcastReceiver {
    //重寫
    @Override
    public void onReceive(Context context, Intent intent) {
        //判斷網路
        boolean net = NetUtil.isNet(context);
        if (net) {

            new MyAsync().execute();

            boolean wifi = NetUtil.isWifi(context);
            if (wifi) {
                Toast.makeText(context, "目前是wifi狀態", Toast.LENGTH_SHORT).show();
            } else {
                boolean wang = NetUtil.isWang(context);
                if (wang) {
                    Toast.makeText(context, "目前使用的是流量", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            Toast.makeText(context, "還沒網!", Toast.LENGTH_SHORT).show();
            //彈框到設定網路頁面
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("提示");
            builder.setMessage("網路");
            builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS));
                }
            });
            //取消
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
        }
    }

    //網路
    private class MyAsync extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            //網址:
            try {
                URL url = new URL("http://www.xieast.com/api/news/news.php");
                HttpURLConnection coonn = (HttpURLConnection) url.openConnection();
                coonn.setRequestMethod("GET");
                coonn.setReadTimeout(5000);
                coonn.setConnectTimeout(5000);
                if (coonn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    //請求成功
                    InputStream is = coonn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder builder = new StringBuilder();
                    String string = "";
                    while ((string = reader.readLine()) != null) {
                        builder.append(string);
                    }
                    return builder.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        //解析json串

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i("aaa", "onPostExecute: "+s);
            Gson gson = new Gson();
            Json json = gson.fromJson(s, Json.class);
            ArrayList<Data> data = json.getData();

            MyAdapter myAdapter = new MyAdapter(MainActivity.this, data);
            listView.setAdapter(myAdapter);
        }
    }
}

}
//網路判斷
package com.bwie.net;

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

public class NetUtil {
//網路
public static boolean isNet(Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return info.isAvailable();
}
return false;
}

//wifi
public static boolean isWifi(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifi != null) {
        return true;
    }
    return false;
}

//流量
public static boolean isWang(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wang = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (wang != null) {
        return true;
    }
    return false;
}

}
//資料類自擬
//介面卡
package com.bwie.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bwie.bean.Data;
import com.bwie.ypp.R;

import java.util.List;

public class MyAdapter extends BaseAdapter {
private Context context;
private List list;

public MyAdapter(Context context, List<Data> list) {
    this.context = context;
    this.list = list;
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = View.inflate(context, R.layout.pipi_layout, null);
        holder = new ViewHolder();
        holder.textView1 = convertView.findViewById(R.id.textView1);
        holder.textView2 = convertView.findViewById(R.id.textView2);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.textView1.setText(list.get(position).getTitle());
    holder.textView2.setText(list.get(position).getDate());
    return convertView;
}

class ViewHolder {
    private TextView textView1, textView2;
}

}