Tag: background

Programmatically Reboot a BlackBerry Device

if you curious about how to programmatically reboot a BlackBerry Device,
there’s no specific API to do it.
but, you should start your curiosity from how you reinstall an application,
sometime you need to reboot your device.

here’s how to programmatically reinstall a module, so the BlackBerry will ask to reboot..

  1. Create a dummy.cod module
  2. public class Dummy extends Application{
    
    	public static void main( String[] args )
    	{
    	    new Dummy().enterEventDispatcher();
    	}
    }
  3. Create new BlackBerry project (reboot project) and include the dummy.cod in the project
  4. In the reboot project, install the dummy.cod
  5. Run the dummy application in the background
  6. Uninstall the dummy application, after removing dummy.cod the BlackBerry will ask to reboot
  7. 	public  void reset() throws IOException, ApplicationManagerException {
    
    		// load the dummy cod file
    		byte[] cod = IOUtilities.streamToBytes(getClass().getResourceAsStream("/dummy.cod"));
    		//create new module
    		int	newHandle = CodeModuleManager.createNewModule(cod.length,
    				cod, cod.length);
    		//install the module
    		if (newHandle != 0) {
    			int savecode = CodeModuleManager.saveNewModule(newHandle, true);
    			if (savecode == CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN)
    				System.out
    				.println("The operation completed successfully; a module was overwritten and marked for deletion in the process.");
    		//now run the dummy application in background
    		ApplicationDescriptor appDesc = CodeModuleManager.getApplicationDescriptors(newHandle)[0];
    		ApplicationManager.getApplicationManager().runApplication(appDesc, false);
    		CodeModuleManager.deleteModuleEx(newHandle, true);
    		}
    		//restart the blackberry if reuired
    		if (CodeModuleManager.isResetRequired())
    			CodeModuleManager.promptForResetIfRequired();
    
    		//if you want to automate the reboot.
    		EventInjector.TrackwheelEvent moveEvent =  new EventInjector.TrackwheelEvent( EventInjector.TrackwheelEvent.THUMB_ROLL_UP, 1, 1 );
    		EventInjector.KeyCodeEvent pressEndKey = new EventInjector.KeyCodeEvent(
    				KeyCodeEvent.KEY_DOWN, (char) Keypad.KEY_ENTER , 0, 100);
    		EventInjector.KeyCodeEvent releaseEndKey = new EventInjector.KeyCodeEvent(
    				KeyCodeEvent.KEY_UP, (char) Keypad.KEY_ENTER, 0, 100);
    
    		try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    		e.printStackTrace();
    		}
    		EventInjector.invokeEvent(moveEvent);
    		EventInjector.invokeEvent(pressEndKey);
    		EventInjector.invokeEvent(releaseEndKey);
    		Status.show("device is restarting");
    	}

[1] http://blog.vimviv.com/blackberry/programmatically-reboot-blackberry-device/
[2] http://supportforums.blackberry.com/t5/Java-Development/How-can-I-programmatically-reset-a-blackberry/td-p/116854


Process incoming data (queue overflow)

When you develop applications for the BlackBerry smartphone, any network communication or lengthy data processing should be performed in its own thread. This is easy to realize for network input/output (I/O) because network connections must be initiated in their own thread, otherwise a deadlock situation may occur.[1]

When an application performs lengthy processing on the main event thread, the BlackBerry smartphone user can perceive the application to be slow because it is unable to process input commands. In an extreme situation, the application can close if it blocks or ties up the main event thread. If an application ties up the main event thread, the system is unable to dispatch messages to it (for example, BlackBerry smartphone user input, UI updates or network I/O). If the application message queue exceeds its limit, the application is terminated with the one of the following errors[2]:

Process [application name] killed due to message queue overflow

or

Uncaught Exception: [ApplicationName] is not responding; process terminated

Cause
An application is blocking the main event thread.

The main event thread processes system messages. Blocking this thread prevents system messages from being processed and can lead to a message queue overflow.

Because there is a finite amount of storage space for messages, the issue is caused when these messages are not being processed. If an application stops processing messages for a long period of time, the system assumes that the application has stopped responding and is no longer functioning as expected. This is the reason why the process was terminated.

Resolution
Move long processes or processes that block to a separate background thread.

Application stops responding when opening a connection[3]

Flow of what is occurring

  • Application opens connection
  • UI pushing dialog box to the foreground
  • BlackBerry is now locked

Flow of what should occur

  • Application places a connection into a thread
  • Application runs the connection in a thread off of the main event thread
  • UI pushes dialog box to the foreground and thread execution is currently paused
  • User is notified of connection and accepts
  • System returns execution to the connection thread

[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800563/How_To_-_Process_incoming_data.html?nodeid=1162112&vernum=0
[2] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800783/Support_-_Process_[ApplicationName]_killed_due_to_message_queue_overflow.html?nodeid=826932&vernum=0
[3] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/796557/800451/800563/Support_-_My_Application_Hangs_When_Opening_a_Connection.html?nodeid=800455


Open a push listener connection

The BlackBerry Mobile Data Service is capable of pushing data to a third-party application so that data is always available to the user. There are two common scenarios in which a push connection would be opened[1]:

  • when an application runs
  • when the device starts and runs in the background
//run method from with a thread
public void run() {
     //For Background Listener threads it is import to add the delay
     //If the application starts and displays the “Allow Connection” dialogue
     //Before the home screen is available it’s possible to cause a UI lock
     while(RadioInfo.getSignalLevel()==RadioInfor.LEVEL_NO_COVERAGE)(
          try {
               Thread sleep(1000);
          } catch( Exception e ) {}
     }
     //Just add an extra wait to ensure the device is fully up and running
     //the user is looking at the home screen
     try {
          Thread sleep(3000);
     } catch( Exception e ) {}

     StreamConnection stream = null;
     InputStream input = null;

     try {
          for(;;){
               try {
                    Thread.sleep(1000);
                    System.out.printIn(‘eclBackgroundThread--ThreadRunning (just to be sure)”);
               } catch( Exception e ) {}
          synchronized(this) {
               //synchronize here so that we don’t end up creating a connection that is never closed
               //The URL will be http://: where  is the value that the push server also                needs
               //to use to post data
               _notify = (StreamConnectionNotifier)Connector open(URL);
               _connectionOpened = true;
          }

          //NOTE: the following will block until data is received
          stream = _notify acceptAndOpen();
          input = stream.openInputStream();

          //Read the received data in from the stream and process it accordingly
     } catch (IOException ioex) {}
}



[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/796557/800451/800662/How_To_-_Open_a_push_listener_connection.html?nodeid=1033505&vernum=0


Update GUI from background listener

detect gui,
getSingleton,
update status from background thread [1]

/**
 * FolderListenerGUI.java
 *
 * Author: Mark Sohm
 */

package com.samples.folderListener;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;

public class FolderListenerGUI extends UiApplication
{
  private MainScreen mainScreen;
  private static RichTextField newMailNotifier;

  public static void main(String[] args)
  {
    boolean startup = false;

    //Check parameters to see if the application was entered
    //through the alternate application entry point.
    for (int i=0; i<args.length; ++i)
    {
      if (args[i].startsWith("init"))
      {
        startup = true;
      }
    }

    if (startup)
    {
      //Entered through the alternate application entry point.
      //Enable folderlistener on startup.
      FolderListenerApp.waitForSingleton();
    } else
    {
      //Entered by selecting the application icon on the ribbon.
      //Start the FolderListenerGUI.
      FolderListenerGUI app = new FolderListenerGUI();
      app.enterEventDispatcher();
    }
  }

  public FolderListenerGUI()
  {
    //Pass a reference to the FolderListenerGUI
    //to the FolderListenerApp.
    FolderListenerApp.waitForSingleton().
      setFolderListenerGUI(this);

    //Initialize mainScreen.
    mainScreen = new MainScreen();

    //Initialize the fields.
    newMailNotifier = new RichTextField("No mail yet...",
      RichTextField.NON_FOCUSABLE);
    LabelField title = new LabelField("Folder Listener GUI",
      LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
    mainScreen.setTitle(title);
    mainScreen.add(newMailNotifier);

    //Display the main screen
    pushScreen(mainScreen);
  }

  //Update the RichTextField with a new mail message.
  public static void NewMailArrived()
  {
    newMailNotifier.setText("New mail arrived!");
  }

  //Remove the FolderListenerGUI instance from
  //FolderListenerApp on exit.
  protected void onExit()
  {
    //Remove the reference to FolderListenerGUI
    //from FolderListenerApp.
    FolderListenerApp.waitForSingleton().unsetFolderListenerGUI();
  }
}

/**
 * FolderListenerApp.java
 *
 */

package com.samples.folderListener;

import net.rim.blackberry.api.mail.*;
import net.rim.blackberry.api.mail.event.*;
import net.rim.device.api.system.*;
import net.rim.blackberry.api.mail.*;

public final class FolderListenerApp implements FolderListener {

  private FolderListenerGUI folderListenerGUI = null;
  //Long value: com.samples.folderListener
  public static final long RTSID_MY_APP = 0x7451402f595f81a5L;

  public FolderListenerApp()
  {
    try
    {
      //Get the store from the default instance.
      Store store = Session.getDefaultInstance().getStore();
      //Add the folder listener to the store.
      store.addFolderListener(this);
    }
    catch (Exception e)
    {
      System.out.println(e.toString());
    }
  }

  //Returns an instance of the running FolderListenerApp.
  public static FolderListenerApp waitForSingleton()
  {
    //Ensure this is a singleton instance.

    //Open the RuntimeStore.
    RuntimeStore store = RuntimeStore.getRuntimeStore();
    //Obtain the reference of FolderListenerApp.
    Object obj = store.get(RTSID_MY_APP);

    //If obj is null, there is no current reference
    //to FolderListenerApp. Start a new instance
    // of FolderListenerApp if one is not running.
    if (obj == null)
    {
      //Store a reference to this instance in the RuntimeStore.
      store.put(RTSID_MY_APP, new FolderListenerApp());

      return (FolderListenerApp)store.get(RTSID_MY_APP);
    } else
    {
      return (FolderListenerApp)obj;
    }
  }

  //Called when a new message is created.
  public void messagesAdded(FolderEvent e)
  {
    //Get the message that fired the folder event.
    Message orginalMessage = e.getMessage();
    //Get the folder the message is in.
    Folder messageFolder = orginalMessage.getFolder();

    //Is the new message in the Inbox?
    if (messageFolder.getType() == Folder.INBOX)
    {

      //Check if the FolderListenerGUI is running.
      if (folderListenerGUI != null)
      {

        //Grab the lock for the running FolderListenerGUI.
        folderListenerGUI.invokeAndWait(new Runnable()
        {
          public void run()
          {
            //Call the NewMailArrived method to update the
            //screen with a notification.
            folderListenerGUI.NewMailArrived();
          }
        });
      }
    }
  }

  //Passes in reference to the FolderListenerGUI that is running.
  public void setFolderListenerGUI(FolderListenerGUI folderGUI)
  {
    folderListenerGUI = folderGUI;
  }

  //Set the reference to the FolderListenerGUI to null
  //(when it is shut down).
  public void unsetFolderListenerGUI()
  {
    folderListenerGUI = null;
  }

  //Not used in this sample.
  public void messagesRemoved(FolderEvent e)
  {
  }
}

[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800783/How_To_-_Allow_a_background_listener_to_detect_and_update_a_GUI_application.html?nodeid=827026&vernum=0


auto-run startup application

BlackBerry application support auto-run at every startup.

if you want to create background application only use this [1]:

To create an auto-start application using the BlackBerry® Java® Plug-in for Eclipse®
  1. Double click on BlackBerry_App_Descriptor.xml found in the BlackBerry project.
  2. On the Application tab, check off Auto-run on startup.
  3. If you do not want an application icon to be shown on the home screen check the Do not display the application icon on the BlackBerry home screen check box.

To create an auto-start application using the BlackBerry JDE
   1. In the BlackBerry JDE, right-click the project and select Properties.
   2. On the Application tab, check the Auto-run on Startup check box.
   3. If you want your application to run in the background, and not appear on the ribbon, check the System Module check box.

else, if you want to create background application & ui application use this [2]:

The BlackBerry architecture allows applications to be started automatically in the background by the system without requiring the user to explicitly initialize them. This allows application threads to always run in the background with no user interface component. Alternate Entry Points can be used to launch the user interface (UI) component of the auto-started application when the user selects the icon from the ribbon. This feature allows application threads to be launched in the background that can be used for actions like listening for incoming push messages, pre-processing data, or initializing network communications with a server host.

After creating the projects for the original application, you will have to create another project for the UI entry point. Assuming that the thread to be run exists in the same project as the original application, follow these steps:

   1. Right-click the project node and select Properties.
   2. In the Properties window, select the Application tab.
   3. Verify the following options are checked: Auto-run on startup and System module (to register the thread with the system).
   4. Create another project under the same folder as the original project. Right-click the new project node and select Properties.
   5. Select the Application tab and select Alternate CLDC Application Entry Point from the Project type drop-down list. As shown in the attached file, select the name of the original project (for example, trafficreporter) from the Alternate entry point for drop-down list. Also specify the arguments that would launch the application using this alternate entry point (for example: gui).
   6. Modify the main() method of the original project as follows:

      public static void main(String[] args) {
           if ( args != null && args.length > 0 && args[0].equals("gui") ){
                // code to initialize the app
                theApp.enterEventDispatcher();
           } else {
                // code to launch the background thread }
           }
      }
   7. Add your application icon file to the this new entry point application and make it the ribbon icon.

The entry point application now consists only of an application icon and a parameter to pass to the main() method of the main application. There is no source code associated with this project. The main application contains all of the source code, including the thread to be started automatically.

Now, whenever the device is started, this main() method will be executed without any arguments, and the background thread will start. When the application icon is clicked from the main ribbon, the main() method will be executed with the argument specified in the above code sample ("gui") and the application can pop a screen to the foreground.

[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800901/How_To_-_Configure_an_application_to_start_automatically_when_the_device_is_turned_on.html?nodeid=800920&vernum=0
[2] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/796557/800738/800901/How_To_-_Setup_an_alternate_entry_point_for_my_application.html?nodeid=800820


lock the screen from background thread

this is sample how to lock the screen from background thread by pushing a Dialog.

private void notifyUser(String msg)
    {
        UiEngine ui = Ui.getUiEngine();
        EncodedImage icon = Theme.getIcon(false, true);
        Bitmap bm = null;
        if (icon != null) {
            bm = icon.getBitmap();
        } else {
            bm = Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION);
        }
        synchronized (Application.getEventLock()) {
            Screen screen = new Dialog(Dialog.D_OK, msg, Dialog.OK,
                    bm, Manager.VERTICAL_SCROLL) {

                protected void onUiEngineAttached(boolean attached) {

                    if (locked) {
                        locked = false;
                        foreGround();
                    }

                    super.onUiEngineAttached(attached);
                    addKeyListener(new myKeyPadListener());
                }
            };
            ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_SHOW_LOWER);
        }
    }
private void notifyUser(String msg) {
        UiEngine ui = Ui.getUiEngine();
        EncodedImage icon = Theme.getIcon(false, true);
        Bitmap bm = null;
        if (icon != null) {
            bm = icon.getBitmap();
        } else {
            bm = Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION);
        }
        synchronized (Application.getEventLock()) {
            Screen screen = new Dialog(Dialog.D_OK, msg, Dialog.OK, bm, Manager.VERTICAL_SCROLL) {

                protected void onUiEngineAttached(boolean attached) {
                    super.onUiEngineAttached(attached);
                    addKeyListener(new SalatKeyPadListener());
                    Timer tmr = new Timer();
                    TimerTask tt = new TimerTask() {

                        public void run() {
                            invalidate();
                        }
                    };
                    tmr.scheduleAtFixedRate(tt, 500, 500);
                }

                protected void onVisibilityChange(boolean visible) {
                    if (notified) {
                        CancelNotification();
                    }
                }

              public boolean onClose() {
                    if (notified) {
                        CancelNotification();
                    }
                    return super.onClose();
                }
            };
            ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_SHOW_LOWER);
        }
    }

[1] http://supportforums.blackberry.com/rim/board/message?board.id=java_dev&message.id=21625


  • Copyright © 1996-2010 vaks.in. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress