先写一个Handler
@SuppressLint("HandlerLeak")
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==0){
String json= (String) msg.obj;
Toast.makeText(getActivity(),json.toString(),Toast.LENGTH_LONG).show();
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray data = jsonObject.getJSONArray("data");
listView.setAdapter(new MyAdapter(getActivity(),data));
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
在onCreateView中进行广播
receiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(receiver,intentFilter);
用广播方法进行判断
//定义广播监听网络状态
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//判断是否有网
boolean b = NetWorkUtils.isNetWorkConnection(context);
//有网识别网络类型
if(b){
//调用网络请求方法
getHttpData();
boolean wifi = NetWorkUtils.isWifi(context);
if(wifi){
Toast.makeText(context, "wifi", Toast.LENGTH_SHORT).show();
}
boolean mobile = NetWorkUtils.isMobile(context);
if(mobile){
Toast.makeText(context, "mobile", Toast.LENGTH_SHORT).show();
}
}else{
//没网 -----弹框-----设置网络提示
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_WIRELESS_SETTINGS));
}
});
//no按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
}
获取数据
private void getHttpData() {
new Thread(new Runnable() {
@Override
public void run() {
//创建url
String path = "http://www.xieast.com/api/news/news.php";
try {
URL url = new URL(path);
//打开网络连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式
conn.setRequestMethod("GET");
//延时
conn.setConnectTimeout(5000);
//获取状态码
int code = conn.getResponseCode();
if(code==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);
}
//发送消息
String json = bos.toString();
Message message = new Message();
message.obj=json;
message.what=0;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(receiver);
}
在另一个页面
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag02,null,false);
listView = view.findViewById(R.id.listview_2);
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(path);
return view;
}
//AsyncTask
private class MyAsyncTask extends AsyncTask<String,Void,String> {
//接收path参数
@Override
protected String doInBackground(String... strings) {
String url = strings[0];
//创建URL
try {
URL url1 = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
//请求方法
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
//状态码
int responseCode = connection.getResponseCode();
if(responseCode==200){
//获取网络数据
InputStream inputStream = connection.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;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Gson gson = new Gson();
JsonBean jsonBean = gson.fromJson(s, JsonBean.class);
ArrayList<Data> data = jsonBean.getData();
//适配器
listView.setAdapter(new MyAdapter_2(getActivity(),data));
}
}