首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2ME开发 >

J2ME 图片上载实例 简洁明了

2012-09-28 
J2ME 图片下载实例 简洁明了package com.wanchong/** * 作者:万冲 * QQ:569845790 * Mail:wanchong998@qq

J2ME 图片下载实例 简洁明了
package com.wanchong;
/**
* 作者:万冲
* QQ:569845790
* Mail:wanchong998@qq.com
*/
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class DMIDlet extends MIDlet{

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub

}

protected void pauseApp() {
// TODO Auto-generated method stub

}

protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
Display.getDisplay(this).setCurrent(new DCanvas());
}

}



package com.wanchong;
/**
* 作者:万冲
* QQ:569845790
* Mail:wanchong998@qq.com
*/
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class DCanvas extends Canvas implements Runnable{



Image image;

public DCanvas()
{
setFullScreenMode(true);
repaint();
//启动下载线程
new Thread(this).start();
}


protected void paint(Graphics g) {
// TODO Auto-generated method stub
g.setColor(0x0);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0xff0000);
g.drawString("正在下载中....", 0, 0, 0);
if(image != null)
{
g.drawImage(image, 0, 0, 0);
}
}


public void run() {
// TODO Auto-generated method stub
try {
connect();
} catch (Exception e) {
e.printStackTrace();
}

}

//String url = "http://www.hao123.com/images/logox3.gif";
String url = "http://www.sincol.net/uploads/allimg/2009-08/05162349-1-32N02.png";
public void connect() throws Exception
{
HttpConnection http = null;
InputStream is = null;
OutputStream os = null;
byte[] data = null;
try
{
http = getHttpConnection(url);

int code = http.getResponseCode();
// 返回200 表示连接成功
if (code == HttpConnection.HTTP_OK)
{
is = http.openInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = -1;
while ((ch = is.read()) != -1) {
baos.write(ch);
System.out.println(ch);
}
data = baos.toByteArray();

}
else
{
System.out.println("网络连接错误");
}
//下载图片数据完成后创建图片
if(data != null)
{
image = Image.createImage(data, 0, data.length);
repaint();
}

}
finally
{
if(os != null)
{
os.close();
os = null;
}

if(is != null)
{
is.close();
is = null;
}
if(http != null)
{
http.close();
http = null;
}
}
}


/**
* 取得一个URL的连接
* @param url
* @return
* @throws Exception
*/
private HttpConnection getHttpConnection(String url) throws Exception
{
HttpConnection http = (HttpConnection) Connector.open(url);
http.setRequestProperty("Content-Type", "application/octet-stream");//get
http.setRequestMethod(HttpConnection.GET);

return http;
}

}

热点排行