Programming on Java in C-style






3.26/5 (17 votes)
Software to write programs on Java-language for Cell Phone in the same style you do it on C-language for MPU
Programming on Java in C-style.
Download source code and samples - 77 kB

1. The main idea of the article.
The target of the article is to show, how to program on Java-language in classical C-language style. Typical sample of practical importance of this approach is Cell Phone with J2ME, where you have to use Java. This approach possesses for example microprocessor (MPU) programmers who mostly use classical (or procedure oriented) single thread C-language program these devices without learning Java-language.
The realization of this target is based on 2 things:
This style was called Java-Rapid Programming Interface, because it posses C-programmer with minimal additional knowledge of Java create rapidly applications for Cell Phones on Java. More about Rapid Interface which is available for many platforms: Win32, Linux, WinCE, DOS and ReactOS you can find here. The library suggested in this article is oriented first of all on programming Cell Phone as display for microcontrollers, but you can add additional commands to extend area of Java-Rapid. All source-codes are available.
It is important to note that nevertheless your program will be on Java-language (and you can add in it any Java constructions if you want), but practically the grammar of your program will be very close to classical C-language.
2. Practical usage of Java-Rapid program interface
Practically Java-Rapid Programming Interface consists of 2 java source-ode files: rapid.java and rapcanvas.java. You must copy them to source-code directory of your project. Rapcanvas.java has subroutine: private void run() - this is zone of C-language: inside it and near-by you can write your algorithm in C-like language. You can use subroutines in C-style in the same file only. The following sections: 2.1...2.4 are for programmers who has no experience in Java programming and where it is explained in details how practically compile jar-files using Java-Rapid. Experienced programmers can omit them. First of all you must install standard software for developing J2ME Midlets. There are several packages of free distributed software for this purpose. Here we will consider 2 most typical of them.
2.1 KToolBar.
KToolBar is standard and free software of Sun Microsystems for creating Midlets. It has no own text editor and thus it has no possibility of automatic move to place of the error in source-code file.
1. Create project by selecting menu option: New Project. The name of the project can be as you like (it will be the name of jar-file), but Midlet class name must be exact: Rapid (beginning with capital letter). In API Selection (you can enter it during creating new project or later if you choose option Settings). Select Custom and select Profiles and set configurations corresponding to your Cell Phone, for example it can be: MIDP 2.0, CLDC 1.1 Among Optional select the following:
If you make wrong selection in this section you can compile your application without errors but when you start it on Cell Phone you can get error message like: Wrong Application. All applications discussed here were tested on typical non-top performance Cell Phone SonyEricsson K550 with MIDP 2.0, CLDC 1.1, 176*220 pix screen.
2. Find the folder with created project. It is always in Apps-subfolder of KToolBar folder (no other locations are possible in KToolBar). But this folder for Sun KToolBar is hidden in Documents and Settings\User\ j2mewtk, for SonyEricsson KToolBar it is inside basic folder of application. Copy to src- subfolder of your project (it must be empty after creation of project) 2 basic files of Java-Rapid: rapid.java and rapcanvas.java.
3. Using Text editor (for example EditPlus) in rapcanvas.java find subroutine public void run() (it must be empty) and add there your application in Java-Rapid (for example any of sample applications from download). Save file. All is ready to build application.
4. Build application using Build option of KToolBar (KToolBar has useful option Clear console, use it to delete previous information). If you meet errors correct them. KTollBar gives line number where error was detected and type of error. You can easily find this line using Text Editor. Practically during work with the project 2 programs must be opened at the same time: EditPlus and KToolBar. After editing error do not forget to save file, and only after this use again Build option of KToolBar. After fixing all errors create jar-file using menu option: Project/Package/Create Package.
5. You can use simulation to test your application using option Run, but this works correctly only in case of simple programs. Then upload jar-file to Cell Phone (see section 2.3) and continue tests on real platform. Jar-file will be in bin-subfolder.
2.2 NetBeans.
NetBeans is very slow, but it has on-line grammar check which is very convenient for beginners.
1. Create new empty project (take away check on Create Hello MIDlet) using menu option: File/New project/Mobility/MIDP Application. Select name of midlet and directory (NetBeans allows this). Select configuration which must correspond to your phone, for example CLDC-1.1, MIDP-2.0. This is very important, otherwise your Midlet will not work on phone (emulator will work) without any commentaries.
2. NetBeans will create directory of project. Subdirectory src will be empty. Copy there 2 files: rapid.java and rapcanvas.java. Turn off/Turn on your project to refresh source files of your project. You must see new files among src -files of project.
3. Select menu option Project Properties/Application descriptor/MIDlets/Add .Do not change anything (if you change you will get Install failed on the last stage of your work)! It must be:
Select OK and quit this option.
4. In file RapCanvas.java find subroutine Run(). This is the place where you must write your application on Rapid. You can add subroutines after it if you need. It is not recommended to make any changes in other places of RapCanvas.java file. It is recommended for the first time copy there samples from download and compile them.
5. Press Build button and compile your application. It may be found errors. Correct your text. Then press Run to run your application in Emulation.
6 And at last upload jar-file to your phone. It is in bin-subdirectory of your project. .
2.3 Uploading jar-file to Cell Phone via BlueTooth
If you have BT- on your phone (and you need it if you want to communicate with microcontrollers) you can use this link without any additional hardware and cables.
1. Using software BlueSoleil. Run on PC BlueSoleil. Turn on BT on your phone. Your phone must be detected (double click orange Earth to detect devices as satellites on the orbit around Earth). Make connection with PC. In BlueSoleil click right mouse key your phone and select Refresh services, then select Make connection/File Transfer. Send your jar-file using standard Drag and Drop action (do not forget to confirm contact on your phone).
2. Using Standard MS Windows BT-software. Open program (connection with your Cell Phone must be set previously). Select option Send file, in the first window select your Cell Phone, in the next window select file to send. Your jar-file will be uploaded to any available folder (Games and Applications folders are not available during upload). If file with this name exists Cell Phone will ask you to overwrite it (but practically often it does not overwrite file but adds new one with addition ..._2, ..._3 and so on at the end like in UNIX OS). File system of Cell Phone is not as good as Windows and thus often to see new file you must reenter folder. Run jar-file. This time it will install you application to "forbidden" application folder. Select Games or Application folder and install your application. This is not transparent operation, as Cell Phone software can refuse installation without any commentaries (just output Operation Failed). Most often the reason is that when you created project your settings did not correspond to Cell Phone ones. During installation Cell Phone will ask you important question like Keep existing data? The meaning of this question is: J2ME allocates some service memory for application settings. Among them is what you save using Rapid Save command. If you select Yes all settings will remain. Only after that you will be asked to start your application. During Debugging application on Cell Phone the most important key of phone is Menu events key (it is marked as 2 rectangles). It works like Ctr/Alt/Del of Windows and provides forced close of hanged up application. If you have not this key debugging application will be doubtful.
2.4 Turn on EditPlus text editor for Java-Rapid.
If you are using KToolBar software it is recommended to use EditPlus editor. Special files for Java-Rapid are available for this Editor in the download. Download distributive of EditPlus from www.editplus.com and install it. Replace java.asp and java.stx files on special ones done for Java-Rapid. It is recommended to copy to that directory java-rapid.hlp file. Run EditPlus. In menu option: Tools/Configure User Tools/Add Tool/Help file. Input Menu text: Help, Command: find using file browser Java-Rapid help -file (java-rapid.hlp). Now all Java-Rapid commands in source-file will be green. Move cursor to green word and press Ctrl/1, you will get context help for this command. To obtain Auto-completion input name of Java-Rapid command and space. To find couple bracket use Search/Select Brace.
3. Download, samples.
Download source code and samples
- 77 kB
The download below includes the following files.
HellowWorld.rap - the simplest program. It is so simple that its
code can be shown here
public void run()
{ printf( "Hello World");
  Wait(-1);
  exit();
}
4. Structure of JAVA-RAPID application.
General structure of a program is based on the following approach. All external events (like key press, select option of menu and so on) change global variable EventID to some preset numerical values. Zero means no events. In a program you must organize one or several work cycles where you analyze EventID (and do all other necessary for your application tasks). Text of main subroutine on Java-Rapid can look like as follows:
public void run()
{ int x,y,cod.........
  String buf=new String();
  .........
  Menu(.........
  QuitEvent(999); // preset Quit event
  KeyEvent(998,0); // preset key press events
//------- work cycle ---------------
  while(EventID !=999)
  { switch(EventID)
    {
    Case 998: EventID=0; cod=Inkey();.........break;
    ..........................................
    }
//-- independent of system events part --------
    ..............................
    Wait(1); // very important for single-thread
   }
   exit();
}
public String Sub(int x, byte[] y, String Z)
{ String str=new String();
  ......................
  return str;
}
Subroutines in J2ME look like in C, but there are some differences:
5. Java variables
Available types of variables differ from C-language. And in C-zone you must use Java variables. They are as follows:
Variable declarations looks like:
short n;
byte[] data=new byte[128];
String text=new String();
String[] SA=new String(32);
EventID - special system variable of Java-Rapid. EventID has fixed name (which you can't change) and is global. User has to declare at the beginning of program EventID values for some system events (for example press key, or select menu item). EventID is zero if there is no events. In work cycle you must control value of EventID.
6. Java-Rapid commands.
6.1 Conversion of types.
6.2 Mathematical functions
6.3 System commands
List of properties:
"rap_version"
"DxFont"
"DyFont"
"DxScreen"
"DyScreen"
"isDoubleBuffer"
"MemTotal"
"MemFree"
Also are supported all properties of Java command System.getProperty(prop); Which can differ for different phones. Samples of argument prop:
"microedition.configuration",
"microedition.profiles",
"bluetooth.api.version",
"microedition.media.version",
"supportTrueColor",
"microedition.commports"
where
tau - delay in msec
Wait(-1) - wait until press of any key
This command in Java-Rapid is very important, as it stops current thread and gives possibility to other threads do there work. It is recommended to include it in work cycles with minimum delay: Wait(1);
In Java-Rapid command differs from C, for example:
printf("text1"+var1+"text2"+var2);
where
var1,var2 -names of variables of any types (there format to print is set automatically).
text1,text2- fixed text(string literals). They can include \n which means carriage return
This command has possibility of infinite scroll of screen in so-called DOS or console style and this is very convenient.
If in addition some graphical primitives are outputted on screen:
1) they will not scroll together with text;
2) text will be always outputted over graphics
If first argument in list of variables of command printf is numeric you must input before it empty string literal:
int x;
........
printf(""+x);
where
x, y - coordinates in pixels. 0,0 point corresponds to the left upper corner of the first character of the output text.
Command has limitation on number of inputs on current screen (without taking into account scrolled out lines) - 100 entries. The syntax of the command corresponds to C-language.
where
name -consists of several words in any order (register is important)
"Syst[em]" - system,
"Mono[space]" - monospace
"Cou[rier]" - monospace
"Prop[ortional]" - proportional
"Ari[al]" - proportional
"B[old]" - bold
"I[talic]" - italic
"U[nderline]" -underlined
size: 1- small, 2-medium, 3-large
Real sizes of symbols depend on phone model. Some fonts can be not available on your phone
Sample: Font(2,"Prop BI");
Font will acts on all screen.
Return from command - key Enter. DelBack - key is available. You can use this command several times, for example:
printf("\nYear ==>"); gets(buf1);
printf("\nMonth ==>"); gets(buf2);
printf("\nDay ==>"); gets(buf3);
where
XY[0]=x ,XY[1]=y - coordinates.
where
nota- standard nota-number in MIDI-notation 1,..... 127
duration - duration in milliseconds
level- volume 0....100
void QuitEvent(int iEvent) - quit event will take place if you try to close application
void KeyEvent(int KeyDownEvent,int KeyUpEvent)- events of press and release keys.
You must also set Events ID's in Menu-command
6.4 Date and Time
where
TT[0]=hours,
TT[1]=minutes,
TT[2]=seconds
where
DD[0] -year
DD[1] - month (1,2...12)
DD[2] - day (1,2....31)
This command in this realization is valid only for Eastern hemisphere.
In some phones (SonyEricsson for example) there is no internal mechanism to set automatically DST, and you must enter System menu and change it manually.
where
DD[3]={yy,mm,dd}
TT[3]={dd,mm,ss}
Julian day from 1-01-2000 12:00:00 GMT. Used in astronomy. Julian day is the same for all points of the Earth.
where
DD[0] - year ( >=1906.)
DD[1] - month (1.....12)
DD[2] - day (1.....31)
return - (Sunday=0, Monday=1,....)
If date is wrong (for example 32-May-2000) week < 0
where
DD[0] - year ( >=1906.)
DD[1] - month (1.....12)
DD[2] - day (1.....31)
return - day of year
This command is convenient for dates compare. For example you need to select events from February 15 until March 15:
Day of year in Java-Rapid is connected with date and March 1 will have the same number for leap and not leap years.
6.5 Standard C string operations
-1 not identical
where
SA - string array
After command the strings in string array will be replaced.
where
Str - source string
i - initial position to find word>
As i is not returned here use the following algorithm to get all words:
while(text1 !=null)
{ text1=GetWord(text,i);
  if(text1!=null)
  { printf("\n"+text1);i=i+Strlen(text1)+1;
  }
  else printf("\n=== Finish ===");
}
6.6 Standard file operations
int open(String name,"W");
At same time can be opened only 2 files: one- for read and one for write.
Returns handle to opened file
where
h - handler of opened file from command open
buf - name of buffer from where to write (data to write can be only array of bytes)
n - number of bytes to write
int read(int h,byte[] buf,int n)- read n -bytes
where
h - handler of opened file from command open
buf - name of buffer to read to
n - max number of bytes to read
return - number of readed bytes.
return=-1 - end of file
or read error
Data can be read only to byte array, n-number of requested bytes, return- real number of read bytes.
where
path0- start directory for search, for example, "e:/Other/". If you want search from top use "/". Here not full names of J2ME used, which have title: file:///localhost, but only parts -analogs to Windows OS. This is true for open command also. It must be mentioned that not all directories in J2ME are available. Different models of Cell Phones have different file systems. For example in SonyEricsson devices have letters:
c:/ - main memory
e:/ removable Flash-memory
Return null- means refuse to select file.
6.7. Save/Restore
Command uses RecordStore mechanism of J2ME. You can save and Restore any number of Java-Strings for each application. They have no names, but only record numbers: 0,1,...... You can add and update them. Even if you update application by installing new one over previous, records can not be deleted if you refuse the option like "Delete application data"Saves str in record number- j of RecordStore
If RecordStore was not created before it will be created.
If j< jmax, j-record will be updated , otherwize a new record will be added to the end of RecordStore, its number will be returned.
If j=-1 - RecordStore will be deleted. The other way to delete RecordStore - select Delete application data, when you update application using new installation.
Get record j. If j>=jmax you will get- null
6.8 BlueTooth operations
BlueTooth operations based on the same group of commands as file operations: open, close, read, write. You will use SPP (serial Port Protocol) profile.where attrib-string with attributes. For Server it can be, for example: attrib="authenticate=false;encrypt=false;name=RFCOMM Server"
h=ComOpen(ComName,attrib) -opens COM-port as Client with known host name You must input server name consisting of 6 hex digits (that is 12 symbols: 0,1...9,A,...F)
For Client in case of USB BT-dongle under Windows XP: attrib="2;master=false;encrypt=true;authenticate=true"
The same for BT-modem (connection with microprocessor via RS-232 or UART):
attrib=":1;master=true;encrypt=true;authenticate=true"
First sigh in attributes is port number or channel number on remote device. This is the most important item of attribute string (you need not write the rest as defaults values will be taken). Its value depends on particular device you want to connect and its software. Java-Rapid has no means to determine this value, and trial method is recommended. Search is not large: possible values are 1, 2, 3. For simple BlueTooth- modems it is 1, as they support only one (SPP) protocol. For BT on PC with BlueSoleil it can be 2 for COM port A or 3 for COM-port B (both values are valid ). For more details see documentation from download.
In Java-Rapid you can have only one connection.
where
data- byte array buffer to receive data (its size must be large enought) n- number of bytes to read (0-means read all available bytes).
return- real number of received bytes.
6.9 Graphical commands
where
iC - color index of screen after clearing
where
iColor1-color index of characters
iColor2-background color index.
You can use 16 indexed colors for text, text background, pens (lines) and brushes (fill). Default values for colors are given below, but you can change them.
0 black, 1 dark blue, 2 dark green, 3 dark cyan, 4 dark red, 5 dark violet, 6 light gray (not brown),7 gray, 8 dark gray, 9 light blue, 10 light green, 11 light cyan, 12 light red (magenta), 13 light violet, 14 yellow, 15 white
When you use graphical commands: line, rectangle, ellipse, curve - the above colors will be used for pens and brushes.
where
iColor - color index (0…15)
R,G,B - color components (0..... 255)
where
Nx,Ny - number of divisions along X and Y axis
Command will draw only baseline grid without text
where
X,Y - arrays with X and Y pixel coordinates
n - number of points
iC - color index.
where
ix1,iy1,ix2,iy2 - coordinates of line points in pixels
iC - color index
where
ix,iy,idX,idY -coordinates of left upper corner and sizes of rectangle in pixels
iPen - color index for border
iBrush - color index for brush.
where
x1,y1- start point of arc
x2,y2 - end point of arc
d- deflection of the arc (double):
r=(d*d+L*L/4)/(2*d)
L- chord length
iC - color index
where
U- array of values to trend (int[5])
Moves trend to next step. Trend here occupies screen completely and has only pixel scale. You must use 5 channels always. It can be signals and fixed levels. When you use Trend you must not use any other graphical primitives (like Line)
6.10 Standard Controls
if Title is long it will be outputted in Ticker mode
Q -String array with questions
A -String array with default answers
n-number of questions (n<=5)
Return- String array with answers. Advice: press phone keys for long time for better work of command.
Q -String with title
A -String with default answer
n-max size of text buffer
Return -String with the answer
mode=mode1+mode2;
mode1: 0- MessageBox is shown for 5 seconds and closes automatically
      10- MessageBox has one knob OK
      20- MessageBox has 2 knobs: OK,Cancel
mode2=1 - information
      2 - confirmation
      3 - warning
      4 - alarm
      5 - error
The difference in mode-2 is in musical support.
Return 1- YES/OK button was pressed
-1 - Cancel button was pressed
i - current value of progress parameter
imax - maximal value of progress parameter.
To open ProgressBar you must use Progress(title,0,imax);
To close ProgressBar you must use Progress(title,imax,imax);
ProgressBar (Gauge) is outputted in all-screen separate window. It has 2 strings of text and Progress Bar
Top string : general title (title when i=0
Low string: current event information from title-argument at i>0
Texts - String array with texts of items.
Ids - int array with EventIDs for items
n - number of items
Menu is created automatically, each model of Cell Phone can do it in different way. For example SonyEricsson first item situate under left soft key and all the others under right soft key with total title Other
Sample:
String Text[]={"Exit","Open","Save"};
int IDs[]={ 999, 200, 201};
Menu(Texts,IDs,3);
Command occupies all screen and return index of selected substring of String array
title- title of Combo window
SA - String array name
n - number of strings in SA to output
Command returns number of selected string.
Command occupies all screen and return index of selected substring of String array
title- title of Combo window
SA - String array name
n - number of strings in SA to output
Command returns recordset of selected items:
0-element: number of selected items, then selected indexes.