利用Handler访问网络数据

时间:2022-05-01 01:50:18

废话不多白吃,代码如下:

1.MainActivity

package com.yz.day11_22_handler;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView; import com.google.gson.Gson; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List; import static com.yz.day11_22_handler.R.id.lv_news; public class MainActivity extends AppCompatActivity { private static MyAdapter mAdapter;
private static ListView mLv_news; //创建Handler对象
static class MyHandler extends Handler
{ private final WeakReference<Activity> reference;
private List<Feed> feeds; public MyHandler(Activity activity)
{
reference = new WeakReference<Activity>(activity);
} @Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (reference.get() != null)
{
switch (msg.what)
{
case HttpUtils.DATA_JSON:
String json = (String) msg.obj;
//解析json数据
feeds = parseJson(json);
mAdapter.setData(feeds);
break;
case HttpUtils.DATA_IMAGE:
Bitmap bitmap = (Bitmap) msg.obj;
Bundle bundle = msg.getData();
String url = bundle.getString("url","http://litchiapi.jstv.com/Attachs/Article/252444/87015790b2724a13a46fbad8712c99dc_padmini.PNG");
Log.i("tag", "=============url"+url);
ImageView iv_conver = (ImageView) mLv_news.findViewWithTag(url);
if (iv_conver != null)
{
iv_conver.setImageBitmap(bitmap);
}
break;
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //获取控件
mLv_news = (ListView) findViewById(lv_news);
//创建Handler对象
MyHandler mHandler = new MyHandler(this);
//创建HttpUtils对象,传递数据
HttpUtils utils = new HttpUtils(mHandler);
mAdapter = new MyAdapter(utils);
mLv_news.setAdapter(mAdapter);
utils.getDataFromNetWork(Url.JSONURL,1);
}
private static List<Feed> parseJson(String json)
{
try {
JSONArray jsonArray = new JSONObject(json).getJSONObject("paramz").getJSONArray("feeds");
List<Feed> list = new ArrayList<>();
Gson gson =new Gson();
for (int i = 0;i < jsonArray.length();i++)
{
          //两种解析方式
// TypeToken<Feed> typeToken = new TypeToken<Feed>(){};
// Feed feed = (Feed) gson.fromJson(jsonArray.getJSONObject(i).getJSONObject("data").toString(), typeToken.getRawType());
JSONObject jsonObject = jsonArray.getJSONObject(i).getJSONObject("data");
Feed feed = new Feed();
feed.setChanged(jsonObject.getString("changed"));
feed.setSubject(jsonObject.getString("subject"));
feed.setSummary(jsonObject.getString("summary"));
feed.setCoverd(jsonObject.getString("cover"));
list.add(feed);
}
return list;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
} }
2.MyAdapter
package com.yz.day11_22_handler;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView; import java.util.List; /**
* Created by 于超 on 2016/11/22.
*/ public class MyAdapter extends BaseAdapter { private List<Feed> list ;
private HttpUtils utils;
public MyAdapter(HttpUtils utils)
{
this.utils = utils;
}
//定义一个方法用来添加数据
public void setData(List<Feed> list)
{
this.list = list;
notifyDataSetChanged(); }
@Override
public int getCount() {
return list != null?list.size():0;
} @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) { MyHolder myHolder;
if (view == null)
{
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_list,viewGroup,false);
myHolder = new MyHolder(view);
view.setTag(myHolder);
}else
{
myHolder = (MyHolder) view.getTag();
}
Feed feed = list.get(i);
myHolder.tv_subject.setText(feed.getSubject());
myHolder.tv_summary.setText(feed.getSummary());
myHolder.tv_changed.setText(feed.getChanged());
//获取图片地址
String imagePaht = feed.getCoverd();
String url_image = Url.BASEURL+imagePaht;
utils.getDataFromNetWork(url_image,2);
//为控件设置标签,以便通过标签查找获取
myHolder.iv_conver.setTag(url_image);
return view;
}
class MyHolder
{
private TextView tv_subject,tv_summary,tv_changed;
ImageView iv_conver; public MyHolder(View convertView)
{
tv_subject = (TextView) convertView.findViewById(R.id.tv_subject);
tv_summary = (TextView) convertView.findViewById(R.id.tv_summary);
tv_changed = (TextView) convertView.findViewById(R.id.tv_changed);
iv_conver = (ImageView) convertView.findViewById(R.id.iv_conver);
}
}
}
3.HttpUtils(在这里创建了一个线程池,看起来效率更高一点)
package com.yz.day11_22_handler;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* Created by Administrator on 2016/11/22.
*/ public class HttpUtils {
static final int DATA_JSON = 1;
static final int DATA_IMAGE = 2;
private static Handler mHandler;
private final ExecutorService mPool; public HttpUtils(Handler handler)
{
this.mHandler = handler;
//创建一个拥有6条子线程的线程池对象
mPool = Executors.newFixedThreadPool(6);
} public void getDataFromNetWork(final String path,final int type)
{
mPool.execute(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200)
{
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len =inputStream.read(buffer))!= -1)
{
baos.write(buffer,0,len);
}
byte[] data = baos.toByteArray();
//根据type的不同,选择获取不同的数据类型
switch (type)
{
case DATA_JSON:
String json = new String(data);
Message msg = Message.obtain();
msg.what = DATA_JSON;
msg.obj = json;
mHandler.sendMessage(msg);
break;
case DATA_IMAGE:
//将图片传递到handler
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.i("tag", "===============data"+new String(data));
Message msg1 = Message.obtain();
msg1.what = DATA_IMAGE;
msg1.obj = bitmap; Bundle bundle = new Bundle();
bundle.putString("url",path);
msg1.setData(bundle);
mHandler.sendMessage(msg1);
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}); }
}