为什么很多游戏要加入loading滚动条呢?加入loading状态并不是为了使软件显得更专业美观,而是为了保证程序的运行内存不溢出。通常计算机/手机的存储系统分为:cup 的缓存,磁盘(或者手机中的存储用的的flash ram或者其他类型的可以持久保存的存储系统),运行内存。我们知道通常nokia s40的heap size为200kb大小,而通常我们加入程序和3张128*128的图片之后内存就趋于崩溃了,再加入声音和地图,程序的运算内存就显得太不够了。一般来讲,很多游戏仅仅在运行的时候把所有的资源一次性读入heap memory这样,我们在模拟器看到程序运行的状况就非常接近崩溃的边缘,如果不小心加入了新的图片,可能就没有足够的运算内存了。
我们如何解决heap size不够的事情呢?手机是不能够改变其heap size的,我们只有想办法控制heap memory的使用。最直观的做法就是:存储内存与运算内存的优化使用,当运算内存需要资源时从存储内存中调用,需要新的资源时,就把不需要的释放掉。下面我就结合一段代码解释我们是如何制作loading状态的。
众所周知,java是内置多线程的,我们可以使用两个线程来解决loading的问题,一个读资源的线程,一个绘制资源的线程。程序代码:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* loading演示
* @author gaogao
* */
class maincanvas
extends canvas
implements runnable {
//程序状态
static final int loading = 0;
static final int gameing = 1;
//程序状态控制器
int state = loading;
//主线程
thread thread = null;
//是否loading完毕,
boolean isloaded = false;
//内部类,新开读取资源的 线程
class loading
implements runnable {
//内线程
thread innerthread = null;
public loading() {
innerthread = new thread(this);
innerthread.start();
}
int counter = 100;
public void run() {
//模拟读取资源
//把下面的东西改成读取资源的代码即可
while (counter > 0) {
counter--;
try {
thread.sleep(20);
}
catch (exception ex) {}
}
//loading结束
isloaded = true;
}
}
loading loading = null;
public maincanvas() {
loading = new loading();
thread = new thread(this);
thread.start();
}
int loadingcounter = 0;
//绘制..
public void paint(graphics g) {
g.setcolor(0);
g.fillrect(0, 0, getwidth(), getheight());
switch (state) {
case loading: {
g.setcolor(0xffffff);
g.drawstring("loading" + ">>>>>".substring(0, loadingcounter),
getwidth() >> 1, getheight() >> 1,
graphics.hcenter graphics.top);
loadingcounter = ++loadingcounter % 5;
}
break;
case gameing: {
g.setcolor(0xffffff);
g.drawstring("game", getwidth() >> 1, getheight() >> 1,
graphics.hcenter graphics.top);
}
break;
}
}
public void run() {
while (true) {
try {
thread.sleep(100);
}
catch (exception ex) {
}
if (isloaded) {
loading = null;
state = gameing;
}
repaint(0, 0, getwidth(), getheight());
servicerepaints();
}
}
}
public class main
extends midlet {
maincanvas mc;
public void startapp() {
if (mc == null) {
mc = new maincanvas();
display disp = display.getdisplay(this);
disp.setcurrent(mc);
}
}
public void destroyapp(boolean bool) {}
public void pauseapp() {}
}
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器