Running Background Applications - BLACKBERRY

While an application, by default, will exit when the last screen is closed, you can override this behavior to send an application to the background instead, meaning that the UI will not be displayed, but the application will continue to run as the user performs other tasks. Running applications in the background is useful in the following situations:

  • You want your application to periodically check for changes on the device or for events. For example, the BlackBerry Messages application always runs to check for incoming mail.
  • You want to periodically download new information from the network. Several weather and stock applications use this approach.
  • You need to maintain a connection to an external server. An instant messaging application might need to maintain a connection to the messaging server.

Detecting Backgrounding or Foregrounding

An application can be sent to the background if a user when presses the red phone key or explicitly switches tasks. You can detect this background status by overriding the UiApplication.deactivate method. Similarly, you can detect your application coming back into the foreground by overriding UiApplication.activate. Let’s modify HelloWorldApp to display a message when Hello World goes to the background or comes to the foreground:

#START## public class HelloWorldApp extends UiApplication { private HelloWorldMainScreen mainScreen; public HelloWorldApp() { mainScreen = new HelloWorldMainScreen(); pushScreen(mainScreen); } public void deactivate() { mainScreen.appendLabelText("Went to background"); } public void activate() { mainScreen.appendLabelText("Came to foreground"); } /** * @param args */ public static void main(String[] args) { HelloWorldApp app = new HelloWorldApp(); app.enterEventDispatcher(); } }

When you run this application, you’ll immediately see a “Came to foreground” message. The message is displayed because of the initial activation of the application. Press the red button, and then select the icon a few times to send the application back and forth from foreground to background. You’ll see something like Figure.

Hello World after going between the background and foreground a few times.

Hello World after going between the background and foreground a few times

Sending Your Application to the Background

You can send your application to the background using the UiApplication. request Back ground() method. To make Hello World go to the background rather than exit when the user closes the main screen, let’s override Screen.close() in HelloWorldMainScreen:

Now, pressing the escape key or selecting Close from Hello World will actually send the application to the background. You can test that this produces the same messages as in the example.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status