Wednesday, December 24, 2008

Pushing Web Content to BlackBerry Wireless Devices

            
            Deploying and enabling a web-based application on a BlackBerry wireless device allows for reduced development time by not creating a BlackBerry application. A Browser Push differs from a BlackBerry client push application as there is no requirement to develop a client to reside on the device. There are four types of Browser Push that can be sent to the BlackBerry wireless device.
  1. Browser Channel Push
  2. Browser Channel Delete Push
  3. Browser Content Cache Push
  4. Browser Message Push

Browser Channel Push


A Browser Channel Push sends a web page and two icons to the BlackBerry wireless device. The web page is stored in the cache of the BlackBerry Browser, and an icon is shown on the home screen of the device. An unread icon can be specified so that when a new Browser Channel Push arrives to the device, it will display the unread icon. After the user has opened and visited the page, the read icon is shown. This provides the user with a visual indication as to when a page has been updated. It's useful for a news service so that users are aware of when new data has arrived. The icons can even change with every push allowing an application to continually push different icons. This would be useful for a weather application updating the current weather conditions.

Browser Channel Delete Push


A Browser Channel Delete works in a similar, but opposite fashion of the Browser Channel Push. It will remove an icon on the BlackBerry Home screen that has been sent via a Browser Channel Push. Icons initiating from a Browser Channel Push can also be removed from the device itself.

Browser Content Cache Push


Browser Content Cache Push is the most discreet type of Browser Push. A Browser Content Push will push a web page to the BlackBerry wireless device and store it in the BlackBerry Browser's cache. The user is not informed in any way when this push takes place, or when the page has been updated.

Browser Message Push


Instead of creating an icon on the home screen of the BlackBerry wireless device, a Browser Message Push will arrive in the Inbox on the device. When the user opens the message, the default browser on the device is launched then opens the page. Unlike the Browser Channel Push or Browser Content Push, the web page is stored as a browser message instead of in the BlackBerry Browser's cache. This means that the page will be available until the message is deleted. It will not be removed from the BlackBerry Browser cache when other events (browsing, cache clear) take place. The message created from a Browser Message Push is not sent to, and will not appear in, a user's Inbox on their desktop. It is sent directly to the device.

How to push


Push applications can be created using any development language that is able to initiate a network connection and perform an HTTP post. A post to the BlackBerry MDS Server handles the delivery of the push to a BlackBerry wireless device. The post is made up of the standard html request headers, a few unique Browser Push headers and the web page being pushed (it is not required to send the web page when performing a Browser Channel Delete Push). The following additional http request headers are required for a Browser Push to take place.

 

Required

X-RIM-Push-Title
X-RIM-Push-Type

Optional

X-RIM-Push-Channel-ID
X-RIM-Push-UnRead-Icon-URL
X-RIM-Push-Read-Icon-URL
 
"The X-Rim-Push-Title" header holds the title that will appear on the home screen of the device for a Browser Channel Push, or in the subject of the message of a Browser Message Push. The "X-RIM-Push-Type" header holds the value that represents the type of push being sent. Possible values are:
  • Browser-Channel
  • Browser-Message
  • Browser-Content
  • Browser-Channel-Delete
The "X- RIM-Push-Channel-ID" header contains the URL of the page to be pushed to the device. This is not required when performing a Browser Message or Browser Content push. The "X-RIM-Push-UnRead-Icon-URL" and "X-RIM-Push-Read-Icon-URL" are optional headers that specify the URL of the icons to be used for a Browser Channel Push. If these are not specified then the default Browser Channel Push icons are used. These two headers are not required for Browser Message, Browser Content or Browser Channel Delete Push and may be omitted.
The page that is to be pushed is submitted once the headers are sent. It is recommended that this page resides on a web server, although it is not required. If it is not located on a web server, a user would be unable to refresh the page. If the page has been removed from the BlackBerry Browser cache (if a Browser Channel or Browser Content Push was used) they would be unable to view it. It is not required to send the actual page when performing a Browser Channel Delete.

Sample Java Push Application

           A sample Java based push application is included and documented with the BlackBerry JDE. The BlackBerry JDE is available in the JDE installation path: “$JDE_HOME$\samples\com\rim\samples\server\httppushdemo”

Sample Php Push Application

A sample php push application can be downloaded from this URL http://na.blackberry.com/eng/devjournals/resources/journals/jan_2005/phpPush.zip
 

Signing Your BlackBerry Application Before Deployment

Overview

  • Why the need to sign your BlackBerry code
  • Registering and obtaining signature keys
  • Signing your application

Why You Need to Sign Your Code

The concept of “controlled” API's has existed since BlackBerry 3.6 as a way for Research In Motion (RIM) to track the use of some API's for security and export control reasons. In practical terms, this means that in order to run an application on a handheld, you need to register and sign the application. Signing of applications is not required to run applications using the BlackBerry device simulator.

The BlackBerry API is divided into five groups. The first group includes all standard Java API's from MIDP and CLDC and some BlackBerry-specific API's. This group is open for all developers, and applications that use only these open API's require no signatures. The remaining four groups are all controlled API's: RIM Runtime API's, some BlackBerry API's, RIM Cryptography and Certicom Cryptography.

Registering and Obtaining Signature Keys

The registration process serves to verify the developer's identity. It involves downloading and filling out a registration form that you need to fax to RIM. There’s also a one-time processing fee associated with it. RIM will send you a set of signature keys after the registration form and fee are received.

Signing Your Application

Once you receive the signature keys from RIM, you need to install them on your development environment. The detailed instructions on how to do this can be found in the BlackBerry Java Developer Guide, Volume 2 - Advanced Topics. I recommend that you study this procedure, since installing the keys incorrectly will cause the signing process to fail.
Signing the application is very easy once the keys are installed. You need to manually start the Signature Tool from the Build menu in the JDE:

 
 


When you press the Request button, the Signature Tool submits a hash of the application to RIM's signing authority. The signing authority automatically returns the required signature, that is automatically appended to the application. The application can be loaded onto a device after this step.


Note that RIM does not receive a copy of your application, only a hash of the file(s). This allows them to determine the author of the application by matching the hash of the application against records of the hash kept by the signing authorities.

Where to Find More Information

You can find more information on this topic in the BlackBerry Java Developer Guide, Volume 2 - Advanced Topics.

Monday, December 22, 2008

Showing a manufacturer disclaimer during application installation

Overview

This code snippet demonstrates how to display a manufacturer disclaimer when an application is being installed. This behavior is required at least for VoIP applications that are meant to be sent to Symbian for signing.

This snippet can be self-signed.

data\disclaimer.txt

This is an example of the disclaimer text by Symbian for VoIP applications:

You are about to use , which is
developed and owned by . The
manufacturer of this device shall have no liability for
any aspect of the application whatsoever, including its
performance, call routing, intellectual property rights
or support.

PKG file

To display the disclaimer to the user, add the following line to the PKG file of your application:

"..\data\disclaimer.txt" - "", FILETEXT, TEXTEXIT

The FILETEXT install option indicates that a file is to be displayed to the user during the installation procedure. The file itself is not installed on the target device (the target location is empty).

The TEXTEXIT install option displays a dialog box with "positive" and "negative" buttons, such as Ok and Cancel. If the dialog returns true (the user pressed Ok), the software installer continues with the installation. If the dialog returns false (the user pressed Cancel), the software installer is exited and any files that have already been installed are removed.

Display phonenumber during incoming call

Display phonenumber during incoming call

If your application runs in background and if u want to display phonenumber during incoming call just implement this code in abstract method.
PhoneCall callInfo = Phone.getActiveCall();

if ( callInfo != null )
{
Telephone = callInfo.getDisplayPhoneNumber();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Status.show("incoming from: "+Telephone);
}
});

Running Existing MIDlets on the BlackBerry

To run a standard MIDlet on a Java-enabled BlackBerry device, you first need to convert the .jad and .jar files to the .cod format, using the rapc command-line tool that comes with RIM's JDE. You'll find rapc in the bin directory of your JDE installation. This command converts a MIDlet named "LoginMIDlet"

rapc import="c:\BlackBerryJDE3.6\lib\net_rim_api.jar" codename=LoginMIDlet -midlet jad=LoginMIDlet.jad LoginMIDlet.jar
You can load the resulting LoginMIDlet.cod file into your BlackBerry device from your desktop computer over a USB cable. Use the javaloader command, which can also be found in the bin directory of your JDE installation. I used this command to load LoginMIDlet.cod into my BlackBerry 7510:

javaloader -usb load LoginMIDlet.cod

Once the application is loaded into the BlackBerry, you can run it just as if it were a native application. You can use javaloader to delete applications from the BlackBerry as well as to load them. This command will remove LoginMIDlet.cod from the BlackBerry:
javaloader -usb erase -f LoginMIDlet.cod

Monday, November 24, 2008

Locking and Unlocking the Keypad in symbian c++

Locking and Unlocking the Keypad in Symbian c++

HEADER
    #include <aknkeylock.h>
 
LIB  
    avkon.lib 

Code to Lock the Keypad:
RAknKeyLock objKeyLock ;
objKeyLock.Connect();
if(!objKeyLock.IsKeyLockEnabled())
objKeyLock.EnableKeyLock();
objKeyLock.Close();
Code to Unlock the Keypad
RAknKeyLock objKeyLock ;
objKeyLock.Connect();
if(objKeyLock.IsKeyLockEnabled())
objKeyLock.DisableKeyLock();
objKeyLock.Close();
Regards,
Kannabiran.

Friday, October 31, 2008

Getting the incoming call's phone number

Getting the incoming call's phone number in Blackberry

If your application runs in background and if u want to display phone number during incoming call just implement this code in abstract method.

PhoneCall callInfo = Phone.getActiveCall();
if ( callInfo != null) {
Telephone = callInfo.getDisplayPhoneNumber();
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
Status.show("incoming from: "+Telephone);
}
}
);
}

Pausing the application for 1 second in Symbian

Pausing the Symbian app for 1 sec

TRequestStatus timerStatus;
RTimer timer;
timer.CreateLocal();
timer.After(timerStatus,1000000);
User::WaitForRequest(timerStatus);
timer.Close();

This article applies to Symbian and devices P800, P802, P900, P908, P910, M600, P990, W950



Start-up application in Blackberry

Start-up application in Blackberry

To have an application run on startup in Blackberry, right-click the project in the BlackBerry JDE and select Properties. Click the Application tab, and check the Auto-run on Startup check box. If you want your application to run in the background, and not show up on the ribbon at all, check the System Module check box.

Tuesday, June 24, 2008

Best BlackBerry Shortcuts

Home Screen Shortcuts
Now you'll need to hit your Phone icon or click the green phone button to dial a number and place a call, but you'll have access to all of the following shortcuts from your Home Screen via a single click of the corresponding letter key:
  • WAP Browser -- W
  • Alarm -- R
  • Tasks -- T
  • Calculator -- U
  • Options -- O
  • Address Book -- A
  • Search -- S
  • Notes -- D
  • Profiles -- F
  • Help -- H
  • Lock keypad -- K
  • Calendar -- L
  • Messages -- M
  • Browser -- B
  • BlackBerry Messenger -- N
  • Saved messages -- V
  • Compose -- C

Typing Shortcuts

  • To capitalize a letter with one click, hold down the letter key.
  • To insert a period, click the Space key twice.
  • Turn CAP Lock on by pressing the ALT key followed by the right Shift key. Turn it off by pressing either Shift key.
  • Turn Number Lock on by pressing the ALT key followed by the left Shift key. Turn it off by pressing either Shift key.
  • Type an accented letter or special character by holding the corresponding letter and scrolling left or right with the trackball.
  • Insert the current date into a message or document by pressing the L key followed by the D key and Space key.
  • Insert the current time into a message or document by pressing the L key followed by the T key and Space key.

Messaging (E-mail and SMS)

  • In e-mail inbox, press the S key to search for a sender or a word within a subject line, and any mail folder regardless of message was sent or received.
  • Within inbox, access the complete list of messages sent by hitting the ALT key followed by the O key.
  • Within inbox, access the complete list of messages received by hitting the ALT key followed by the I key.
  • Within inbox, access the complete list of SMS text messages received by hitting the ALT key followed by the S key.
  • Within inbox, access phone log by hitting the ALT key followed by the P key.
  • Within inbox, access voicemail log by hitting the ALT key followed by the V key.
  • To delete all messages sent or received before a specific date, highlight that date with the cursor, hit the BlackBerry Menu key, select Delete Prior and confirm selection.
  • To enable automatic spell checking of e-mail messages, click the Options icon on BlackBerry home screen. Then click Spell Check and select the Spell Check E-Mail Before Sending option.
  • To do a manual spell check, click the BlackBerry Menu key within a composed message and select Check Spelling.
  • When a message is being spell checked, suggested fixes to unrecognized words can be ignored by clicking the escape key.

When in a list of messages, or when reading a message:

T- Top
B- Bottom
Space bar- next page
Num shift + Space bar - previous page

When in a list of messages:
N- go to Next day
P- go to Prev day

Spreadsheet Attachments:

  1. Change the size of a column by pushing the W key.
  2. Go to a specific cell by pressing the G key.
  3. View contents of a cell by pressing the Space key.
  4. Search for text by clicking the F key, and then type the desired word.
  5. Switch to a different worksheet by pressing V and selecting the desired sheet.

Presentation Attachments:

  1. Skip to the next slide by pressing the N key.
  2. Return to the previous slide by clicking the P key.
  3. Start slideshow by pushing the S key.
  4. Stop slideshow by clicking the Escape key.
  5. Switch to a new view of the slideshow by clicking the M key.

Phone Functions

  1. Multitask while on phone calls by hitting the BlackBerry menu key during a call and then selecting Home Screen. You'll then have access to e-mail and other documents--though most BlackBerrys don't allow for simultaneous voice and data transfer, so Internet access is unavailable while on calls.
  2. Find specific contacts from your BlackBerry home screen by pressing keys for first and last initials, with a space between them. If more than one contact has the same initials, scroll to the appropriate contact.

BlackBerry Browser

  1. Bring up the Enter Web Address field from any Web page by pressing the G key.
  2. Insert a period in Web address by clicking the Space key.
  3. Insert a back slash in Web address by clicking either the Left Shift or Right Shift keys and then hitting Space.
  4. Add an item to bookmarks list by clicking the A key.
  5. Bring up your bookmark list by clicking the K key.
  6. Refresh a Web page by clicking the R key.
  7. Display a list of the last 20 pages visited by hitting the I key.
  8. Open browser options with the O key.

Back to Basics: Starts and Stops

  1. To put device into Standby Mode so keys cannot be pressed while it's not in use, hold down the Mute key for a second or two. Undo Standby Mode by holding Mute for another couple of seconds.
  1. If BlackBerry slows down, starts malfunctioning or freezing, always try removing the battery and SIM card--if the device has one--and waiting a few seconds before reinserting it. Ninety-five percent of the issues Aflac BlackBerry users experience are resolved by simply removing the battery, according to Genet.

Software Test Plan for a mobile application

Software Test Plan for a mobile application

1 Introduction

1.1 Overview

This document explains the testing methodology for a mobile application, and is to be used as a guide for the testing activity.

The intended audience for this document: The Project Managers Product development team members Test engineers

1.2 Scope

The scope of testing as explained in the document is to test the operating characteristics of an application that runs on mobile devices supporting J2ME. The tests are organized by requirement category such as usability, functionality, security, etc. The procedure for carrying out testing in terms of preparation of test cases, test environment setup, defects logging and reporting are explained.

The document does not address the following:

  • Content censorship (i.e. assessment against standards for violence, gambling, political messaging etc.) for the purpose of preventing the deployment or sale of an application. Distribution, DRM etc.
  • Testing requirements specific to a particular manufacturer’s (or network operator’s) device, user interface, and standards (e.g. WAP) implementation.


1.3 References Mention the documents of references

1.4 Acronyms

Acronym Expansion
DRM Digital Rights Management
J2ME™ Java™ 2 Platform Micro Edition

2 Test Plan and Strategy

2.1 Unit Testing

2.1.1 Objective

The objective of Unit testing is to verify that a particular module of source code is working properly. Unit tests are designed to test a single class or component or module in isolation. Developers run unit tests, and only for the components they are working on.

2.1.2 Entry Criteria

  • Test cases are reviewed
  • Build is complete and self test done
  • Unit Test environment is set up

2.1.3 Exit Criteria

  • All planned test cases are executed
  • Units are working as per the expected results
  • Defect are fixed in the code and tracked to closure

2.1.4 Logging Tests and Reporting

The developer will fix the defects that are found in unit testing. Additionally, if defects corresponding to other modules or components are found during unit testing, these will be reported.

2.2 System Testing

In System Testing, separate units (packages / modules / components), or groups of units of the application are united and tested as a completely merged application. The purpose of System Testing is to identify defects that will only surface when a complete system is assembled. Verification of the system at this stage might include: functionality, usability, security, installation etc. It is intended to validate the application as a whole.

The rest of this document mainly explains how System Testing is performed by the testing team.


2.2.1 Testing Procedure

The steps in testing consist of:  Creation of all the test scenarios and test cases

  • Preparation of a test case document that has a brief description of the test case , steps to conduct tests and expected result
  • Defect Report generation.

Outlined below are the main test types that will be performed

a. Application Characteristics (AC) – Information about the application is provided to help the testing team in the testing work.

b. Stability (ST) – Focusing on the application being stable on the device.

c. Application Launch (AL) – Once an application is loaded it must start (launch) and stop correctly in relation to the device and other applications on the device.

d. User Interface (UI)

e. Functionality (FN) - Documented features are implemented in the application and work as expected. Sources for the information are user manuals, formatted application specification documents and online documentation.

f. Connectivity (CO) – the application must demonstrate its ability to communicate over a network correctly. It must be capable of dealing with both network problems and server-side problems.

g. Personal Information Management (PI) - The application accessing user information needs to be able to do it in an appropriate manner and not to destroy the information.

h. Security


2.3 Regression Testing

This is an additional step, and is done prior to taking up system testing which is to test new functionality. Regression testing consists of running a set of standard tests to ensure that old functionality has not been broken by new functionality. Regression tests are also run if a new release is made after fixing a number of defects.

2.4 Pass/Fail Conditions

It is expected that an application must pass all the tests in each test category to be successful.

2.5 Test Report

For each report, the following information is provided: • The name of the application

  • The version number of the application
  • Device used for testing
  • Device firmware version

For each error reported, the following information is provided:

  • Description of the error
  • Frequency of occurrence of error: Systematic or Random or Once
  • Location of the error in the application
  • Steps to reproduce the error

3 Schedules for Testing

This will be decided in consultation with the project manager.


4 Risks and Assumptions

4.1 Risks:

The following may impact the test cycle:

  • Device availability
  • Any new feature addition/modification to the application which is not communicated in advance.
  • Any delay in the software delivery schedule including defect fixes. Any changes in the functional requirements since the requirements were signed-off/formulated

4.2 Assumptions:

  • Every release to QA will accompany a release note specifying details of the features implemented and its impact on the module under test.
  • All "Show-Stopper" bugs receive immediate attention from the development team.
  • All bugs found in a version of the software will be fixed and unit tested by the development team before the next version is released
  • All documentation will be up-to-date and delivered to the system test team.
  • Devices, Emulators and other support tools will be fully functional prior to project commencement.
  • In case of lack of required equipment or changes in the feature requirements, the test schedules may need to be reviewed.

5 Entry and Exit Criteria

5.1 Entry Criteria

  • Development of the application is complete
  • Successful completion of unit testing for the applications
  • Release of software to the test environment
  • Dedicated resources are allocated
  • Approved test bed to carry out system testing.
  • Test environment is up and working

5.2 Exit Criteria

The Following is the criteria when the testing will be stopped for this module:

  • All test cases have been executed and at least 95% have passed successfully. The remaining 5% do not impact critical functionality
  • All test results have been evaluated and accepted.
  • There are no showstoppers or high criticality defects unresolved or outstanding
6 Test Metrics

Following metrics will be captured and reported as part of the Test

  • Summary Report
  • Test Design effort
  • Test execution effort
  • Number of Test Cases executed
  • Number of Defects and their classification
  • Test Coverage (Number of test cases executed/Number planned)

7 Logging Tests and Reporting

Some third party applications will be used for reporting bugs found during test execution. The QA team will log defects in the tool as testing progresses.

8 Roles and Responsibilities


The roles and responsibilities of the testing team for the project are as follows:

8.1 Project Manager / Test Manager Responsibilities:

  • Overall responsibility for managing the testing process
  • Approval of test documents
  • Approval of inspections/reviews done as per the test plan
  • Providing resources for the project

8.2 Test Lead

Responsibilities:

  • Requirement gathering
  • Planning and estimating for testing
  • Tracking and monitoring the testing as per the test plan
  • Reporting the project status

8.3 Test Engineer

Responsibilities:

  • Creating the test cases as per the test plan
  • Executing the test cases
  • Documenting the results and logging errors.
9 Deliverables
  • Test Plan
  • Test Cases Document – Document with a description and expected result for each test case.
  • Test Results – The Pass/Fail status of each test cases and the list of issues.

Wednesday, April 9, 2008

Brew application development - Get Started

Creating and selling applications using the BREW® platform follows this simple four step process:
  1. Download the BREW SDK®
    Download the FREE BREW SDK and start developing BREW applications today!
    The next three steps apply to developers writing applications for BREW Operators using the standard BREW business model.
  2. Become a BREW Developer/Authentication
    Authenticated BREW Developers receive the benefits of the Alliance Program.
  3. Application Development
    Authenticated developers are given access to the BREW Developer Extranet, which contains the tools and information necessary to develop applications for specific BREW devices.
  4. Application Testing and Distribution
    Application testing is performed by an independent third party. Application distribution is managed by the developer via the BREW Developer Extranet.

Getting the IMSI number from mobile devices

An International Mobile Subscriber Identity, or IMSI [im-zee], is a unique number associated with all GSM and Universal Mobile Telecommunications System (UMTS) network mobile phone users. It is stored in the Subscriber Identity Module (SIM) inside the phone and is sent by the phone to the network. It is also used to acquire other details of the mobile in the Home Location Register (HLR) or as locally copied in the Visitor Location Register. In order to avoid the subscriber being identified and tracked by eavesdroppers on the radio interface, the IMSI is sent as rarely as possible and a randomly generated TMSI is sent instead.

The IMSI is used in any mobile network that interconnects with other networks, in particular CDMA and EVDO networks as well as GSM nets. This number is provisioned in the phone directly or in the R-UIM card (a CDMA analogue equivalent to a SIM card in GSM)

An IMSI is usually 15 digits long, but can be shorter (for example MTN South Africa's IMSIs are 14 digits). The first 3 digits are the Mobile Country Code, and is followed by the Mobile Network Code (MNC), either 2 digits (European standard) or 3 digits (North American standard). The remaining digits are the mobile subscriber identification number (MSIN) within the network's customer base.

The IMSI conforms to the International Telecommunication Union (ITU) E.212 numbering standard.

Example

IMSI:404400021281732

MCC 404 India
MNC 40 Airtel
MSIN 0021281732


Code:

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class MobileProperties extends MIDlet implements CommandListener {
Form f = null;
Display dis = null;
Command ok = null;
Command exit = null;

public MobileProperties () {
dis=Display.getDisplay(this);
f = new Form(" Mobile Details ");
ok =new Command(" Ok",Command.OK,1);
exit =new Command(" Exit",Command.EXIT,2);
f.addCommand(ok);
f.addCommand(exit);
f.setCommandListener(this);
}

public void startApp(){
try {
f.append(" Nokia IMSI : " + System.getProperty("com.nokia.mid.imsi")+"\n");
f.append(" IMSI : " + System.getProperty("IMSI")+"\n");

} catch(Exception e) {
f.append("Exception :"+e);
}
dis.setCurrent(f);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable s) {
if (c == ok) {
destroyApp(true);
notifyDestroyed();
} else if (c==exit) {
destroyApp(true);
notifyDestroyed();
}
}
}

Getting the IMEI number from mobile devices of different manufacturers

International Mobile Equipment Identity (IMEI) is used to identify valid devices connected to GSM and UMTS network. This number can be accessed from a mobile phone by dialing *#06# on the keypad. IMEI is commonly use by software developers as part of software protection scheme to prevent it from being pirated.

JavaME developers however suffers from a drawback because MIDP/CLDC specification does not include an API to obtain IMEI from mobile devices. However there are few phone manufacturers included this functionality through System.getPropery() calls. Here's how to get IMEI number from mobile devices of different manufacturers

Manufacturer Argument
Nokia Mobiles System.getProperty("com.nokia.mid.imei”);
Sony-Ericsson Mobiles System.getProperty("com.sonyericsson.imei");
Motorola Mobile System.getProperty("IMEI");
Motorola Mobile System.getProperty("com.motorola.IMEI");
Samsung Mobiles System.getProperty("com.samsung.imei");
Siemens Mobiles System.getProperty("com.siemens.imei");


Code:

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class MobileProperties extends MIDlet implements CommandListener {
Form f = null;
Display dis = null;
Command ok = null;
Command exit = null;
String s1= null;

public MobileProperties () {
dis=Display.getDisplay(this);
f = new Form(" Mobile Details ");
ok =new Command(" Ok",Command.OK,1);
exit =new Command(" Exit",Command.EXIT,2);
f.addCommand(ok);
f.addCommand(exit);
f.setCommandListener(this);
}

public void startApp(){
try {
if ((s1 = System.getProperty("phone.imei")) == null || s1.equals("")) {
s1 = System.getProperty("com.nokia.mid.imei");
}
if (s1 == null || s1.equals("")) {
s1 = System.getProperty("com.sonyericsson.imei");
}
} catch(Exception e) {
f.append("Exception :"+e);
}
dis.setCurrent(f);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable s) {
if (c == ok) {
destroyApp(true);
notifyDestroyed();
} else if (c==exit) {
destroyApp(true);
notifyDestroyed();
}
}
}

Getting a random number from range


If you need to get a random number between X and Y, you should use some mathematical pattern using the Math Class and some calculus.

You can use this quick method to get the random number:

public int getRandomNumber(int min, int max) {
Random rnd;
rnd = new Random();
return min + Math.abs(rnd.nextInt()) % (max - min);
}


Another Method

Using the below code you can generate a 4 digit random integer.
int random4Digit = (int) (9 * Math.random())
+ (int) (9 * Math.random())
+ (int) (9 * Math.random())
+ (int) (9 * Math.random());

You can generate a 5 digit random int, by adding one more '(int) (9 * Math.random())'

Installing an application on the Phone's Game menu

By default in Nokia mobiles, when a user install a Java ME application, it is installed in the default folder on in "Applications" folder. If you want to suggest a Nokia device to install the JAR file in the Game menu of the mobile device, you have to insert this property in the JAD file of your game:
Nokia-MIDlet-Category: Game

Detecting if a Class/Package is available on the phone

You know Java ME has many optional packages that phones must have preinstalled over MIDP and CLDC. So, how can you compile one only code that detects on the fly if some class or API is available?

We can use the dynamic instantiation method, like this:

Code:
boolean MMAPIAvailable;
try {
// Try to instantiate a class using a string as the Class name
// so, the SDK without the API can compile the application
Class.forName("javax.microedition.media.Player").newInstance();
// If the next code is executed, then the API is available
MMAPIAvailable = true;
} catch ( ClassNotFoundException e) {
MMAPIAvailable = false;
}

Blocking the screen saver using J2Me

If your application doesn't demand constant key presses, after a while the screen saver on a J2ME phone will start automatically.

To make sure that the display light is turned on, the setLights method should be called before the screen saver is started and this must be done in a loop since the screen saver is not disabled just interrupted.

BacklightWorkaround.java
import com.nokia.mid.ui.DeviceControl;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class BacklightWorkaround extends MIDlet {

private SimpleCanvas canvas;

/**
* Keeps the backlight on by repeatedly setting
*/

class LightThread extends Thread {
public void run() {
while(true){

DeviceControl.setLights(0, 100);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

private class SimpleCanvas extends Canvas implements CommandListener{
private Command exitCmd;
private MIDlet midlet;

public SimpleCanvas(MIDlet midlet) {
this.midlet = midlet;
exitCmd = new Command("Exit",Command.EXIT, 1);
addCommand(exitCmd);
setCommandListener(this);
}
public void paint(Graphics g) {
g.drawString("Let there be light.", 0, 0, Graphics.LEFT|Graphics.TOP);
}

public void commandAction(Command command, Displayable displayable) {
if(command == exitCmd){
midlet.notifyDestroyed();
}
}
}

public void startApp() {
if(canvas == null){
canvas = new SimpleCanvas(this);
new LightThread().start();
}

Display.getDisplay(this).setCurrent(canvas);
}

public void pauseApp() { }

public void destroyApp(boolean unconditional) { }
}

Adding contacts using JSR 75

Following code snippets show how to add contacts using JSR 75.

PIMWrite class
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

public class PIMWrite extends MIDlet implements CommandListener
{
private Command PIMWriteCmd,exitCommand,generateName;
PIMImpl pimImpl;
private static Random random = new Random();
static String[] names;

public static Display display;
public static Form result;
private String sp,si,s1;
private String[] strJSR = new String[12];
private long l;
int noOfContacts;

TextField textfield = new TextField("Enter No of Contacts: ","",3,TextField.NUMERIC);


/*Constructs an Object
*/

public PIMWrite() {

display = Display.getDisplay(this);

PIMWriteCmd = new Command("PIMWrite", Command.SCREEN, 0);


exitCommand = new Command("Exit", Command.SCREEN, 0);

result=new Form("Write Contacts To PIM");
result.append(textfield);
System.out.println(" noOfContacts: "+noOfContacts);

result.addCommand(PIMWriteCmd);
result.addCommand(exitCommand);
result.setCommandListener(this);

}

public void startApp() throws MIDletStateChangeException {
display.setCurrent(result);

}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable s)
{
if (c == exitCommand)
{
destroyApp(false);
notifyDestroyed();
}

else if(c == PIMWriteCmd)
{
noOfContacts = Integer.parseInt(textfield.getString());
createConatactName();
System.out.println(" noOfContacts: "+noOfContacts);
//Start the PIM thread and write contacts .
pimImpl = new PIMImpl();
pimImpl.start();


}
}

public void createConatactName()
{
names = new String[noOfContacts];
for (int i = 0; i < style="color: rgb(102, 204, 102);">){
names[i] = PIMWrite.generateName()+" "+PIMWrite.generateName();
System.out.println(" Names :"+ names[i]+ " i "+i);
}
}


public static String generateName()
{
return generateName(4, 7, true);
}


/** This method generates the random names
*
* @param minLength Minimum length of name
* @param maxLength Max length of name
* @param capitalize Captilize
* @return name
*/

public static String generateName(int minLength, int maxLength, boolean capitalize)
{

int limit = (random.nextInt(maxLength - minLength + 1)) + minLength;
StringBuffer s = new StringBuffer(limit);
for (int i = 0; i < style="color: rgb(102, 204, 102);">)
{
char c = (char)((random.nextInt(26)) + 'a');
s.append(c);
}
if (capitalize && (s.length() > 0)) s.setCharAt(0, Character.toUpperCase(s.charAt(0)));
return s.toString();
}
}
PIM Implementation class

/**
* PIM Implementation class
*/

import javax.microedition.pim.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Command;

public class PIMImpl extends Thread
{
static Alert check;

StringItem si;
//----------------------------------------Phone Book---------------------------------

int noOfRecords;
public static boolean pimTemp = false;
Random randPh = new Random();


public PIMImpl()
{

}

public void run()
{
writeData();
}



public synchronized void writeData()
{

String ph[] = new String[PIMWrite.names.length];
for (int i=0;inames.length ;i++ )
{

String r = Long.toString(randPh.nextLong());
if(r.startsWith("-"))
{
r = r.replace('-','9');
}
ph[i] =(r.length()>10)?(r.substring(0,10)):(r);



// System.out.println(" PH :"+ph[i] +"i:"+i);
}


int tc = 0;
PIM pim;
try{

ContactList contacts = null;
ContactList conT = null;
pim = PIM.getInstance();
try {

contacts = (ContactList) pim.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// An error occurred
return;
}
for(int i=0;inames.length;i++)
{

Contact contact = contacts.createContact();
String[] name = new String[contacts.stringArraySize(Contact.NAME)];

// System.out.println("i = "+i);
if (contacts.isSupportedField(Contact.TEL))
{
contact.addString(Contact.TEL, Contact.ATTR_MOBILE, ph[i]);
}

if (contacts.isSupportedArrayElement(Contact.NAME, Contact.NAME_GIVEN))
name[Contact.NAME_GIVEN] = PIMWrite.names[i];
contact.addStringArray(Contact.NAME, PIMItem.ATTR_NONE, name);


try {
contact.commit();
} catch (PIMException e) {
// An error occured
}
PIMWrite.result.deleteAll();
String msg=" Contacts Adding :"+i;
si = new StringItem("",msg);
PIMWrite.result.append(si);

}
check = new Alert("Added","Added ",null,AlertType.CONFIRMATION);
check.setTimeout(Alert.FOREVER);
PIMWrite.display.setCurrent(check);

try {
contacts.close();
} catch (PIMException e) {
}

}catch(Exception e){
String er = e+" ; tc="+tc;
check = new Alert( "Response",er,null,AlertType.CONFIRMATION );
check.setTimeout(Alert.FOREVER);

PIMWrite.display.setCurrent(check);
}
// return true;

}

}