WEB开发网
开发学院WEB开发Jsp 深入MIDIet State Change Exception 阅读

深入MIDIet State Change Exception

 2008-01-05 10:31:38 来源:WEB开发网   
核心提示:当MIDIet程序运行时出现错误的时候,应用程序治理器(application manager)会发出这个异常(exception). 在MIDIet类中也有两个方法可以发出这个异常(exception): destroyApp()和startApp().下面是一个捕捉和发送例外的例子,深入MIDIet State C

  当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
  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");
  }
  }
  }
  }

Tags:深入 MIDIet State

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接