深入MIDIet State Change Exception

分类: J2ME   出处:iocblog整理  更新时间:2008-07-09   添加到收藏  

  当midiet程序运行时出现错误的时候,应用程序管理器(application manager)会发出这个异常(exception). 在midiet类中也有两个方法可以发出这个异常(exception): destroyapp()和startapp().
  
  下面是一个捕捉和发送例外的例子。这个简单的midiet显示一个form和一个关闭程序的按钮(显示exit).
  
  创建这个例子的时候,我们会有这个问题:当按下关闭按钮或者应用程序管理器(application manager)要关闭这个midiet的时候,如果midiet正在下载程序,会发生什么情况?我们可以抛出异常(exception)而不是马上关闭程序。也就是说,下载请求不应在此时被关闭。应用程序管理器会在以后重试。
  
  这个例子如何工作:当使用者第一次按下exit按钮,我们调用destroyapp(false)方法。这里传入参数false告诉方法这个请求不是无条件的,而且我们将会抛出midietstateexception异常.这个异常(exception)会在commandaction()里被捕捉到,同时会设置一个标志,这个标志意味着我们将可以关闭程序. 这样,当我们再一次按下exit按钮的时候。midiet将要继续运行直到exit按钮第二次被按下。
  
  注意:以下例子基于midp和cldc 1.0.3.
  
  1. java源代码:
  /*----------------------------------------------------
  * a look inside midletstatechangeexception and the
  * destroyapp() method
  *
  * www.corej2me.com
  *---------------------------------------------------*/
  
  import javax.microedition.midlet.*;
  import javax.microedition.lcdui.*;
  
  public class exceptiontest extends midlet implements commandlistener
  {
  private display display;       // reference to display object
  private form frmmain;         // a form
  private command cmdexit;       // a command to exit the midlet
  private boolean safetoexit = false;  // is it safe to exit the midlet?
  
  public exceptiontest()
  {
  display = display.getdisplay(this);
  
  cmdexit = new command("exit", command.screen, 1);
  frmmain = new form("test exception");
  frmmain.addcommand(cmdexit);
  frmmain.setcommandlistener(this);
  }
  
  // called by application manager to start the midlet.
  public void startapp()
  {
  display.setcurrent(frmmain);
  }
  
  // we are about to be placed in the paused state
  public void pauseapp()
  {
  }
  
  // we are about to enter the destroyed state
  public void destroyapp(boolean unconditional) throws midletstatechangeexception
  {
  system.out.println("inside destroyapp()");
  
  // if we do not need to unconditionally exit(来源 www.iocblog.net)
  if (unconditional == false)
  {
  system.out.println("requesting not to be shutdown");
  throw new midletstatechangeexception("please don't shut me down.");
  }
  }
  
  // check to see if the exit command was selected
  public void commandaction(command c, displayable s)
  {
  if (c == cmdexit)
  {
  try
  {
  // is it ok to exit?
  if (safetoexit == false)
  destroyapp(false);
  else
  {
  destroyapp(true);
  notifydestroyed();
  }
  }
  catch (midletstatechangeexception excep)
  {
  safetoexit = true;  // next time, let's exit
  system.out.println(excep.getmessage());
  system.out.println("resuming the active state");
  }
  }
  }
  }