Android 优酷

来源:互联网 发布:淘宝母婴用品好做吗 编辑:程序博客网 时间:2024/06/01 01:33

服务器端:

<?xml version="1.0" encoding="UTF-8"?><channels><channel id="1"><name>一个人</name><time>2012-02-02</time><count>12</count><icon>http://172.16.40.157:8080/web/a.jpg</icon></channel><channel id="2"><name>2个人</name><time>2012-02-02</time><count>112</count><icon>http://172.16.40.157:8080/web/b.jpg</icon></channel></channels>

优酷:

channel.java:

package cn.itcast.youku.domain;public class Channel {private String id;private String name;private String time;private int count;private String icon;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getTime() {return time;}public void setTime(String time) {this.time = time;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}public String getIcon() {return icon;}public void setIcon(String icon) {this.icon = icon;}}
ChannelService.ajva:

package cn.itcast.youku.service;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import android.util.Xml;import cn.itcast.youku.domain.Channel;public class ChannelService {public static List<Channel> getChannels (InputStream is ) throws Exception{XmlPullParser parser = Xml.newPullParser();parser.setInput(is, "utf-8");List<Channel> channels = new ArrayList<Channel>();    int type =parser.getEventType();Channel channel = null;while(type!=XmlPullParser.END_DOCUMENT){switch (type) {case XmlPullParser.START_TAG:if("channel".equals(parser.getName())){channel = new Channel();String id = parser.getAttributeValue(0);channel.setId(id);}else if("name".equals(parser.getName())){String name = parser.nextText();channel.setName(name);}else if("time".equals(parser.getName())){String time = parser.nextText();channel.setTime(time);}else if("count".equals(parser.getName())){String count = parser.nextText();channel.setCount(Integer.parseInt( count));}else if("icon".equals(parser.getName())){String icon = parser.nextText();channel.setIcon(icon);}break;case XmlPullParser.END_TAG:if("channel".equals(parser.getName())){channels.add(channel);channel = null;}break;}type = parser.next();}return channels;}}
ImageUtil.java:

package cn.itcast.youku.service;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import cn.itcast.youku.util.StreamTool;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;public class ImageUtil {/** * 获取网络address地址对应的图片 * @param address * @return bitmap的类型  */public static Bitmap getImage(String address) throws Exception{//通过代码 模拟器浏览器访问图片的流程 // http://xxx.xxx/a.jpgint start = address.lastIndexOf("/");String iconname = address.substring(start+1, address.length());File file = new File(Environment.getExternalStorageDirectory(),iconname);FileOutputStream fos = new FileOutputStream(file);URL url = new URL(address);HttpURLConnection conn =  (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000);//获取服务器返回回来的流 InputStream is = conn.getInputStream();byte[] result = StreamTool.getBytes(is);//把图片信息 保存到sd卡fos.write(result);fos.flush();fos.close();Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);return bitmap;}}
NetUtil.java:

package cn.itcast.youku.service;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class NetUtil {/** * 获取服务器频道信息返回回来的输入流 *  * @param address *            频道信息的jsp或者servlet的地址 * @return inputstream */public static InputStream getChannelStream(String address) throws Exception {URL url = new URL(address);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");int code = conn.getResponseCode();if (code == 200) {return conn.getInputStream();}return null;}}
StreamTool.java:

package cn.itcast.youku.util;import java.io.ByteArrayOutputStream;import java.io.InputStream;public class StreamTool {/** * 把一个inputstream里面的内容转化成一个byte[]  */public static byte[] getBytes(InputStream is) throws Exception{ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while((len = is.read(buffer))!=-1){bos.write(buffer, 0, len);}is.close();bos.flush();byte[] result = bos.toByteArray();System.out.println(new String(result));return  result;}}
DemoActivity.java:

package cn.itcast.youku;import java.io.File;import java.io.InputStream;import java.util.List;import cn.itcast.youku.domain.Channel;import cn.itcast.youku.service.ChannelService;import cn.itcast.youku.service.ImageUtil;import cn.itcast.youku.service.NetUtil;import android.app.Activity;import android.graphics.Bitmap;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class DemoActivity extends Activity {private ListView lv;private List<Channel> channels;private LayoutInflater inflater;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// inflater = (LayoutInflater)// getSystemService(LAYOUT_INFLATER_SERVICE);inflater = LayoutInflater.from(this);lv = (ListView) this.findViewById(R.id.lv);String address = getResources().getString(R.string.serverurl);try {InputStream is = NetUtil.getChannelStream(address);channels = ChannelService.getChannels(is);} catch (Exception e) {Toast.makeText(this, "获取数据失败", 0).show();e.printStackTrace();}// 填充listview的数据lv.setAdapter(new MyAdapter());lv.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {Channel chanel = (Channel) lv.getItemAtPosition(position);String channelid = chanel.getId();Toast.makeText(DemoActivity.this, "提交 " + channelid + "到服务器", 0).show();}});}private class MyAdapter extends BaseAdapter {@Overridepublic int getCount() {// TODO Auto-generated method stubreturn channels.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn channels.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View view = inflater.inflate(R.layout.item, null);Channel channel = channels.get(position);ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);TextView tv_count = (TextView) view.findViewById(R.id.tv_count);TextView tv_name = (TextView) view.findViewById(R.id.tv_name);TextView tv_time = (TextView) view.findViewById(R.id.tv_time);// 这句代码会产生问题么?tv_count.setText("点播次数 " + channel.getCount());tv_name.setText(channel.getName());tv_time.setText("播放时间 " + channel.getTime());String address = channel.getIcon();int start = address.lastIndexOf("/");String iconname = address.substring(start + 1, address.length());File file = new File(Environment.getExternalStorageDirectory(),iconname);if (file.exists() && file.length() > 0) {// 如果存在 就直接使用 sd卡的文件iv_item.setImageURI(Uri.fromFile(file));System.out.println("使用缓存");} else {// 如果不存在 才去下载网络上的图片try {Bitmap bitmap = ImageUtil.getImage(address);iv_item.setImageBitmap(bitmap);System.out.println("下载新的图片");} catch (Exception e) {e.printStackTrace();iv_item.setImageResource(R.drawable.default_icon);}}return view;}}}
item.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@drawable/background"    android:orientation="horizontal" >    <ImageView        android:id="@+id/iv_item"        android:layout_width="80px"        android:layout_height="60px"        android:src="@drawable/ic_launcher" />    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="vertical" >        <TextView            android:id="@+id/tv_name"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:text="标题"            android:textColor="@android:color/black"            android:textSize="16sp" />        <LinearLayout            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:orientation="horizontal" >            <TextView                android:id="@+id/tv_time"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="播放时间"                android:textColor="@android:color/darker_gray"                android:textSize="10sp" />            <TextView                android:layout_marginLeft="30dip"                android:id="@+id/tv_count"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="播放次数 "                android:textColor="@android:color/darker_gray"                android:textSize="10sp" />        </LinearLayout>    </LinearLayout></LinearLayout>
main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@android:color/white"    android:gravity="center_horizontal"    android:orientation="vertical" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/summary"        android:textColor="@android:color/darker_gray"        android:textSize="25sp" />    <ListView        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:id="@+id/lv"          >    </ListView></LinearLayout>

0 0