Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 73
Текст из файла (страница 73)
This snippet of C++ code is intended to reverse thecontents of an array, ar:#include <stdlib.h>void reverseArray(int ar[]) {if(ar = NULL) return;unsigned int len = sizeof(ar);for(unsigned int index = len-1; index >= 0; index--) {int temp = ar[index];ar[index] = ar[len-index-1];ar[len-index-1] = temp;}}The example is based on a genuine piece of code. It actually containsfour mistakes: three are coding errors and the fourth is an algorithmicerror.
These are mistakes which will not generate compiler errors but willcause runtime errors. Let us go through them:• if(ar = NULL) return; is intended to check that ar is a validarray; however because the assignment (=) operator has been usedrather than the equality (==) operator, ar will be set to null; thecondition evaluates to false, so the program will carry on with arequal to null• sizeof(ar) is intended to return the number of elements in thearray; in fact, it returns the size of an object in bytes so, at best, itwill return the size of the array in bytes, not the number of elements;however, even though ar[] looks like an array, it is actually a pointer408THE MARKET, THE OPPORTUNITIES AND SYMBIAN’S PLANSand sizeof(ar) will return the size of the pointer, which is typically4 for a 32-bit machine• an unsigned integer, index, was used for the loop counter; thismeans index will never go negative and therefore the loop willnot terminate• the number of times the code was intended to go through the loop isequal to the number of elements in the array; think about an array offive elements: I want to swap the first with the last, the second withthe second to last and the third, or middle element, can stay where itis; in other words, I want to make two swaps, not five!This is the equivalent Java code:void reverseArray(int[] ar) {if(ar == null) return;int len = ar.length;for(int index = len-1; index >= 0; index--) {int temp = ar[index];ar[index] = ar[len-index-1];ar[len-index-1] = temp;}}The Java compiler expects the argument of an if statement to be aboolean, therefore we have to use the equality operator.
Java arrays arefirst-class objects and so ar.length will return the number of elementsin the array. Primitive types in Java (bytes, ints, longs) are always signedso my loop counter will go negative.We’ve removed three out of four faults by using Java, allowing us toconcentrate on the algorithmic error. Arguably a four-fold improvementin productivity!Less Code to Write (and Less Code to Deliver)Java applications also require fewer lines of source code. The followingEPOC C++ code sends the message ”Hello Imperial” to the server193.63.255.1 (which belongs to Imperial College in London) on port 7,which is the echo port.
The code then reads the echoed reply:RSocketServ ss;err=ss.Connect();RSocket sock;err=sock.Open(ss, KAfInet, KSockStream, KUndefinedProtocol);const TInt KEchoPort = 7;TInetAddr imperial(INET_ADDR(193,63,255,1), KEchoPort);TRequestStatus stat;sock.Connect(imperial, stat);User::WaitForRequest(stat);SYMBIAN AND JAVA409TBuf8<14> text = _L("Hello Imperial");sock.Write(text, stat);User::WaitForRequest(stat);sock.Read(text, stat);User::WaitForRequest(stat);sock.Close();Although this is Symbian OS C++ code, WIN32 code is very similar.Here’s the equivalent Java code:SocketConnection socket= (SocketConnection)Connector.open("socket://193.63.255.1:7");DataOutputStream out = socket.openDataOutputStream();DataInputStream in = socket.openDataInputStream();out.writeUTF("Hello Imperial");out.flush();String echoedText = in.readUTF();socket.close();Not only is the code shorter (seven lines rather than 14), but it’s a lotclearer as well.This is not quite the end of the story.
Java bytecode itself is compact sothat, in general, a line of Java source will generate less code than a lineof C++. This is because add, new, etc. are expressed as single bytecodeswhereas the C equivalent will expand into word instructions or multipleassembler instructions. On the other hand, we need to be aware of thehigher overhead associated with each Java class and that JAR files, if notobfuscated, can be very wordy.However, in general the consequence of compact bytecode and fewerlines of source is that Java downloads are smaller than C++ equivalents.This is important for over-the-air (OTA) delivery.8.5.4 Ease of PortingJava is not a guarantee of success when it comes to device-independenceand coping with the huge range of mobile phones; however, it is theleast painful solution. APIs are compact and standard user interfaceclasses reduce the worst of the variability.
Expert groups such as the JavaTechnology for the Wireless Industry (JSR 185) initiative are helping toimprove portability and reduce fragmentation across mobile phones.8.6 Symbian and JavaSymbian uses Java to expose the advantages and strengths of SymbianOS through APIs, that, by and large, are standard. Many of the newerwireless Java APIs, such as multimedia, Bluetooth and PIM, are interfacesonto native functionality, which means that a Java implementation is only410THE MARKET, THE OPPORTUNITIES AND SYMBIAN’S PLANSas good as the underlying platform. Rather than just delivering a vanillaMIDP implementation, Symbian is providing a Java environment that willenable operators and services providers to create revenue through rich,exciting, value-added services.8.6.1 Current ImplementationSymbian’s approach is not only to provide a best of breed environment forstandard games and MIDlets (and even here the extra color depth, largescreens and good performance will add value as shown in Figures 8.9and 8.10), but also to enable the large and complex applications andservices we discussed earlier.Symbian’s Java implementation ensures that MIDlets are treated inthe same manner as native applications (they are ‘‘first class citizens’’)of the platform and, as far as possible, have the appearance of and aremanaged in the same way as native applications.
Here are a few featuresof Symbian’s implementation:• MIDlets are installed, run and removed like native applications• MIDlets use native UI components, which are faster and smaller andhelp to maintain a native look and feel(a)(b)(c)Figure 8.9 Goldminer by Macrospace on a. Siemens SL45i, b. Trium Eclipse and c.
Nokia7650.Figure 8.10 FunnyBalls by Cybiko, designed for the 9200; good use is made of the screenand the array of control buttons make game play much easier.SYMBIAN AND JAVA411• there are no limits on heap size• there are no limits on characters in a text field or text box, etc.• there are no limits on the RMS• the heap can grow and shrink• there is support for the native color depth• there is one VM instantiation per MIDlet suite.Although Symbian’s main focus is on CLDC, the Java VM must nonethelessprovide uncompromising performance and advanced memory management to deliver the richer services and games we’re interested in. Here’sa summary of Symbian’s VM progress:• Symbian’s first CLDC 1.0 implementation was based on Sun’s originalKVM, but with the addition of ARM’s VTK software acceleration and aheap that can grow; a stack that can grow allows very deep recursion• Sun’s CLDC HI 1.0 uses a dynamic adaptive compiler (DAC) forimproved performanceNo debug version is available, so the emulator uses the original KVMconfigured for debugging.
The heap can both grow and shrink, withthe heap shrunk on the basis of the percentage used after majorgarbage collection. This means, on the one hand, that applicationsshould not run out of memory (within the limits of the available systemmemory) but, on the other, that memory no longer needed by a MIDletcan be recovered by the system for use by other applications.• CLDC HI 1.1: improves the static and ROMization footprint, whichreduces the size of all preinstalled JSRsChanging from native to lightweight threads also reduces the footprint.There are small performance gains, around 10 % measured againstEEMBC benchmarks. The heap and stacks have associated growand shrink heuristics, with shrink heuristics applied during garbagecollection.
In addition, ARM is developing the Jazelle technology foruse with CLDC HI 1.1, which is a promising combination.It is worth noting that there is a close correlation between SymbianOS functionality and the wireless JSRs, to the extent that is there islittle significant Symbian technology that cannot be exposed via theappropriate JSR.8.6.2 Future PlansHaving looked in depth at the market and opportunities, it’s now timeto consider Symbian’s plans and how they meet market needs. The412THE MARKET, THE OPPORTUNITIES AND SYMBIAN’S PLANSSecurityv7.0s(now)ProvisioningGames supportEnhanced UIMessaging (JSR 120)Bluetooth (JSR 82)MIDP 2.0(JSR 118)CLDC HI 1.0Figure 8.11 Java technology in Symbian OS Version 7.0s.markets of interest are, broadly, games, location services, web andadvanced consumer services, enterprise mobility and mobile commerce.This discussion should be seen as a rough guide only!Symbian OS Version 7.0s (see Figure 8.11) is used, for instance, on theNokia 6600 and provides the basic requirements for connected gamesand utilities.
There are many thousands of simple games and utilitiesrunning on MIDP 1.0; however, the number of Java APIs in SymbianOS Version 7.0s is an order of magnitude greater than in MIDP 1.0. Itwill be interesting to see how the number of MIDlets will increase as aconsequence.8.6.2.1 BluetoothJava APIs for Bluetooth (JSR 82) enables MIDlets to communicate overBluetooth. However mobile phones can also use these APIs to host andshare services, such as games, printer controllers and rendering services.A Java MIDlet registers itself as a Bluetooth service using the ServiceDiscovery Protocol (SDP).