Date post: | 12-Jan-2015 |
Category: |
Technology |
Upload: | winstorevn |
View: | 453 times |
Download: | 0 times |
PORTING TO NOKIA ASHA
Cao PhongDeveloper Tech Support ManagerAug 07, 2013
CONTENTSUX Overview from a porting perspectiveDeveloper Offering
Java ME appsNew, updated and removed APIsLCDUI, LWUIT changes
SDK ManagerPorting from AndroidGame development introduction
UX EVOLUTION
3” QVGA screen
© 2013 Nokia DevelopingForTheNewAshaPlatform.pptx v. 0.2 2013-04-20 Attila Csipa
3” QVGA SCREEN
© 2013 Nokia DevelopingForTheNewAshaPlatform.pptx v. 0.2 2013-04-20 Attila Csipa
HARDWARE KEYS BACK BUTTON
NOKIA ASHAAPI OVERVIEW
© 2013 Nokia DevelopingForTheNewAshaPlatform.pptx v. 0.2 2013-04-20 Attila Csipa
CHANGED / REMOVED APISAPI CHANGE
JSR-75 (PIM) No support for To-Do list
JSR-177 (Security and Trust Services) No support for SATSA-APDU
JSR-234 (Adv Multimedia supplements) Added: imageencoding/postprocessing, tunerRemoved: audio3d, music
Nokia UI API – Category Bar Max of 4 icons
Nokia UI API – Gesture API Added double-tap gesture
Nokia UI API – Popup List API No list dialog
Nokia UI API – Sound API No com.nokia.mid.sound (use javax.microedition.media instead)
© 2013 Nokia DevelopingForTheNewAshaPlatform.pptx v. 0.2 2013-04-20 Attila Csipa
NEW ASHA JAVA APIS
© 2013 Nokia DevelopingForTheNewAshaPlatform.pptx v. 0.2 2013-04-20 Attila Csipa
COMPATIBILITY?Source & binary compatible
– xx years old Java ME apps run on Nokia Asha 1.0 phones!
Downwards compatibility– Check API support of target phones– Lowest common denominator:
→ Nokia Asha SDK compiled app runs on old phones
PORTINGAll Java ME apps should run on full touch phone
– High-Level UI– Adapts automatically– Components include touch-support– Check layout– New UI components (CategoryBar, etc.) don’t have to be used
– Low-Level UI– New screen size & aspect ratio (but: most Java apps already flexible here)– Touch supported in Java ME since many years
New APIs for Internationalization, Multitouch, Pinch, CategoryBar & Sensors– Only work on new phones– Careful app design even keeps downwards compatibility
PORTING
Non
-touc
hTo
uch
and
type
Full
touc
h
Non-touch app with high-level UI (LCDUI):automatically adapts
Asha
DYNAMIC API USAGE
Single code base for different phones– Code that uses new APIs
– Externalize to extra class– Check API support at runtime
– Instantiate class if supported– Different methods for checking available
EXAMPLE: DOUBLETAP GESTUREGesture API
– Introduced in Touch & Type– Full Touch added Pinch gesture– New Nokia Asha added Doubletap gesture– Query support at runtime
// Doubletap gestureif (GestureInteractiveZone.isSupported(GestureInteractiveZone.GESTURE_DOUBLE_TAP)) {
// Gesture is supported - register class as listenerGestureRegistrationManager.setListener(this, this);// Register for doubletap gesturegestureZone = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_DOUBLE_TAP);GestureRegistrationManager.register(this, gestureZone);
}
EXAMPLE: OPTIONAL MULTITOUCHEncapsulate API using code to separate class
Check support and instantiate on demand
public class MultitouchManager implements MultipointTouchListener {
public MultitouchManager(MainCanvas canvas) {MultipointTouch mpt = MultipointTouch.getInstance();mpt.addMultipointTouchListener(this);
}
public void pointersChanged(int[] pointerIds) { /* ... */ }}
if (System.getProperty("com.nokia.mid.ui.multipointtouch.version") != null) {// API is supported: Can implement multipoint touch functionalitymultiManager = new MultitouchManager(this);useMultitouch = true;
}
protected void pointerPressed(int x, int y) {if (!useMultitouch) {
// Handle touch event // on single-touch phone
}}
In MainCanvas class (extends Canvas)
Hint: only handle Canvas.pointerPressed() on single touch phones
EXAMPLE: API AVAILABILITYNo System property for the API version?
– Check Class availability– ClassNotFoundException? → API not supported
// Virtual keyboard supporttry {
// Check if class is availableClass.forName("com.nokia.mid.ui.VirtualKeyboard");vkbManager = new VkbManager(this);useVkb = true;
} catch (ClassNotFoundException e) {// Class not available: running app on Java Runtime < 2.0.0 phone.// -> no Virtual Keyboard API support.useVkb = false;
} catch (Exception e) { }
NEED FOR THREADS IN COMMAND ACTION
Protected methods– From commandAction()
– = event dispatch thread– Asha Platform:
Throws SecurityException“Blocking call performed in the event thread”
→ Call from extra thread!
public class ProtectedCallAsha extends MIDlet implements CommandListener, Runnable {private Display display;private Form mainScreen;private Command execute;private Command exitCmd;Thread thread;protected void startApp() throws MIDletStateChangeException {
… //The initialization screen with the Commands}public void commandAction(Command cmd, Displayable display) {
// Direct call to the protected method from commandAction is not allowed on Asha software platform 1.0if (cmd == execute) {
thread = new Thread(this);thread.start();
}if (cmd == exitCmd) { notifyDestroyed(); }
}public void run() {
//The protected method call is executed within a Threadtry {
// for example: QualifiedCoordinates coordinates = location.getQualifiedCoordinates();}catch (Exception exception) {
mainScreen.append("Exception: " + exception.getMessage() + "\n");}
}}
CANVAS CHANGES
3” QVGA SCREEN
© 2013 Nokia DevelopingForTheNewAshaPlatform.pptx v. 0.2 2013-04-20 Attila Csipa
TOOL- AND STATUSBARSCanvas in full screen mode with status bar: 240 x 302 (320-18) pixels.
Canvas not in full screen mode: 240 x 262 (320-18-40) pixels.
PRACTICAL ISSUES - CLIPPING
PRACTICAL ISSUES - CLIPPING
public void paint(Graphics g) { int width = getWidth(); int height = getHeight(); g.setColor(0xFFFFFF); g.fillRect(0, 0, width, height); g.setColor(0x000000); g.drawLine(0, height/2, width, height/2);g.drawLine(width/2, 0, width/2, height);g.setColor(0xFF0000); g.drawString("Absolute String", 120, 151-(font.getHeight()/2), Graphics.TOP | Graphics.HCENTER); g.setColor(0x00FF00); g.drawString("Relative String", getWidth() / 2, (getHeight() / 2) - (font.getHeight() / 2), Graphics.TOP | Graphics.HCENTER);
}
USING: VIRTUAL KEYBOARDShow keyboard
Hide keyboard
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
CustomKeyboardControl vkbControl = VirtualKeyboard.getCustomKeyboardControl();vkbControl.launch(VirtualKeyboard.SYSTEM_KEYBOARD, VirtualKeyboard.VKB_MODE_ALPHA_LOWER_CASE);
vkbControl.dismiss();
USING: VIRTUAL KEYBOARD
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
public class MainCanvas extends Canvas implements KeyboardVisibilityListener{
private int screenHeight;private int visibleHeight;
public MainCanvas() {setFullScreenMode(true);screenHeight = getHeight(); // Original screen height == 320visibleHeight = screenHeight; // No VKB visibleVirtualKeyboard.setVisibilityListener(this);
}public void showNotify(int keyboardCategory) {
// VKB now visible -> visibleHeight == 142 (or not, NO HARDCODING!)visibleHeight = screenHeight - VirtualKeyboard.getHeight();
}public void hideNotify(int keyboardCategory) {
// VKB now hidden -> visibleHeight == 320visibleHeight = screenHeight;
}}
visibleHeight ~142
visibleHeight == 320
PRACTICAL ISSUES – VIRTUAL KEYBOARD
if (keyboardType.equals("OnekeyBack") || keyboardType.equals("None")) {
// Series 40 full touch or Nokia Asha software platform detected
com.nokia.mid.ui.VirtualKeyboard.hideOpenKeypadCommand(true);}
com.nokia.keyboard.type == “OnekeyBack”
BACK ON PLATFORMS
BACK STEPPINGHierarchical navigation flowSkipped elements
– Options / context menus– Dialogs– Notification Panel– Pickers
Long-press closes current app
BACK BEHAVIOURHW back key – must have
– App main level: exit app– App sub level: back to upper hierarchy level
No SW back button allowed
One exception: games – SW button same behaviour as HW back key- HW button can pause
BACK COMMANDSType “BACK” command: mapped to HW key
– Not visible on screen
CategoryBar: automatic back command– Invisible on Asha Platform → mapped to HW keycmdBack = new IconCommand("Back", Command.BACK, 3, IconCommand.ICON_BACK);frmMain.addCommand(cmdHelp);
HW KEY → BACK COMMANDS
No back command,no category bar:
Default system dialog toclose the app.
Category bar in use(also w/o own back command):Callback to CategoryBar listener
with “back” code (-1).
Traditional back command added:
Not visible on screen,executed via HW key.
EXITING THE APP3 options
– Long-press on back HW button– Swiping out app– Manually within app
public void exit() {destroyApp(true);notifyDestroyed();
}
BACK AND EXIT COMMAND COMBINATIONS• If MIDlet has Exit Command implemented, pressing back key closes the MIDlet.• If MIDlet has Back Command implemented, pressing back key handles the Back Command.• If MIDlet has Back and Exit Commands implemented, Back command is mapped to the back key and
Exit Command to the option menu.• If Exit Command is mapped to the back key, it is normally handled by using commandAction()
method (it is possible, for example, to show confirmation dialog before exiting).• MIDlet is closed by pressing back key, even if the Exit Command is not implemented.• MIDlets can be closed also by swiping horizontally across the screen.• If there is a custom implementation of the back command, the only way to close the MIDlet is to
swipe the screen.• The back key can terminate the MIDlet only if a back or an exit command have not been added to the
current displayable.
© 2013 Nokia DevelopingForTheNewAshaPlatform.pptx v. 0.2 2013-04-20 Attila Csipa
PORTING FROM ANDROID
FEATURESET/RANGE COMPARISON
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
Feature Android Phone Series 40 Touch PhoneCPU 600+ MHz 200-1000 MHzDisplay tech Capacitive Resistive or CapacitiveTouch interaction Multi-point touch Single-touch and Multi-point touch *Display resolution 240x320 upwards 240x320, 240x400Sensors GPS, Proximity, Acceleration GPS, Acceleration *Multitasking Yes NoBackground processing Yes NoLow-level API access Yes LimitedUI Definition Declarative or programmatical ProgrammaticalReady-to-use UI components Android UI Standard LCDUI, LWUITBattery life Fair ExcellentDevelopment platforms Windows, Mac, Linux WindowsIDEs Eclipse Eclipse, NetbeansApplication size limitations 50MB + 4GB 2MB + Persistent Storage
TOOLING SUPPORT
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
Android Series40
Officially supported IDEs Eclipse/IntelliJ Eclipse and NetBeans IDE
Emulator Multiple profiles One profile per SDK
Emulator debugging Yes Yes
On-device debugging Yes Yes
Remote device access No* Yes (RDA)
MEMORY IS GOLDOn Series 40 Memory Limitations: Application JAR file size can’t exceed 5 MB (2 for FT)Java Heap Size is 2 to 4 MB.
Use Nokia Device Matrix for checking exact values: http://www.developer.nokia.com/Devices/Device_specifications/
Option: download of needed resources and caching in RMS
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
WILL THE REAL JAVA PLEASE STAND UP?
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
• Android code runs on the Dalvik virtual machine, which in practice is able to handle most of the standard Java SE code.
• Ashas are based on the commonly used Java ME and MIDP 2.0 specifications• Difference between the two is the version of the Java language used: Android
supports Java 1.6+, but Series 40 runs on Java 1.3.• The Java ME class library is relatively thin compared to the "desktop" flavour of Java,
which means in some cases additional code must be included, e.g. for String or image manipulation operations.
GOOD PORTING CANDIDATES• Content-intensive applications, showing lots of textual content and making use of vertical
scrolling.
• Single-purpose tools utilizing network connectivity: Content aggregators, RSS/News readers; Location-aware applications featuring maps.
• Various business applications.
• Casual games (puzzle, 2D arcade), children's apps (drawing, coloring, touch interaction, soundboards).
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
API COMPARISON
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
Topic Handling in Android Handling in Series 40Touch input View#onTouchEvent,GestureDetector pointerPressed, pointerDragged, pointer
Released (Canvas, CustomItem),GestureInteractiveZone for receiving GestureEvent objects that define the type of the gesture
Google Maps in Android and Nokia Maps in Java ME
MapView MapCanvas, initialised with a Display object
Sensors SensorManager, updates viaListener SensorManager, open a Connection and then get updates via Listener
Network connections HttpUrlConnection, Apache HTTP Client HttpConnectionMessaging SmsManager for sending text messages Sending a TextMessage into
a MessageConnection (Wireless Messaging API)
File access Many methods for accessing the file system in the Context class
Operations via FileConnection (FileConnection API)
Persistent Storage Activity#onSaveInstanceState,SharedPreferences
Persistent storage access via the RecordStore class
Databases for personal information management (PIM)
A number of ContentProviderclasses for various data sources
Accessing contact lists, calendars, and to-do lists via the Personal Information Management (PIM) API
Multimedia playback MediaPlayer (audio+video),SoundPool, JetPlayer
General-purpose Player class (created using Manager) for audio and video
UI PORTING
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
NAVIGATIONTabs = Category bar
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
NAVIGATIONDashboard navigation viaCustom Grid layouts
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
BACK BUTTONAndroid uses HW back keyAsha uses bottom-right iconFull Touch
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
UI ELEMENT EQUIVALENTSFor a detailed list, see
http://www.developer.nokia.com/Resources/Library/Porting_to_Series_40/#!porting-from-android-to-series-40/android-ui-to-s40.html
(for Full Touch at the moment, but also applicable to new Asha due to API similarities)
© 2013 Nokia Porting to Nokia Asha v1.0 March 8, 2013 Attila Csipa
2D AND 3D GAME DEVELOPMENT
GAMES ON ASHAGames are most popular downloads in Nokia StoreCommercialization of games is easier comparing to other types of appsAsha supports both 2D and 3D game development with dedicated APIs, however, 3D should be used cautiously (performance!)
2D GRAPHICS FOR GAMESGame API – part of the standard MIDP 2.X
Package javax.microedition.lcdui.gameContains only 5 classes:
– GameCanvas– Layer– LayerManager– Sprite– TiledLayer
GAMECANVAS• Double buffered• Convenient for minimizing code of game loop• Extends the Canvas class, but provides more control over the painting cycle and
threading• GameCanvas.getGraphics returns a new off-screen Graphics object• The returned Graphics object should be re-used• When all graphics are drawn, GameCanvas.flushGraphics() flushes them to the screen
GAME LOOP
public class MyCanvas extends GameCanvas implements Runnable {
public void run() {
Graphics g = getGraphics();
while(true) {
// respond to user input
// update the game staterespond to key events
flushGraphics();
}
}
}
GRAPHICAL ASSETS• Instead of multiple small images, graphical assets for a game should be represented by
a single image or very few images, virtually separated into multiple areas of similar size.• Such approach dramatically reduces memory usage and simplifies management of
visual elements – backgrounds, characters, game items.
EXAMPLE OF GRAPHICAL ASSETS
Image 1 Image 2
WORKING WITH GRAPHICAL ASSETS
SPRITEAnimated element of the game (character)Define Sequence, DelayFlip, RotateDefine Reference PointDetect Collisions
SPRITE - STAR
SPRITE - LIGHTNING
SPRITE MANAGEMENTThe Sprite class dramatically simplifies sprite management
– Image image = Image.createImage(“mysprite.png”);– Sprite sprite = new Sprite(image, 5,5);
The Sprite class manages movement– sprite.move(10,10);
The Sprite class manages collisions– sprite.collidesWith(otherSprite,false);– sprite.collidesWith(tiledLayer,false);– sprite.collidesWith(otherImage,20,20,false);
SPRITE ANIMATIONThe frames used to create an animated Sprite are provided by a single image file, loaded using an Image object. The Sprite class separates the image into each individual frame of a width and height specified in its constructor and assigns a number to each, starting at 0.
The sequence in which the frames are displayed defaults to the order they where drawn in the original image. However, this can be overridden using the method setFrameSequence(int[] sequence), passing to the method an array of integers, representing the order of the frame numbers.
To achieve the effect of animation, the current frame being displayed on the sprite must be changed. This is done by calling the methods nextFrame() and prevFrame(). These methods simply select the next or previous frame in the frame sequence. If the nextFrame() method is called at the end of the sequence, the first frame in the sequence is displayed. If the prevFrame() method is called at the start of the sequence, the last frame is displayed.
GAME BACKGROUNDS AND LAYERS
Layer– Abstract class, any visual game element
LayerManager– Combines layers together, provides viewport
TiledLayer– Game areas, backgrounds
TILEDLAYER
Tiles are used to create background and foreground spritesTiles can be composed of sub-images to create arbitrary sprites
– Once created the tile works as a whole unitTiles can be animated to create the illusion of movement
– For example, to create the rippling water effectDon’t have Sprite methods
TILES AND LAYERS• LayerManager simplifies tile management:
– Image image = Image.createImage(“/mytile.png”);– LayerManager layerManager = new LayerManager();– TiledLayer tiledLayer = new TiledLayer(cols, rows, image, X, Y);– tiledLayer.fillCells(0,0,cols,rows,1);– layerManager.append(tiledLayer);
• LayerManager paints tiles and sprites in the order that they are appended to manage depth ordering.
tile1 tile2 tile3 tile4mytile.png
new TiledLayer(cols, rows, image, 35, 40);
Static tile set
LAYER MANAGEMENT• Manages a series of layers
– Appends, inserts and removes layers– Controls how layers are rendered to the screen
• View window controls the visible region on the screen– Size (usually fixed to be optimal for the device screen)– Position (used for scrolling user’s view)
• Example: – View window 85x85 pixels, located at (20,20)
(20,20)
85
85
y
x
COLLISION DETECTIONSprite provides methods for detecting collisions with
– Sprites– TiledLayers– Images
You can detect collisions – At the pixel level (slow but accurate).
– Collision detected only if opaque pixels collide– Using Collision rectangles (fast, not as accurate)
To define collition detection, use the following methods– collidesWith(Sprite s, boolean pixelLevel)– collidesWith(TiledLayer t, boolean pixelLevel)– collidesWith(Image img, int x, int y, boolean pixelLevel)
To define collision rectangle, use the following method– defineCollisionRectangle(int x, int y, int width, int height)
3D GRAPHICS APIJSR-184 (M3G) – Mobile 3D GraphicsObject-Oriented 3DScene Graph basedOptional MIDP JSRVery compact APIVery fast developmentOptimized for small memory and budget CPU
LIGHTWEIGHT API, ONLY 30 CLASSES
AnimationControllerAnimationTrackAppearance Background Camera CompositingModeFog Graphics3D Group Image2D
IndexBufferKeyframeSequenceLight Loader Material Mesh MorphingMeshNode Object3D PolygonMode
RayIntersectionSkinnedMeshSprite3D Texture2D Transform Transformable TriangleStripArrayVertexArrayVertexBufferWorld
MORE INFORMATIONOverview
– www.developer.nokia.com/Develop/asha/java/start/Downloads
– SDK: www.developer.nokia.com/Develop/asha/java/tools.xhtml– LWUIT: projects.developer.nokia.com/LWUIT_for_Series_40
Guides– Nokia Asha Design Guidelines: www.developer.nokia.com/Resources/Library/Asha_UI/– Porting guide: www.developer.nokia.com/Resources/Library/Porting_to_Series_40/– Documentation: www.developer.nokia.com/Develop/asha/java/resources/docs/– Training Videos: www.developer.nokia.com/Develop/asha/learning.xhtml– Code Examples: www.developer.nokia.com/Develop/asha/java/resources/code/
SPECIAL THANKS
Michael Samarin
Jukka Silvennoinen
Andreas Jakl
THANK YOUQUESTIONS?