Thursday, October 27, 2011

Reset programmatically in Blackberry device

Create a dummy application

    public class DummyApp extends Application{ 
     
        public static void main( String[] args ) 
        { 
            new DummyApp().enterEventDispatcher(); 
        } 
    } 

Compile the code into .cod file and place in your project
let's say MyProject/res/DummyApp

in your main program add this method

    private void reset() {
        try {
               byte[] codData = getResource("/DummyApp");
           
            int dummycodhandle = CodeModuleManager.createNewModule(codData.length, codData, codData.length);
     
                //Save the module
            int result = CodeModuleManager.saveNewModule(dummycodhandle, true);
            if (result != CodeModuleManager.CMM_OK && result != CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN)
            {
                //The cod file was not saved.
                throw new Exception("Failed to save dummy cod.");
            }
                          
           int dummycodhandle2=CodeModuleManager.getModuleHandle("DummyApp");
           ApplicationDescriptor[] desc = CodeModuleManager.getApplicationDescriptors(dummycodhandle2);

           ApplicationManager.getApplicationManager().runApplication( desc[0], false );

           // Make sure the application is already started, assume 5 seconds is enough     
           Thread.currentThread().sleep(5000);
          
           CodeModuleManager.deleteModuleEx(dummycodhandle2,true);
           CodeModuleManager.promptForResetIfRequired();
        }
        catch (Exception e) {
            e.printStackTrace();
    }
    }
   
    private byte[] getResource(String name)
    {
        DataBuffer db = new DataBuffer();
        byte[] data = new byte[1024];
        DataInputStream input = new DataInputStream(UiApplication.getUiApplication().getClass().getResourceAsStream(name));
       
          int len = 0;
            try{
               while ( -1 != (len = input.read(data)) )
               {
                   db.write(data, 0, len);
               }
            }catch(Throwable e)
            {
                e.printStackTrace();
            }
            return db.getArray();                  
    }

When you want to ask your device to restart, just call the method reset()

2 comments:

Anonymous said...

Thread.currentThread().sleep(5000);

should be written as

Thread.sleep(5000);

since sleep is a static method

Ali Irawan (Wen) said...

Yeah it could be written as

Thread.sleep(5000);

Thanks for the update.